test.cc 553 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017
  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. // Regression test for OSS-Fuzz #508087118: a long Content-Type ran str2tag
  631. // recursively (one stack frame per character) and overflowed the stack.
  632. TEST(Str2tagTest, LongInputDoesNotOverflowStack) {
  633. std::string long_content_type(60000, 'x');
  634. EXPECT_NO_THROW(detail::can_compress_content_type(long_content_type));
  635. }
  636. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  637. Server svr;
  638. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  639. EXPECT_EQ(req.accept_content_types.size(), 3U);
  640. EXPECT_EQ(req.accept_content_types[0], "application/json");
  641. EXPECT_EQ(req.accept_content_types[1], "text/html");
  642. EXPECT_EQ(req.accept_content_types[2], "*/*");
  643. res.set_content("ok", "text/plain");
  644. });
  645. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  646. EXPECT_TRUE(false);
  647. res.set_content("bad request", "text/plain");
  648. });
  649. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  650. auto se = detail::scope_exit([&] {
  651. svr.stop();
  652. listen_thread.join();
  653. ASSERT_FALSE(svr.is_running());
  654. });
  655. svr.wait_until_ready();
  656. Client cli("localhost", PORT);
  657. {
  658. auto res =
  659. cli.Get("/accept_ok",
  660. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::OK_200, res->status);
  663. }
  664. {
  665. auto res = cli.Get("/accept_bad_request",
  666. {{"Accept", "text/html;q=abc,application/json"}});
  667. ASSERT_TRUE(res);
  668. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  669. }
  670. }
  671. TEST(DivideTest, DivideStringTests) {
  672. auto divide = [](const std::string &str, char d) {
  673. std::string lhs;
  674. std::string rhs;
  675. detail::divide(str, d,
  676. [&](const char *lhs_data, std::size_t lhs_size,
  677. const char *rhs_data, std::size_t rhs_size) {
  678. lhs.assign(lhs_data, lhs_size);
  679. rhs.assign(rhs_data, rhs_size);
  680. });
  681. return std::make_pair(std::move(lhs), std::move(rhs));
  682. };
  683. {
  684. const auto res = divide("", '=');
  685. EXPECT_EQ(res.first, "");
  686. EXPECT_EQ(res.second, "");
  687. }
  688. {
  689. const auto res = divide("=", '=');
  690. EXPECT_EQ(res.first, "");
  691. EXPECT_EQ(res.second, "");
  692. }
  693. {
  694. const auto res = divide(" ", '=');
  695. EXPECT_EQ(res.first, " ");
  696. EXPECT_EQ(res.second, "");
  697. }
  698. {
  699. const auto res = divide("a", '=');
  700. EXPECT_EQ(res.first, "a");
  701. EXPECT_EQ(res.second, "");
  702. }
  703. {
  704. const auto res = divide("a=", '=');
  705. EXPECT_EQ(res.first, "a");
  706. EXPECT_EQ(res.second, "");
  707. }
  708. {
  709. const auto res = divide("=b", '=');
  710. EXPECT_EQ(res.first, "");
  711. EXPECT_EQ(res.second, "b");
  712. }
  713. {
  714. const auto res = divide("a=b", '=');
  715. EXPECT_EQ(res.first, "a");
  716. EXPECT_EQ(res.second, "b");
  717. }
  718. {
  719. const auto res = divide("a=b=", '=');
  720. EXPECT_EQ(res.first, "a");
  721. EXPECT_EQ(res.second, "b=");
  722. }
  723. {
  724. const auto res = divide("a=b=c", '=');
  725. EXPECT_EQ(res.first, "a");
  726. EXPECT_EQ(res.second, "b=c");
  727. }
  728. }
  729. TEST(SplitTest, ParseQueryString) {
  730. string s = "key1=val1&key2=val2&key3=val3";
  731. Params dic;
  732. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  733. [&](const char *b, const char *e) {
  734. string key, val;
  735. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  736. if (key.empty()) {
  737. key.assign(b2, e2);
  738. } else {
  739. val.assign(b2, e2);
  740. }
  741. });
  742. dic.emplace(key, val);
  743. });
  744. EXPECT_EQ("val1", dic.find("key1")->second);
  745. EXPECT_EQ("val2", dic.find("key2")->second);
  746. EXPECT_EQ("val3", dic.find("key3")->second);
  747. }
  748. TEST(SplitTest, ParseInvalidQueryTests) {
  749. {
  750. string s = " ";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. {
  756. string s = " = =";
  757. Params dict;
  758. detail::parse_query_text(s, dict);
  759. EXPECT_TRUE(dict.empty());
  760. }
  761. }
  762. TEST(ParseQueryTest, ParseQueryString) {
  763. {
  764. std::string s = "key1=val1&key2=val2&key3=val3";
  765. Params dic;
  766. detail::parse_query_text(s, dic);
  767. EXPECT_EQ("val1", dic.find("key1")->second);
  768. EXPECT_EQ("val2", dic.find("key2")->second);
  769. EXPECT_EQ("val3", dic.find("key3")->second);
  770. }
  771. {
  772. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  773. Params dic;
  774. detail::parse_query_text(s, dic);
  775. EXPECT_EQ("", dic.find("key1")->second);
  776. EXPECT_EQ("val1", dic.find("key2")->second);
  777. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  778. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  779. }
  780. }
  781. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  782. Params dic;
  783. EXPECT_EQ(detail::params_to_query_str(dic), "");
  784. dic.emplace("key1", "val1");
  785. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  786. dic.emplace("key2", "val2");
  787. dic.emplace("key3", "val3");
  788. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  789. }
  790. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  791. string content_type = "multipart/form-data; boundary=something";
  792. string boundary;
  793. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  794. EXPECT_TRUE(ret);
  795. EXPECT_EQ(boundary, "something");
  796. }
  797. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  798. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  799. string boundary;
  800. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  801. EXPECT_TRUE(ret);
  802. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  803. }
  804. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  805. string content_type =
  806. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  807. string boundary;
  808. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  809. EXPECT_TRUE(ret);
  810. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  811. }
  812. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  813. string content_type =
  814. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  815. string boundary;
  816. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  817. EXPECT_TRUE(ret);
  818. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  819. }
  820. TEST(GetHeaderValueTest, DefaultValue) {
  821. Headers headers = {{"Dummy", "Dummy"}};
  822. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  823. EXPECT_STREQ("text/plain", val);
  824. }
  825. TEST(GetHeaderValueTest, DefaultValueInt) {
  826. Headers headers = {{"Dummy", "Dummy"}};
  827. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  828. EXPECT_EQ(100ull, val);
  829. }
  830. TEST(GetHeaderValueTest, RegularValue) {
  831. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  832. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  833. EXPECT_STREQ("text/html", val);
  834. }
  835. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  836. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  837. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  838. EXPECT_STREQ("text/html", val);
  839. }
  840. TEST(GetHeaderValueTest, SetContent) {
  841. Response res;
  842. res.set_content("html", "text/html");
  843. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  844. res.set_content("text", "text/plain");
  845. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  846. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  847. }
  848. TEST(GetHeaderValueTest, RegularValueInt) {
  849. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  851. EXPECT_EQ(100ull, val);
  852. }
  853. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  854. Headers headers = {{"Content-Length", "x"}};
  855. auto is_invalid_value = false;
  856. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  857. is_invalid_value);
  858. EXPECT_EQ(0ull, val);
  859. EXPECT_TRUE(is_invalid_value);
  860. }
  861. TEST(GetHeaderValueTest, Range) {
  862. {
  863. Headers headers = {make_range_header({{1, -1}})};
  864. auto val = detail::get_header_value(headers, "Range", 0, 0);
  865. EXPECT_STREQ("bytes=1-", val);
  866. }
  867. {
  868. Headers headers = {make_range_header({{-1, 1}})};
  869. auto val = detail::get_header_value(headers, "Range", 0, 0);
  870. EXPECT_STREQ("bytes=-1", val);
  871. }
  872. {
  873. Headers headers = {make_range_header({{1, 10}})};
  874. auto val = detail::get_header_value(headers, "Range", 0, 0);
  875. EXPECT_STREQ("bytes=1-10", val);
  876. }
  877. {
  878. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  879. auto val = detail::get_header_value(headers, "Range", 0, 0);
  880. EXPECT_STREQ("bytes=1-10, 100-", val);
  881. }
  882. {
  883. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  884. auto val = detail::get_header_value(headers, "Range", 0, 0);
  885. EXPECT_STREQ("bytes=1-10, 100-200", val);
  886. }
  887. {
  888. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  889. auto val = detail::get_header_value(headers, "Range", 0, 0);
  890. EXPECT_STREQ("bytes=0-0, -1", val);
  891. }
  892. }
  893. TEST(ParseHeaderValueTest, Range) {
  894. {
  895. Ranges ranges;
  896. auto ret = detail::parse_range_header("bytes=1-", ranges);
  897. EXPECT_TRUE(ret);
  898. EXPECT_EQ(1u, ranges.size());
  899. EXPECT_EQ(1u, ranges[0].first);
  900. EXPECT_EQ(-1, ranges[0].second);
  901. }
  902. {
  903. Ranges ranges;
  904. auto ret = detail::parse_range_header("bytes=-1", ranges);
  905. EXPECT_TRUE(ret);
  906. EXPECT_EQ(1u, ranges.size());
  907. EXPECT_EQ(-1, ranges[0].first);
  908. EXPECT_EQ(1u, ranges[0].second);
  909. }
  910. {
  911. Ranges ranges;
  912. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  913. EXPECT_TRUE(ret);
  914. EXPECT_EQ(1u, ranges.size());
  915. EXPECT_EQ(1u, ranges[0].first);
  916. EXPECT_EQ(10u, ranges[0].second);
  917. }
  918. {
  919. Ranges ranges;
  920. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  921. EXPECT_FALSE(ret);
  922. }
  923. {
  924. Ranges ranges;
  925. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  926. EXPECT_TRUE(ret);
  927. EXPECT_EQ(2u, ranges.size());
  928. EXPECT_EQ(1u, ranges[0].first);
  929. EXPECT_EQ(10u, ranges[0].second);
  930. EXPECT_EQ(100u, ranges[1].first);
  931. EXPECT_EQ(-1, ranges[1].second);
  932. }
  933. {
  934. Ranges ranges;
  935. auto ret =
  936. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  937. EXPECT_TRUE(ret);
  938. EXPECT_EQ(3u, ranges.size());
  939. EXPECT_EQ(1u, ranges[0].first);
  940. EXPECT_EQ(10u, ranges[0].second);
  941. EXPECT_EQ(100u, ranges[1].first);
  942. EXPECT_EQ(200u, ranges[1].second);
  943. EXPECT_EQ(300u, ranges[2].first);
  944. EXPECT_EQ(400u, ranges[2].second);
  945. }
  946. {
  947. Ranges 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=0", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  955. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  956. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  957. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  958. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  959. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  960. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  961. EXPECT_TRUE(ranges.empty());
  962. }
  963. }
  964. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  965. Request req;
  966. req.set_header("Accept-Encoding", "gzip");
  967. Response res;
  968. res.set_header("Content-Type", "text/plain");
  969. auto ret = detail::encoding_type(req, res);
  970. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  971. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  972. #else
  973. EXPECT_TRUE(ret == detail::EncodingType::None);
  974. #endif
  975. }
  976. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  977. Request req;
  978. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  979. Response res;
  980. res.set_header("Content-Type", "text/plain");
  981. auto ret = detail::encoding_type(req, res);
  982. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  983. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  984. #elif CPPHTTPLIB_ZLIB_SUPPORT
  985. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  986. #elif CPPHTTPLIB_ZSTD_SUPPORT
  987. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  988. #else
  989. EXPECT_TRUE(ret == detail::EncodingType::None);
  990. #endif
  991. }
  992. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  993. Request req;
  994. req.set_header("Accept-Encoding",
  995. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  996. Response res;
  997. res.set_header("Content-Type", "text/plain");
  998. auto ret = detail::encoding_type(req, res);
  999. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1000. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1001. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1002. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1003. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1004. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1005. #else
  1006. EXPECT_TRUE(ret == detail::EncodingType::None);
  1007. #endif
  1008. }
  1009. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1010. // All supported encodings rejected with q=0 should return None
  1011. Request req;
  1012. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1013. Response res;
  1014. res.set_header("Content-Type", "text/plain");
  1015. auto ret = detail::encoding_type(req, res);
  1016. EXPECT_TRUE(ret == detail::EncodingType::None);
  1017. }
  1018. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1019. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1020. Request req;
  1021. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1022. Response res;
  1023. res.set_header("Content-Type", "text/plain");
  1024. auto ret = detail::encoding_type(req, res);
  1025. EXPECT_TRUE(ret == detail::EncodingType::None);
  1026. }
  1027. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1028. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1029. Request req;
  1030. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1031. Response res;
  1032. res.set_header("Content-Type", "text/plain");
  1033. auto ret = detail::encoding_type(req, res);
  1034. EXPECT_TRUE(ret == detail::EncodingType::None);
  1035. }
  1036. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1037. // RFC 7231: Accept-Encoding values are case-insensitive
  1038. Request req;
  1039. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1040. Response res;
  1041. res.set_header("Content-Type", "text/plain");
  1042. auto ret = detail::encoding_type(req, res);
  1043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1044. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1045. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1049. #else
  1050. EXPECT_TRUE(ret == detail::EncodingType::None);
  1051. #endif
  1052. }
  1053. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1054. // q value should determine priority, not hardcoded order
  1055. Request req;
  1056. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1057. Response res;
  1058. res.set_header("Content-Type", "text/plain");
  1059. auto ret = detail::encoding_type(req, res);
  1060. // gzip has highest q=1.0, so it should be selected even though
  1061. // br and zstd are also supported
  1062. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1063. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1064. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1065. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1066. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1067. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1068. #else
  1069. EXPECT_TRUE(ret == detail::EncodingType::None);
  1070. #endif
  1071. }
  1072. TEST(BufferStreamTest, read) {
  1073. detail::BufferStream strm1;
  1074. Stream &strm = strm1;
  1075. EXPECT_EQ(5, strm.write("hello"));
  1076. char buf[512];
  1077. EXPECT_EQ(2, strm.read(buf, 2));
  1078. EXPECT_EQ('h', buf[0]);
  1079. EXPECT_EQ('e', buf[1]);
  1080. EXPECT_EQ(2, strm.read(buf, 2));
  1081. EXPECT_EQ('l', buf[0]);
  1082. EXPECT_EQ('l', buf[1]);
  1083. EXPECT_EQ(1, strm.read(buf, 1));
  1084. EXPECT_EQ('o', buf[0]);
  1085. EXPECT_EQ(0, strm.read(buf, 1));
  1086. }
  1087. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1088. auto host = "www.httpwatch.com";
  1089. auto ip = hosted_at(host);
  1090. EXPECT_EQ("23.96.13.243", ip);
  1091. std::vector<std::string> addrs;
  1092. hosted_at(host, addrs);
  1093. EXPECT_EQ(1u, addrs.size());
  1094. }
  1095. #if 0 // It depends on each test environment...
  1096. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1097. auto host = "www.youtube.com";
  1098. std::vector<std::string> addrs;
  1099. hosted_at(host, addrs);
  1100. EXPECT_EQ(20u, addrs.size());
  1101. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1102. EXPECT_TRUE(it != addrs.end());
  1103. }
  1104. #endif
  1105. class ChunkedEncodingTest : public ::testing::Test {
  1106. protected:
  1107. ChunkedEncodingTest()
  1108. : cli_(HOST, PORT)
  1109. #ifdef CPPHTTPLIB_SSL_ENABLED
  1110. ,
  1111. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1112. #endif
  1113. {
  1114. cli_.set_connection_timeout(2);
  1115. #ifdef CPPHTTPLIB_SSL_ENABLED
  1116. cli_.enable_server_certificate_verification(false);
  1117. #endif
  1118. }
  1119. virtual void SetUp() {
  1120. read_file("./image.jpg", image_data_);
  1121. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1122. res.set_content("Hello World!", "text/plain");
  1123. });
  1124. svr_.Get(
  1125. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1126. res.set_chunked_content_provider(
  1127. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1128. size_t remaining = image_data_.size() - offset;
  1129. if (remaining == 0) {
  1130. sink.done();
  1131. } else {
  1132. constexpr size_t CHUNK_SIZE = 1024;
  1133. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1134. sink.write(&image_data_[offset], send_size);
  1135. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1136. }
  1137. return true;
  1138. });
  1139. });
  1140. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1141. svr_.wait_until_ready();
  1142. }
  1143. virtual void TearDown() {
  1144. svr_.stop();
  1145. if (!request_threads_.empty()) {
  1146. std::this_thread::sleep_for(std::chrono::seconds(1));
  1147. for (auto &t : request_threads_) {
  1148. t.join();
  1149. }
  1150. }
  1151. t_.join();
  1152. }
  1153. #ifdef CPPHTTPLIB_SSL_ENABLED
  1154. SSLClient cli_;
  1155. SSLServer svr_;
  1156. #else
  1157. Client cli_;
  1158. Server svr_;
  1159. #endif
  1160. thread t_;
  1161. std::vector<thread> request_threads_;
  1162. std::string image_data_;
  1163. };
  1164. TEST_F(ChunkedEncodingTest, NormalGet) {
  1165. auto res = cli_.Get("/chunked");
  1166. ASSERT_TRUE(res);
  1167. std::string out;
  1168. read_file("./image.jpg", out);
  1169. EXPECT_EQ(StatusCode::OK_200, res->status);
  1170. EXPECT_EQ(out, res->body);
  1171. }
  1172. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1173. std::string body;
  1174. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1175. body.append(data, data_length);
  1176. return true;
  1177. });
  1178. ASSERT_TRUE(res);
  1179. std::string out;
  1180. read_file("./image.jpg", out);
  1181. EXPECT_EQ(StatusCode::OK_200, res->status);
  1182. EXPECT_EQ(out, body);
  1183. }
  1184. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1185. std::string body;
  1186. auto res = cli_.Get(
  1187. "/chunked",
  1188. [&](const Response &response) {
  1189. EXPECT_EQ(StatusCode::OK_200, response.status);
  1190. return true;
  1191. },
  1192. [&](const char *data, size_t data_length) {
  1193. body.append(data, data_length);
  1194. return true;
  1195. });
  1196. ASSERT_TRUE(res);
  1197. std::string out;
  1198. read_file("./image.jpg", out);
  1199. EXPECT_EQ(StatusCode::OK_200, res->status);
  1200. EXPECT_EQ(out, body);
  1201. }
  1202. TEST(RangeTest, FromHTTPBin_Online) {
  1203. auto host = "httpbingo.org";
  1204. auto path = std::string{"/range/32"};
  1205. #ifdef CPPHTTPLIB_SSL_ENABLED
  1206. auto port = 443;
  1207. SSLClient cli(host, port);
  1208. #else
  1209. auto port = 80;
  1210. Client cli(host, port);
  1211. #endif
  1212. cli.set_connection_timeout(5);
  1213. {
  1214. auto res = cli.Get(path);
  1215. ASSERT_TRUE(res);
  1216. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1217. EXPECT_EQ(StatusCode::OK_200, res->status);
  1218. }
  1219. {
  1220. Headers headers = {make_range_header({{1, -1}})};
  1221. auto res = cli.Get(path, headers);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1224. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1225. }
  1226. {
  1227. Headers headers = {make_range_header({{1, 10}})};
  1228. auto res = cli.Get(path, headers);
  1229. ASSERT_TRUE(res);
  1230. EXPECT_EQ("bcdefghijk", res->body);
  1231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1232. }
  1233. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1234. // entire resource, while the original httpbin returned 200. Both are
  1235. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1236. {
  1237. Headers headers = {make_range_header({{0, 31}})};
  1238. auto res = cli.Get(path, headers);
  1239. ASSERT_TRUE(res);
  1240. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1241. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1242. res->status == StatusCode::PartialContent_206);
  1243. }
  1244. {
  1245. Headers headers = {make_range_header({{0, -1}})};
  1246. auto res = cli.Get(path, headers);
  1247. ASSERT_TRUE(res);
  1248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1249. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1250. res->status == StatusCode::PartialContent_206);
  1251. }
  1252. // go-httpbin returns 206 with clamped range for over-range requests,
  1253. // while the original httpbin returned 416. Both behaviors are observed
  1254. // in real servers, so we only verify the request succeeds.
  1255. {
  1256. Headers headers = {make_range_header({{0, 32}})};
  1257. auto res = cli.Get(path, headers);
  1258. ASSERT_TRUE(res);
  1259. }
  1260. }
  1261. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1262. auto host = "unresolvableaddress.local";
  1263. auto path = std::string{"/"};
  1264. #ifdef CPPHTTPLIB_SSL_ENABLED
  1265. auto port = 443;
  1266. SSLClient cli(host, port);
  1267. #else
  1268. auto port = 80;
  1269. Client cli(host, port);
  1270. #endif
  1271. cli.set_connection_timeout(1);
  1272. {
  1273. auto res = cli.Get(path);
  1274. ASSERT_FALSE(res);
  1275. }
  1276. std::this_thread::sleep_for(std::chrono::seconds(8));
  1277. }
  1278. #if defined(__linux__) && defined(__GLIBC__) && \
  1279. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1280. // Forward declaration: in split builds split.py strips `inline` and moves the
  1281. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1282. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1283. // against the symbol in both header-only and split builds.
  1284. namespace httplib {
  1285. namespace detail {
  1286. int getaddrinfo_with_timeout(const char *node, const char *service,
  1287. const struct addrinfo *hints,
  1288. struct addrinfo **res, time_t timeout_sec);
  1289. } // namespace detail
  1290. } // namespace httplib
  1291. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1292. //
  1293. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1294. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1295. // gai_suspend() call hits the connection timeout the function calls
  1296. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1297. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1298. // still alive and still references the now-destroyed stack frame.
  1299. //
  1300. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1301. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1302. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1303. // and runs them in a container.
  1304. namespace {
  1305. bool should_run_issue_2431_tests() {
  1306. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1307. return v && *v && std::string(v) != "0";
  1308. }
  1309. std::string unique_unresolvable_host(int n) {
  1310. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1311. // glibc still asks the configured nameserver — which is exactly the path
  1312. // we want to exercise. A unique label per call avoids the resolver cache.
  1313. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1314. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1315. std::to_string(n) + ".invalid";
  1316. }
  1317. } // namespace
  1318. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1319. if (!should_run_issue_2431_tests()) {
  1320. GTEST_SKIP()
  1321. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1322. }
  1323. for (int i = 0; i < 8; ++i) {
  1324. struct addrinfo hints;
  1325. memset(&hints, 0, sizeof(hints));
  1326. hints.ai_family = AF_UNSPEC;
  1327. hints.ai_socktype = SOCK_STREAM;
  1328. auto host = unique_unresolvable_host(i);
  1329. struct addrinfo *result = nullptr;
  1330. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1331. &result, /*timeout_sec=*/1);
  1332. if (rc == 0 && result) { freeaddrinfo(result); }
  1333. }
  1334. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1335. // stack region they still believe holds their gaicb.
  1336. std::this_thread::sleep_for(std::chrono::seconds(3));
  1337. }
  1338. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1339. if (!should_run_issue_2431_tests()) {
  1340. GTEST_SKIP()
  1341. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1342. }
  1343. std::atomic<bool> stop{false};
  1344. std::vector<std::thread> threads;
  1345. for (int t = 0; t < 8; ++t) {
  1346. threads.emplace_back([t, &stop] {
  1347. int i = 0;
  1348. while (!stop.load(std::memory_order_relaxed)) {
  1349. struct addrinfo hints;
  1350. memset(&hints, 0, sizeof(hints));
  1351. hints.ai_family = AF_UNSPEC;
  1352. hints.ai_socktype = SOCK_STREAM;
  1353. auto host = unique_unresolvable_host(t * 100000 + i++);
  1354. struct addrinfo *result = nullptr;
  1355. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1356. &result, /*timeout_sec=*/1);
  1357. if (rc == 0 && result) { freeaddrinfo(result); }
  1358. }
  1359. });
  1360. }
  1361. std::this_thread::sleep_for(std::chrono::seconds(8));
  1362. stop.store(true, std::memory_order_relaxed);
  1363. for (auto &th : threads) {
  1364. th.join();
  1365. }
  1366. std::this_thread::sleep_for(std::chrono::seconds(3));
  1367. }
  1368. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1369. if (!should_run_issue_2431_tests()) {
  1370. GTEST_SKIP()
  1371. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1372. }
  1373. std::atomic<bool> stop{false};
  1374. std::vector<std::thread> threads;
  1375. for (int t = 0; t < 8; ++t) {
  1376. threads.emplace_back([t, &stop] {
  1377. int i = 0;
  1378. while (!stop.load(std::memory_order_relaxed)) {
  1379. auto host = unique_unresolvable_host(t * 100000 + i++);
  1380. Client cli(host, 80);
  1381. cli.set_connection_timeout(1, 0);
  1382. cli.set_read_timeout(1, 0);
  1383. cli.set_write_timeout(1, 0);
  1384. (void)cli.Get("/");
  1385. }
  1386. });
  1387. }
  1388. std::this_thread::sleep_for(std::chrono::seconds(8));
  1389. stop.store(true, std::memory_order_relaxed);
  1390. for (auto &th : threads) {
  1391. th.join();
  1392. }
  1393. std::this_thread::sleep_for(std::chrono::seconds(3));
  1394. }
  1395. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1396. TEST(ConnectionErrorTest, InvalidHost) {
  1397. auto host = "-abcde.com";
  1398. #ifdef CPPHTTPLIB_SSL_ENABLED
  1399. auto port = 443;
  1400. SSLClient cli(host, port);
  1401. #else
  1402. auto port = 80;
  1403. Client cli(host, port);
  1404. #endif
  1405. cli.set_connection_timeout(std::chrono::seconds(2));
  1406. auto res = cli.Get("/");
  1407. ASSERT_TRUE(!res);
  1408. EXPECT_EQ(Error::Connection, res.error());
  1409. }
  1410. TEST(ConnectionErrorTest, InvalidHost2) {
  1411. auto host = "httpcan.org/";
  1412. #ifdef CPPHTTPLIB_SSL_ENABLED
  1413. SSLClient cli(host);
  1414. #else
  1415. Client cli(host);
  1416. #endif
  1417. cli.set_connection_timeout(std::chrono::seconds(2));
  1418. auto res = cli.Get("/");
  1419. ASSERT_TRUE(!res);
  1420. EXPECT_EQ(Error::Connection, res.error());
  1421. }
  1422. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1423. auto host = "httpcan.org/";
  1424. #ifdef CPPHTTPLIB_SSL_ENABLED
  1425. SSLClient cli(host);
  1426. #else
  1427. Client cli(host);
  1428. #endif
  1429. cli.set_connection_timeout(std::chrono::seconds(2));
  1430. auto res = cli.Get("/");
  1431. ASSERT_TRUE(!res);
  1432. stringstream s;
  1433. s << "error code: " << res.error();
  1434. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1435. }
  1436. TEST(ConnectionErrorTest, InvalidPort) {
  1437. auto host = "localhost";
  1438. auto port = 44380;
  1439. #ifdef CPPHTTPLIB_SSL_ENABLED
  1440. SSLClient cli(host, port);
  1441. #else
  1442. Client cli(host, port);
  1443. #endif
  1444. cli.set_connection_timeout(std::chrono::seconds(2));
  1445. auto res = cli.Get("/");
  1446. ASSERT_TRUE(!res);
  1447. EXPECT_TRUE(Error::Connection == res.error() ||
  1448. Error::ConnectionTimeout == res.error());
  1449. }
  1450. TEST(ConnectionErrorTest, Timeout_Online) {
  1451. auto host = "google.com";
  1452. #ifdef CPPHTTPLIB_SSL_ENABLED
  1453. auto port = 44380;
  1454. SSLClient cli(host, port);
  1455. #else
  1456. auto port = 8080;
  1457. Client cli(host, port);
  1458. #endif
  1459. cli.set_connection_timeout(std::chrono::seconds(2));
  1460. // only probe one address type so that the error reason
  1461. // correlates to the timed-out IPv4, not the unsupported
  1462. // IPv6 connection attempt
  1463. cli.set_address_family(AF_INET);
  1464. auto res = cli.Get("/");
  1465. ASSERT_TRUE(!res);
  1466. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1467. }
  1468. TEST(CancelTest, NoCancel_Online) {
  1469. auto host = "httpbingo.org";
  1470. auto path = std::string{"/range/32"};
  1471. #ifdef CPPHTTPLIB_SSL_ENABLED
  1472. auto port = 443;
  1473. SSLClient cli(host, port);
  1474. #else
  1475. auto port = 80;
  1476. Client cli(host, port);
  1477. #endif
  1478. cli.set_connection_timeout(std::chrono::seconds(5));
  1479. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1480. ASSERT_TRUE(res);
  1481. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1482. EXPECT_EQ(StatusCode::OK_200, res->status);
  1483. }
  1484. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1485. // Use /bytes with a large payload so that the DownloadProgress callback
  1486. // (which only fires for Content-Length responses) is invoked before the
  1487. // entire body is received, giving cancellation a chance to fire.
  1488. auto host = "httpbingo.org";
  1489. auto path = std::string{"/bytes/524288"};
  1490. #ifdef CPPHTTPLIB_SSL_ENABLED
  1491. auto port = 443;
  1492. SSLClient cli(host, port);
  1493. #else
  1494. auto port = 80;
  1495. Client cli(host, port);
  1496. #endif
  1497. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1498. cli.set_connection_timeout(std::chrono::seconds(5));
  1499. ASSERT_TRUE(!res);
  1500. EXPECT_EQ(Error::Canceled, res.error());
  1501. }
  1502. TEST(CancelTest, WithCancelLargePayload_Online) {
  1503. auto host = "httpbingo.org";
  1504. auto path = std::string{"/bytes/524288"};
  1505. #ifdef CPPHTTPLIB_SSL_ENABLED
  1506. auto port = 443;
  1507. SSLClient cli(host, port);
  1508. #else
  1509. auto port = 80;
  1510. Client cli(host, port);
  1511. #endif
  1512. cli.set_connection_timeout(std::chrono::seconds(5));
  1513. uint32_t count = 0;
  1514. auto res =
  1515. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1516. ASSERT_TRUE(!res);
  1517. EXPECT_EQ(Error::Canceled, res.error());
  1518. }
  1519. TEST(CancelTest, NoCancelPost) {
  1520. Server svr;
  1521. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1522. res.set_content("Hello World!", "text/plain");
  1523. });
  1524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1525. auto se = detail::scope_exit([&] {
  1526. svr.stop();
  1527. thread.join();
  1528. ASSERT_FALSE(svr.is_running());
  1529. });
  1530. svr.wait_until_ready();
  1531. Client cli(HOST, PORT);
  1532. cli.set_connection_timeout(std::chrono::seconds(5));
  1533. auto res =
  1534. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1535. "application/json", [](uint64_t, uint64_t) { return true; });
  1536. ASSERT_TRUE(res);
  1537. EXPECT_EQ("Hello World!", res->body);
  1538. EXPECT_EQ(StatusCode::OK_200, res->status);
  1539. }
  1540. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1541. Server svr;
  1542. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1543. res.set_content("Hello World!", "text/plain");
  1544. });
  1545. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1546. auto se = detail::scope_exit([&] {
  1547. svr.stop();
  1548. thread.join();
  1549. ASSERT_FALSE(svr.is_running());
  1550. });
  1551. svr.wait_until_ready();
  1552. Client cli(HOST, PORT);
  1553. cli.set_connection_timeout(std::chrono::seconds(5));
  1554. auto res =
  1555. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1556. "application/json", [](uint64_t, uint64_t) { return false; });
  1557. ASSERT_TRUE(!res);
  1558. EXPECT_EQ(Error::Canceled, res.error());
  1559. }
  1560. TEST(CancelTest, WithCancelLargePayloadPost) {
  1561. Server svr;
  1562. svr.set_payload_max_length(200 * 1024 * 1024);
  1563. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1564. res.set_content(LARGE_DATA, "text/plain");
  1565. });
  1566. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1567. auto se = detail::scope_exit([&] {
  1568. svr.stop();
  1569. thread.join();
  1570. ASSERT_FALSE(svr.is_running());
  1571. });
  1572. svr.wait_until_ready();
  1573. Client cli(HOST, PORT);
  1574. cli.set_payload_max_length(200 * 1024 * 1024);
  1575. cli.set_connection_timeout(std::chrono::seconds(5));
  1576. auto res =
  1577. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1578. "application/json", [](uint64_t, uint64_t) { return false; });
  1579. ASSERT_TRUE(!res);
  1580. EXPECT_EQ(Error::Canceled, res.error());
  1581. }
  1582. TEST(CancelTest, NoCancelPut) {
  1583. Server svr;
  1584. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1585. res.set_content("Hello World!", "text/plain");
  1586. });
  1587. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1588. auto se = detail::scope_exit([&] {
  1589. svr.stop();
  1590. thread.join();
  1591. ASSERT_FALSE(svr.is_running());
  1592. });
  1593. svr.wait_until_ready();
  1594. Client cli(HOST, PORT);
  1595. cli.set_connection_timeout(std::chrono::seconds(5));
  1596. auto res =
  1597. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1598. "application/json", [](uint64_t, uint64_t) { return true; });
  1599. ASSERT_TRUE(res);
  1600. EXPECT_EQ("Hello World!", res->body);
  1601. EXPECT_EQ(StatusCode::OK_200, res->status);
  1602. }
  1603. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1604. Server svr;
  1605. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1606. res.set_content("Hello World!", "text/plain");
  1607. });
  1608. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1609. auto se = detail::scope_exit([&] {
  1610. svr.stop();
  1611. thread.join();
  1612. ASSERT_FALSE(svr.is_running());
  1613. });
  1614. svr.wait_until_ready();
  1615. Client cli(HOST, PORT);
  1616. cli.set_connection_timeout(std::chrono::seconds(5));
  1617. auto res =
  1618. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1619. "application/json", [](uint64_t, uint64_t) { return false; });
  1620. ASSERT_TRUE(!res);
  1621. EXPECT_EQ(Error::Canceled, res.error());
  1622. }
  1623. TEST(CancelTest, WithCancelLargePayloadPut) {
  1624. Server svr;
  1625. svr.set_payload_max_length(200 * 1024 * 1024);
  1626. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1627. res.set_content(LARGE_DATA, "text/plain");
  1628. });
  1629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1630. auto se = detail::scope_exit([&] {
  1631. svr.stop();
  1632. thread.join();
  1633. ASSERT_FALSE(svr.is_running());
  1634. });
  1635. svr.wait_until_ready();
  1636. Client cli(HOST, PORT);
  1637. cli.set_payload_max_length(200 * 1024 * 1024);
  1638. cli.set_connection_timeout(std::chrono::seconds(5));
  1639. auto res =
  1640. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1641. "application/json", [](uint64_t, uint64_t) { return false; });
  1642. ASSERT_TRUE(!res);
  1643. EXPECT_EQ(Error::Canceled, res.error());
  1644. }
  1645. TEST(CancelTest, NoCancelPatch) {
  1646. Server svr;
  1647. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1648. res.set_content("Hello World!", "text/plain");
  1649. });
  1650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1651. auto se = detail::scope_exit([&] {
  1652. svr.stop();
  1653. thread.join();
  1654. ASSERT_FALSE(svr.is_running());
  1655. });
  1656. svr.wait_until_ready();
  1657. Client cli(HOST, PORT);
  1658. cli.set_connection_timeout(std::chrono::seconds(5));
  1659. auto res =
  1660. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1661. "application/json", [](uint64_t, uint64_t) { return true; });
  1662. ASSERT_TRUE(res);
  1663. EXPECT_EQ("Hello World!", res->body);
  1664. EXPECT_EQ(StatusCode::OK_200, res->status);
  1665. }
  1666. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1667. Server svr;
  1668. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1669. res.set_content("Hello World!", "text/plain");
  1670. });
  1671. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1672. auto se = detail::scope_exit([&] {
  1673. svr.stop();
  1674. thread.join();
  1675. ASSERT_FALSE(svr.is_running());
  1676. });
  1677. svr.wait_until_ready();
  1678. Client cli(HOST, PORT);
  1679. cli.set_connection_timeout(std::chrono::seconds(5));
  1680. auto res =
  1681. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1682. "application/json", [](uint64_t, uint64_t) { return false; });
  1683. ASSERT_TRUE(!res);
  1684. EXPECT_EQ(Error::Canceled, res.error());
  1685. }
  1686. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1687. Server svr;
  1688. svr.set_payload_max_length(200 * 1024 * 1024);
  1689. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1690. res.set_content(LARGE_DATA, "text/plain");
  1691. });
  1692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1693. auto se = detail::scope_exit([&] {
  1694. svr.stop();
  1695. thread.join();
  1696. ASSERT_FALSE(svr.is_running());
  1697. });
  1698. svr.wait_until_ready();
  1699. Client cli(HOST, PORT);
  1700. cli.set_payload_max_length(200 * 1024 * 1024);
  1701. cli.set_connection_timeout(std::chrono::seconds(5));
  1702. auto res =
  1703. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1704. "application/json", [](uint64_t, uint64_t) { return false; });
  1705. ASSERT_TRUE(!res);
  1706. EXPECT_EQ(Error::Canceled, res.error());
  1707. }
  1708. TEST(CancelTest, NoCancelDelete) {
  1709. Server svr;
  1710. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1711. res.set_content("Hello World!", "text/plain");
  1712. });
  1713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1714. auto se = detail::scope_exit([&] {
  1715. svr.stop();
  1716. thread.join();
  1717. ASSERT_FALSE(svr.is_running());
  1718. });
  1719. svr.wait_until_ready();
  1720. Client cli(HOST, PORT);
  1721. cli.set_connection_timeout(std::chrono::seconds(5));
  1722. auto res =
  1723. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1724. "application/json", [](uint64_t, uint64_t) { return true; });
  1725. ASSERT_TRUE(res);
  1726. EXPECT_EQ("Hello World!", res->body);
  1727. EXPECT_EQ(StatusCode::OK_200, res->status);
  1728. }
  1729. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1730. Server svr;
  1731. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1732. res.set_content("Hello World!", "text/plain");
  1733. });
  1734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1735. auto se = detail::scope_exit([&] {
  1736. svr.stop();
  1737. thread.join();
  1738. ASSERT_FALSE(svr.is_running());
  1739. });
  1740. svr.wait_until_ready();
  1741. Client cli(HOST, PORT);
  1742. cli.set_connection_timeout(std::chrono::seconds(5));
  1743. auto res =
  1744. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1745. "application/json", [](uint64_t, uint64_t) { return false; });
  1746. ASSERT_TRUE(!res);
  1747. EXPECT_EQ(Error::Canceled, res.error());
  1748. }
  1749. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1750. Server svr;
  1751. svr.set_payload_max_length(200 * 1024 * 1024);
  1752. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1753. res.set_content(LARGE_DATA, "text/plain");
  1754. });
  1755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1756. auto se = detail::scope_exit([&] {
  1757. svr.stop();
  1758. thread.join();
  1759. ASSERT_FALSE(svr.is_running());
  1760. });
  1761. svr.wait_until_ready();
  1762. Client cli(HOST, PORT);
  1763. cli.set_payload_max_length(200 * 1024 * 1024);
  1764. cli.set_connection_timeout(std::chrono::seconds(5));
  1765. auto res =
  1766. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1767. "application/json", [](uint64_t, uint64_t) { return false; });
  1768. ASSERT_TRUE(!res);
  1769. EXPECT_EQ(Error::Canceled, res.error());
  1770. }
  1771. static std::string remove_whitespace(const std::string &input) {
  1772. std::string output;
  1773. output.reserve(input.size());
  1774. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1775. [](unsigned char c) { return !std::isspace(c); });
  1776. return output;
  1777. }
  1778. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1779. auto host = "httpbingo.org";
  1780. auto path = std::string{"/basic-auth/hello/world"};
  1781. #ifdef CPPHTTPLIB_SSL_ENABLED
  1782. auto port = 443;
  1783. SSLClient cli(host, port);
  1784. #else
  1785. auto port = 80;
  1786. Client cli(host, port);
  1787. #endif
  1788. {
  1789. auto res = cli.Get(path);
  1790. ASSERT_TRUE(res);
  1791. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1792. }
  1793. {
  1794. auto res =
  1795. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1796. ASSERT_TRUE(res);
  1797. auto body = remove_whitespace(res->body);
  1798. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1799. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1800. EXPECT_EQ(StatusCode::OK_200, res->status);
  1801. }
  1802. {
  1803. cli.set_basic_auth("hello", "world");
  1804. auto res = cli.Get(path);
  1805. ASSERT_TRUE(res);
  1806. auto body = remove_whitespace(res->body);
  1807. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1808. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1809. EXPECT_EQ(StatusCode::OK_200, res->status);
  1810. }
  1811. {
  1812. cli.set_basic_auth("hello", "bad");
  1813. auto res = cli.Get(path);
  1814. ASSERT_TRUE(res);
  1815. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1816. }
  1817. {
  1818. cli.set_basic_auth("bad", "world");
  1819. auto res = cli.Get(path);
  1820. ASSERT_TRUE(res);
  1821. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1822. }
  1823. }
  1824. #ifdef CPPHTTPLIB_SSL_ENABLED
  1825. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1826. auto host = "httpbingo.org";
  1827. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1828. auto paths = std::vector<std::string>{
  1829. "/digest-auth/auth/hello/world/MD5",
  1830. "/digest-auth/auth/hello/world/SHA-256",
  1831. };
  1832. auto port = 443;
  1833. SSLClient cli(host, port);
  1834. {
  1835. auto res = cli.Get(unauth_path);
  1836. ASSERT_TRUE(res);
  1837. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1838. }
  1839. {
  1840. cli.set_digest_auth("hello", "world");
  1841. for (const auto &path : paths) {
  1842. auto res = cli.Get(path.c_str());
  1843. ASSERT_TRUE(res);
  1844. auto body = remove_whitespace(res->body);
  1845. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1846. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1847. EXPECT_EQ(StatusCode::OK_200, res->status);
  1848. }
  1849. cli.set_digest_auth("hello", "bad");
  1850. for (const auto &path : paths) {
  1851. auto res = cli.Get(path.c_str());
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1854. }
  1855. }
  1856. }
  1857. #endif
  1858. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1859. auto host = "google.com";
  1860. auto another_host = "example.com";
  1861. auto wrong_ip = "0.0.0.0";
  1862. #ifdef CPPHTTPLIB_SSL_ENABLED
  1863. SSLClient cli(host);
  1864. #else
  1865. Client cli(host);
  1866. #endif
  1867. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1868. auto res = cli.Get("/");
  1869. ASSERT_TRUE(res);
  1870. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1871. }
  1872. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1873. auto host = "google.com";
  1874. auto wrong_ip = "0.0.0.0";
  1875. #ifdef CPPHTTPLIB_SSL_ENABLED
  1876. SSLClient cli(host);
  1877. #else
  1878. Client cli(host);
  1879. #endif
  1880. cli.set_hostname_addr_map({{host, wrong_ip}});
  1881. auto res = cli.Get("/");
  1882. ASSERT_TRUE(!res);
  1883. EXPECT_EQ(Error::Connection, res.error());
  1884. }
  1885. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1886. auto host = "httpbingo.org";
  1887. auto path = std::string{"/absolute-redirect/3"};
  1888. #ifdef CPPHTTPLIB_SSL_ENABLED
  1889. SSLClient cli(host);
  1890. #else
  1891. Client cli(host);
  1892. #endif
  1893. cli.set_follow_location(true);
  1894. auto res = cli.Get(path);
  1895. ASSERT_TRUE(res);
  1896. EXPECT_EQ(StatusCode::OK_200, res->status);
  1897. }
  1898. TEST(RedirectTest, Redirect_Online) {
  1899. auto host = "httpbingo.org";
  1900. auto path = std::string{"/redirect/3"};
  1901. #ifdef CPPHTTPLIB_SSL_ENABLED
  1902. SSLClient cli(host);
  1903. #else
  1904. Client cli(host);
  1905. #endif
  1906. cli.set_follow_location(true);
  1907. auto res = cli.Get(path);
  1908. ASSERT_TRUE(res);
  1909. EXPECT_EQ(StatusCode::OK_200, res->status);
  1910. }
  1911. TEST(RelativeRedirectTest, Redirect_Online) {
  1912. auto host = "httpbingo.org";
  1913. auto path = std::string{"/relative-redirect/3"};
  1914. #ifdef CPPHTTPLIB_SSL_ENABLED
  1915. SSLClient cli(host);
  1916. #else
  1917. Client cli(host);
  1918. #endif
  1919. cli.set_follow_location(true);
  1920. auto res = cli.Get(path);
  1921. ASSERT_TRUE(res);
  1922. EXPECT_EQ(StatusCode::OK_200, res->status);
  1923. }
  1924. TEST(TooManyRedirectTest, Redirect_Online) {
  1925. auto host = "httpbingo.org";
  1926. auto path = std::string{"/redirect/21"};
  1927. #ifdef CPPHTTPLIB_SSL_ENABLED
  1928. SSLClient cli(host);
  1929. #else
  1930. Client cli(host);
  1931. #endif
  1932. cli.set_follow_location(true);
  1933. auto res = cli.Get(path);
  1934. ASSERT_TRUE(!res);
  1935. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1936. }
  1937. #ifdef CPPHTTPLIB_SSL_ENABLED
  1938. TEST(YahooRedirectTest, Redirect_Online) {
  1939. Client cli("yahoo.com");
  1940. auto res = cli.Get("/");
  1941. ASSERT_TRUE(res);
  1942. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1943. cli.set_follow_location(true);
  1944. res = cli.Get("/");
  1945. ASSERT_TRUE(res);
  1946. EXPECT_EQ(StatusCode::OK_200, res->status);
  1947. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1948. }
  1949. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1950. #define REDIR_HOST "httpbingo.org"
  1951. #define REDIR_PATH "/redirect-to"
  1952. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1953. SSLClient cli(REDIR_HOST);
  1954. cli.set_follow_location(true);
  1955. auto res =
  1956. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1957. ASSERT_TRUE(res);
  1958. EXPECT_EQ(StatusCode::OK_200, res->status);
  1959. }
  1960. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1961. SSLClient cli(REDIR_HOST);
  1962. cli.set_follow_location(true);
  1963. Params params;
  1964. params.emplace("url", "http://example.com");
  1965. params.emplace("status_code", "302");
  1966. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1967. ASSERT_TRUE(res);
  1968. EXPECT_EQ(StatusCode::OK_200, res->status);
  1969. }
  1970. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1971. SSLClient cli(REDIR_HOST);
  1972. cli.set_follow_location(true);
  1973. Params params;
  1974. params.emplace("url", "http://example.com");
  1975. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1976. ASSERT_TRUE(res);
  1977. EXPECT_EQ(StatusCode::OK_200, res->status);
  1978. }
  1979. TEST(UrlWithSpace, Redirect_Online) {
  1980. SSLClient cli("edge.forgecdn.net");
  1981. cli.set_follow_location(true);
  1982. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1986. }
  1987. #endif
  1988. #if !defined(_WIN32) && !defined(_WIN64)
  1989. TEST(ReceiveSignals, Signal) {
  1990. auto setupSignalHandlers = []() {
  1991. struct sigaction act;
  1992. sigemptyset(&act.sa_mask);
  1993. act.sa_flags = SA_SIGINFO;
  1994. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1995. switch (sig) {
  1996. case SIGINT:
  1997. default: break;
  1998. }
  1999. };
  2000. ::sigaction(SIGINT, &act, nullptr);
  2001. };
  2002. Server svr;
  2003. int port = 0;
  2004. auto thread = std::thread([&]() {
  2005. setupSignalHandlers();
  2006. port = svr.bind_to_any_port(HOST);
  2007. svr.listen_after_bind();
  2008. });
  2009. auto se = detail::scope_exit([&] {
  2010. svr.stop();
  2011. thread.join();
  2012. ASSERT_FALSE(svr.is_running());
  2013. });
  2014. svr.wait_until_ready();
  2015. ASSERT_TRUE(svr.is_running());
  2016. pthread_kill(thread.native_handle(), SIGINT);
  2017. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2018. ASSERT_TRUE(svr.is_running());
  2019. }
  2020. #endif
  2021. TEST(RedirectToDifferentPort, Redirect) {
  2022. Server svr1;
  2023. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2024. res.set_content("Hello World!", "text/plain");
  2025. });
  2026. int svr1_port = 0;
  2027. auto thread1 = std::thread([&]() {
  2028. svr1_port = svr1.bind_to_any_port(HOST);
  2029. svr1.listen_after_bind();
  2030. });
  2031. Server svr2;
  2032. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2033. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2034. });
  2035. int svr2_port = 0;
  2036. auto thread2 = std::thread([&]() {
  2037. svr2_port = svr2.bind_to_any_port(HOST);
  2038. svr2.listen_after_bind();
  2039. });
  2040. auto se = detail::scope_exit([&] {
  2041. svr2.stop();
  2042. thread2.join();
  2043. svr1.stop();
  2044. thread1.join();
  2045. ASSERT_FALSE(svr2.is_running());
  2046. ASSERT_FALSE(svr1.is_running());
  2047. });
  2048. svr1.wait_until_ready();
  2049. svr2.wait_until_ready();
  2050. Client cli("localhost", svr2_port);
  2051. cli.set_follow_location(true);
  2052. auto res = cli.Get("/2");
  2053. ASSERT_TRUE(res);
  2054. EXPECT_EQ(StatusCode::OK_200, res->status);
  2055. EXPECT_EQ("Hello World!", res->body);
  2056. }
  2057. static void
  2058. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2059. Server svr1;
  2060. std::string captured_authorization;
  2061. svr1.Get("/target", [&](const Request &req, Response &res) {
  2062. captured_authorization = req.get_header_value("Authorization");
  2063. res.set_content("OK", "text/plain");
  2064. });
  2065. int svr1_port = 0;
  2066. auto thread1 = std::thread([&]() {
  2067. svr1_port = svr1.bind_to_any_port(HOST);
  2068. svr1.listen_after_bind();
  2069. });
  2070. Server svr2;
  2071. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2072. res.set_redirect(
  2073. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2074. });
  2075. int svr2_port = 0;
  2076. auto thread2 = std::thread([&]() {
  2077. svr2_port = svr2.bind_to_any_port(HOST);
  2078. svr2.listen_after_bind();
  2079. });
  2080. auto se = detail::scope_exit([&] {
  2081. svr2.stop();
  2082. thread2.join();
  2083. svr1.stop();
  2084. thread1.join();
  2085. ASSERT_FALSE(svr2.is_running());
  2086. ASSERT_FALSE(svr1.is_running());
  2087. });
  2088. svr1.wait_until_ready();
  2089. svr2.wait_until_ready();
  2090. Client cli("localhost", svr2_port);
  2091. cli.set_follow_location(true);
  2092. set_auth(cli);
  2093. auto res = cli.Get("/redir");
  2094. ASSERT_TRUE(res);
  2095. EXPECT_EQ(StatusCode::OK_200, res->status);
  2096. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2097. EXPECT_TRUE(captured_authorization.empty());
  2098. }
  2099. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2100. TestDoNotForwardCredentialsOnRedirect(
  2101. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2102. }
  2103. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2104. TestDoNotForwardCredentialsOnRedirect(
  2105. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2106. }
  2107. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2108. Server svr;
  2109. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2110. // Port number that overflows int — should not crash
  2111. res.set_redirect("http://localhost:99999999999999999999/target");
  2112. });
  2113. auto port = svr.bind_to_any_port(HOST);
  2114. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2115. auto se = detail::scope_exit([&] {
  2116. svr.stop();
  2117. thread.join();
  2118. ASSERT_FALSE(svr.is_running());
  2119. });
  2120. svr.wait_until_ready();
  2121. Client cli(HOST, port);
  2122. cli.set_follow_location(true);
  2123. auto res = cli.Get("/redir");
  2124. // Should fail gracefully, not crash (no valid response due to bad port)
  2125. EXPECT_FALSE(res);
  2126. }
  2127. TEST(RedirectFromPageWithContent, Redirect) {
  2128. Server svr;
  2129. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2130. res.set_content("___", "text/plain");
  2131. res.set_redirect("/2");
  2132. });
  2133. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2134. res.set_content("Hello World!", "text/plain");
  2135. });
  2136. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2137. auto se = detail::scope_exit([&] {
  2138. svr.stop();
  2139. th.join();
  2140. ASSERT_FALSE(svr.is_running());
  2141. });
  2142. svr.wait_until_ready();
  2143. {
  2144. Client cli("localhost", PORT);
  2145. cli.set_follow_location(true);
  2146. std::string body;
  2147. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2148. body.append(data, data_length);
  2149. return true;
  2150. });
  2151. ASSERT_TRUE(res);
  2152. EXPECT_EQ(StatusCode::OK_200, res->status);
  2153. EXPECT_EQ("Hello World!", body);
  2154. }
  2155. {
  2156. Client cli("localhost", PORT);
  2157. std::string body;
  2158. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2159. body.append(data, data_length);
  2160. return true;
  2161. });
  2162. ASSERT_TRUE(res);
  2163. EXPECT_EQ(StatusCode::Found_302, res->status);
  2164. EXPECT_EQ("___", body);
  2165. }
  2166. }
  2167. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2168. Server svr;
  2169. auto port_str = std::to_string(PORT);
  2170. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2171. auto expected_host = "[::1]:" + port_str;
  2172. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2173. res.set_content("___", "text/plain");
  2174. // res.set_redirect("/2");
  2175. res.set_redirect(redirect_url);
  2176. });
  2177. svr.Get("/2", [&](const Request &req, Response &res) {
  2178. auto host_header = req.headers.find("Host");
  2179. ASSERT_TRUE(host_header != req.headers.end());
  2180. EXPECT_EQ(expected_host, host_header->second);
  2181. res.set_content("Hello World!", "text/plain");
  2182. });
  2183. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2184. auto se = detail::scope_exit([&] {
  2185. svr.stop();
  2186. th.join();
  2187. ASSERT_FALSE(svr.is_running());
  2188. });
  2189. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2190. // actually starts anything, so the condition !svr.is_running() will
  2191. // always remain true, and the loop never stops.
  2192. // This basically counts how many milliseconds have passed since the
  2193. // call to svr.listen(), and if after 5 seconds nothing started yet
  2194. // aborts the test.
  2195. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2196. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2197. ASSERT_LT(milliseconds, 5000U);
  2198. }
  2199. {
  2200. Client cli("::1", PORT);
  2201. cli.set_follow_location(true);
  2202. std::string body;
  2203. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2204. body.append(data, data_length);
  2205. return true;
  2206. });
  2207. ASSERT_TRUE(res);
  2208. EXPECT_EQ(StatusCode::OK_200, res->status);
  2209. EXPECT_EQ("Hello World!", body);
  2210. }
  2211. {
  2212. Client cli("::1", PORT);
  2213. std::string body;
  2214. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2215. body.append(data, data_length);
  2216. return true;
  2217. });
  2218. ASSERT_TRUE(res);
  2219. EXPECT_EQ(StatusCode::Found_302, res->status);
  2220. EXPECT_EQ("___", body);
  2221. }
  2222. }
  2223. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2224. Server svr;
  2225. svr.Get("/foo", [](const Request &req, Response &res) {
  2226. auto a = req.params.find("a");
  2227. if (a != req.params.end()) {
  2228. res.set_content((*a).second, "text/plain");
  2229. res.status = StatusCode::OK_200;
  2230. } else {
  2231. res.status = StatusCode::BadRequest_400;
  2232. }
  2233. });
  2234. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2235. auto se = detail::scope_exit([&] {
  2236. svr.stop();
  2237. thread.join();
  2238. ASSERT_FALSE(svr.is_running());
  2239. });
  2240. svr.wait_until_ready();
  2241. {
  2242. Client cli(HOST, PORT);
  2243. cli.set_path_encode(false);
  2244. auto res = cli.Get("/foo?a=explicitly+encoded");
  2245. ASSERT_TRUE(res);
  2246. EXPECT_EQ(StatusCode::OK_200, res->status);
  2247. // This expects it back with a space, as the `+` won't have been
  2248. // url-encoded, and server-side the params get decoded turning `+`
  2249. // into spaces.
  2250. EXPECT_EQ("explicitly encoded", res->body);
  2251. }
  2252. }
  2253. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2254. Server svr;
  2255. svr.Get("/", [](const Request &req, Response &) {
  2256. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2257. });
  2258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2259. auto se = detail::scope_exit([&] {
  2260. svr.stop();
  2261. thread.join();
  2262. ASSERT_FALSE(svr.is_running());
  2263. });
  2264. svr.wait_until_ready();
  2265. {
  2266. Client cli(HOST, PORT);
  2267. cli.set_path_encode(false);
  2268. auto res = cli.Get("/?something=%0A");
  2269. ASSERT_TRUE(res);
  2270. EXPECT_EQ(StatusCode::OK_200, res->status);
  2271. }
  2272. }
  2273. TEST(BindServerTest, BindDualStack) {
  2274. Server svr;
  2275. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2276. res.set_content("Hello World!", "text/plain");
  2277. });
  2278. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2279. auto se = detail::scope_exit([&] {
  2280. svr.stop();
  2281. thread.join();
  2282. ASSERT_FALSE(svr.is_running());
  2283. });
  2284. svr.wait_until_ready();
  2285. {
  2286. Client cli("127.0.0.1", PORT);
  2287. auto res = cli.Get("/1");
  2288. ASSERT_TRUE(res);
  2289. EXPECT_EQ(StatusCode::OK_200, res->status);
  2290. EXPECT_EQ("Hello World!", res->body);
  2291. }
  2292. {
  2293. Client cli("::1", PORT);
  2294. auto res = cli.Get("/1");
  2295. ASSERT_TRUE(res);
  2296. EXPECT_EQ(StatusCode::OK_200, res->status);
  2297. EXPECT_EQ("Hello World!", res->body);
  2298. }
  2299. }
  2300. TEST(BindServerTest, BindAndListenSeparately) {
  2301. Server svr;
  2302. int port = svr.bind_to_any_port("0.0.0.0");
  2303. ASSERT_TRUE(svr.is_valid());
  2304. ASSERT_TRUE(port > 0);
  2305. svr.stop();
  2306. }
  2307. #ifdef CPPHTTPLIB_SSL_ENABLED
  2308. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2309. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2310. CLIENT_CA_CERT_DIR);
  2311. int port = svr.bind_to_any_port("0.0.0.0");
  2312. ASSERT_TRUE(svr.is_valid());
  2313. ASSERT_TRUE(port > 0);
  2314. svr.stop();
  2315. }
  2316. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2317. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2318. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2319. int port = svr.bind_to_any_port("0.0.0.0");
  2320. ASSERT_TRUE(svr.is_valid());
  2321. ASSERT_TRUE(port > 0);
  2322. svr.stop();
  2323. }
  2324. TEST(BindServerTest, UpdateCertsPem) {
  2325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2326. int port = svr.bind_to_any_port("0.0.0.0");
  2327. ASSERT_TRUE(svr.is_valid());
  2328. ASSERT_TRUE(port > 0);
  2329. // Read PEM files
  2330. std::string cert_pem, key_pem, ca_pem;
  2331. read_file(SERVER_CERT_FILE, cert_pem);
  2332. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2333. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2334. // Update server certificates using PEM API
  2335. ASSERT_TRUE(
  2336. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2337. ASSERT_TRUE(svr.is_valid());
  2338. svr.stop();
  2339. }
  2340. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2341. // Start server with client CA (enables client auth)
  2342. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2343. ASSERT_TRUE(svr.is_valid());
  2344. bool handler_called = false;
  2345. svr.Get("/test", [&](const Request &req, Response &res) {
  2346. handler_called = true;
  2347. // Verify client certificate is present
  2348. auto cert = req.peer_cert();
  2349. EXPECT_TRUE(static_cast<bool>(cert));
  2350. res.set_content("ok", "text/plain");
  2351. });
  2352. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2353. auto se = detail::scope_exit([&] {
  2354. svr.stop();
  2355. t.join();
  2356. ASSERT_FALSE(svr.is_running());
  2357. });
  2358. svr.wait_until_ready();
  2359. // Read PEM files
  2360. std::string cert_pem, key_pem, ca_pem;
  2361. read_file(SERVER_CERT_FILE, cert_pem);
  2362. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2363. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2364. // Update server certificates and client CA using PEM API while server running
  2365. ASSERT_TRUE(
  2366. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2367. // Connect with client certificate
  2368. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2369. cli.enable_server_certificate_verification(false);
  2370. cli.set_connection_timeout(30);
  2371. auto res = cli.Get("/test");
  2372. ASSERT_TRUE(res);
  2373. ASSERT_EQ(StatusCode::OK_200, res->status);
  2374. ASSERT_TRUE(handler_called);
  2375. EXPECT_EQ("ok", res->body);
  2376. }
  2377. #endif
  2378. TEST(ErrorHandlerTest, ContentLength) {
  2379. Server svr;
  2380. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2381. res.status = StatusCode::OK_200;
  2382. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2383. "text/html"); // <= Content-Length still 13
  2384. });
  2385. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2386. res.set_content("Hello World!\n", "text/plain");
  2387. res.status = 524;
  2388. });
  2389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2390. auto se = detail::scope_exit([&] {
  2391. svr.stop();
  2392. thread.join();
  2393. ASSERT_FALSE(svr.is_running());
  2394. });
  2395. svr.wait_until_ready();
  2396. {
  2397. Client cli(HOST, PORT);
  2398. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2399. ASSERT_TRUE(res);
  2400. EXPECT_EQ(StatusCode::OK_200, res->status);
  2401. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2402. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2403. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2404. }
  2405. }
  2406. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2407. TEST(ExceptionTest, WithoutExceptionHandler) {
  2408. Server svr;
  2409. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2410. throw std::runtime_error("exception...");
  2411. });
  2412. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2413. throw std::runtime_error("exception\r\n...");
  2414. });
  2415. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2416. auto se = detail::scope_exit([&] {
  2417. svr.stop();
  2418. listen_thread.join();
  2419. ASSERT_FALSE(svr.is_running());
  2420. });
  2421. svr.wait_until_ready();
  2422. Client cli("localhost", PORT);
  2423. {
  2424. auto res = cli.Get("/exception");
  2425. ASSERT_TRUE(res);
  2426. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2427. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2428. }
  2429. {
  2430. auto res = cli.Get("/unknown");
  2431. ASSERT_TRUE(res);
  2432. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2433. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2434. }
  2435. }
  2436. TEST(ExceptionTest, WithExceptionHandler) {
  2437. Server svr;
  2438. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2439. std::exception_ptr ep) {
  2440. EXPECT_FALSE(ep == nullptr);
  2441. try {
  2442. std::rethrow_exception(ep);
  2443. } catch (std::exception &e) {
  2444. EXPECT_EQ("abc", std::string(e.what()));
  2445. } catch (...) {}
  2446. res.status = StatusCode::InternalServerError_500;
  2447. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2448. "text/html"); // <= Content-Length still 13 at this point
  2449. });
  2450. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2451. res.set_content("Hello World!\n", "text/plain");
  2452. throw std::runtime_error("abc");
  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. for (size_t i = 0; i < 10; i++) {
  2462. Client cli(HOST, PORT);
  2463. for (size_t j = 0; j < 100; j++) {
  2464. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2465. ASSERT_TRUE(res);
  2466. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2467. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2468. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2469. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2470. }
  2471. cli.set_keep_alive(true);
  2472. for (size_t j = 0; j < 100; j++) {
  2473. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2474. ASSERT_TRUE(res);
  2475. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2476. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2477. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2478. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2479. }
  2480. }
  2481. }
  2482. TEST(ExceptionTest, AndErrorHandler) {
  2483. Server svr;
  2484. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2485. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2486. });
  2487. svr.set_exception_handler(
  2488. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2489. EXPECT_FALSE(ep == nullptr);
  2490. try {
  2491. std::rethrow_exception(ep);
  2492. } catch (std::exception &e) {
  2493. res.set_content(e.what(), "text/html");
  2494. } catch (...) {}
  2495. res.status = StatusCode::InternalServerError_500;
  2496. });
  2497. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2498. throw std::runtime_error("EXCEPTION");
  2499. });
  2500. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2501. res.set_content("ERROR", "text/html");
  2502. res.status = StatusCode::InternalServerError_500;
  2503. });
  2504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2505. auto se = detail::scope_exit([&] {
  2506. svr.stop();
  2507. thread.join();
  2508. ASSERT_FALSE(svr.is_running());
  2509. });
  2510. svr.wait_until_ready();
  2511. Client cli(HOST, PORT);
  2512. {
  2513. auto res = cli.Get("/exception");
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2516. EXPECT_EQ("EXCEPTION", res->body);
  2517. }
  2518. {
  2519. auto res = cli.Get("/error");
  2520. ASSERT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2522. EXPECT_EQ("ERROR", res->body);
  2523. }
  2524. {
  2525. auto res = cli.Get("/invalid");
  2526. ASSERT_TRUE(res);
  2527. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2528. EXPECT_EQ("NOT_FOUND", res->body);
  2529. }
  2530. }
  2531. #endif
  2532. TEST(NoContentTest, ContentLength) {
  2533. Server svr;
  2534. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2535. res.status = StatusCode::NoContent_204;
  2536. });
  2537. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2538. auto se = detail::scope_exit([&] {
  2539. svr.stop();
  2540. thread.join();
  2541. ASSERT_FALSE(svr.is_running());
  2542. });
  2543. svr.wait_until_ready();
  2544. {
  2545. Client cli(HOST, PORT);
  2546. auto res = cli.Get("/hi");
  2547. ASSERT_TRUE(res);
  2548. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2549. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2550. }
  2551. }
  2552. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2553. #ifdef CPPHTTPLIB_SSL_ENABLED
  2554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2555. ASSERT_TRUE(svr.is_valid());
  2556. #else
  2557. Server svr;
  2558. #endif
  2559. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2560. if (req.path == "/routing_handler") {
  2561. res.set_header("PRE_ROUTING", "on");
  2562. res.set_content("Routing Handler", "text/plain");
  2563. return httplib::Server::HandlerResponse::Handled;
  2564. }
  2565. return httplib::Server::HandlerResponse::Unhandled;
  2566. });
  2567. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2568. res.set_content("Error", "text/html");
  2569. });
  2570. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2571. if (req.path == "/routing_handler") {
  2572. res.set_header("POST_ROUTING", "on");
  2573. }
  2574. });
  2575. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2576. res.set_content("Hello World!\n", "text/plain");
  2577. });
  2578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2579. auto se = detail::scope_exit([&] {
  2580. svr.stop();
  2581. thread.join();
  2582. ASSERT_FALSE(svr.is_running());
  2583. });
  2584. svr.wait_until_ready();
  2585. {
  2586. #ifdef CPPHTTPLIB_SSL_ENABLED
  2587. SSLClient cli(HOST, PORT);
  2588. cli.enable_server_certificate_verification(false);
  2589. #else
  2590. Client cli(HOST, PORT);
  2591. #endif
  2592. auto res = cli.Get("/routing_handler");
  2593. ASSERT_TRUE(res);
  2594. EXPECT_EQ(StatusCode::OK_200, res->status);
  2595. EXPECT_EQ("Routing Handler", res->body);
  2596. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2597. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2598. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2599. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2600. }
  2601. {
  2602. #ifdef CPPHTTPLIB_SSL_ENABLED
  2603. SSLClient cli(HOST, PORT);
  2604. cli.enable_server_certificate_verification(false);
  2605. #else
  2606. Client cli(HOST, PORT);
  2607. #endif
  2608. auto res = cli.Get("/hi");
  2609. ASSERT_TRUE(res);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. EXPECT_EQ("Hello World!\n", res->body);
  2612. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2613. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2614. }
  2615. {
  2616. #ifdef CPPHTTPLIB_SSL_ENABLED
  2617. SSLClient cli(HOST, PORT);
  2618. cli.enable_server_certificate_verification(false);
  2619. #else
  2620. Client cli(HOST, PORT);
  2621. #endif
  2622. auto res = cli.Get("/aaa");
  2623. ASSERT_TRUE(res);
  2624. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2625. EXPECT_EQ("Error", res->body);
  2626. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2627. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2628. }
  2629. }
  2630. TEST(RequestHandlerTest, PreRequestHandler) {
  2631. auto route_path = "/user/:user";
  2632. Server svr;
  2633. svr.Get("/hi", [](const Request &, Response &res) {
  2634. res.set_content("hi", "text/plain");
  2635. });
  2636. svr.Get(route_path, [](const Request &req, Response &res) {
  2637. res.set_content(req.path_params.at("user"), "text/plain");
  2638. });
  2639. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2640. if (req.matched_route == route_path) {
  2641. auto user = req.path_params.at("user");
  2642. if (user != "john") {
  2643. res.status = StatusCode::Forbidden_403;
  2644. res.set_content("error", "text/html");
  2645. return Server::HandlerResponse::Handled;
  2646. }
  2647. }
  2648. return Server::HandlerResponse::Unhandled;
  2649. });
  2650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2651. auto se = detail::scope_exit([&] {
  2652. svr.stop();
  2653. thread.join();
  2654. ASSERT_FALSE(svr.is_running());
  2655. });
  2656. svr.wait_until_ready();
  2657. Client cli(HOST, PORT);
  2658. {
  2659. auto res = cli.Get("/hi");
  2660. ASSERT_TRUE(res);
  2661. EXPECT_EQ(StatusCode::OK_200, res->status);
  2662. EXPECT_EQ("hi", res->body);
  2663. }
  2664. {
  2665. auto res = cli.Get("/user/john");
  2666. ASSERT_TRUE(res);
  2667. EXPECT_EQ(StatusCode::OK_200, res->status);
  2668. EXPECT_EQ("john", res->body);
  2669. }
  2670. {
  2671. auto res = cli.Get("/user/invalid-user");
  2672. ASSERT_TRUE(res);
  2673. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2674. EXPECT_EQ("error", res->body);
  2675. }
  2676. }
  2677. TEST(UserDataTest, BasicOperations) {
  2678. httplib::UserData ud;
  2679. // Initially empty
  2680. EXPECT_FALSE(ud.has("key"));
  2681. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2682. // set and get
  2683. ud.set("key", 42);
  2684. EXPECT_TRUE(ud.has("key"));
  2685. auto *p = ud.get<int>("key");
  2686. ASSERT_NE(nullptr, p);
  2687. EXPECT_EQ(42, *p);
  2688. // Type mismatch → nullptr
  2689. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2690. // Overwrite with different type
  2691. ud.set("key", std::string("hello"));
  2692. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2693. auto *s = ud.get<std::string>("key");
  2694. ASSERT_NE(nullptr, s);
  2695. EXPECT_EQ("hello", *s);
  2696. // erase
  2697. ud.erase("key");
  2698. EXPECT_FALSE(ud.has("key"));
  2699. // clear
  2700. ud.set("a", 1);
  2701. ud.set("b", 2);
  2702. ud.clear();
  2703. EXPECT_FALSE(ud.has("a"));
  2704. EXPECT_FALSE(ud.has("b"));
  2705. }
  2706. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2707. struct AuthCtx {
  2708. std::string user_id;
  2709. };
  2710. Server svr;
  2711. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2712. res.user_data.set("auth", AuthCtx{"alice"});
  2713. return Server::HandlerResponse::Unhandled;
  2714. });
  2715. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2716. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2717. ASSERT_NE(nullptr, ctx);
  2718. res.set_content("Hello " + ctx->user_id, "text/plain");
  2719. });
  2720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2721. auto se = detail::scope_exit([&] {
  2722. svr.stop();
  2723. thread.join();
  2724. ASSERT_FALSE(svr.is_running());
  2725. });
  2726. svr.wait_until_ready();
  2727. Client cli(HOST, PORT);
  2728. auto res = cli.Get("/me");
  2729. ASSERT_TRUE(res);
  2730. EXPECT_EQ(StatusCode::OK_200, res->status);
  2731. EXPECT_EQ("Hello alice", res->body);
  2732. }
  2733. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2734. struct RoleCtx {
  2735. std::string role;
  2736. };
  2737. Server svr;
  2738. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2739. res.user_data.set("role", RoleCtx{"admin"});
  2740. return Server::HandlerResponse::Unhandled;
  2741. });
  2742. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2743. auto *ctx = res.user_data.get<RoleCtx>("role");
  2744. ASSERT_NE(nullptr, ctx);
  2745. res.set_content(ctx->role, "text/plain");
  2746. });
  2747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2748. auto se = detail::scope_exit([&] {
  2749. svr.stop();
  2750. thread.join();
  2751. ASSERT_FALSE(svr.is_running());
  2752. });
  2753. svr.wait_until_ready();
  2754. Client cli(HOST, PORT);
  2755. auto res = cli.Get("/role");
  2756. ASSERT_TRUE(res);
  2757. EXPECT_EQ(StatusCode::OK_200, res->status);
  2758. EXPECT_EQ("admin", res->body);
  2759. }
  2760. TEST(InvalidFormatTest, StatusCode) {
  2761. Server svr;
  2762. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2763. res.set_content("Hello World!\n", "text/plain");
  2764. res.status = 9999; // Status should be a three-digit code...
  2765. });
  2766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2767. auto se = detail::scope_exit([&] {
  2768. svr.stop();
  2769. thread.join();
  2770. ASSERT_FALSE(svr.is_running());
  2771. });
  2772. svr.wait_until_ready();
  2773. {
  2774. Client cli(HOST, PORT);
  2775. auto res = cli.Get("/hi");
  2776. ASSERT_FALSE(res);
  2777. }
  2778. }
  2779. TEST(URLFragmentTest, WithFragment) {
  2780. Server svr;
  2781. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2782. EXPECT_TRUE(req.target == "/hi");
  2783. });
  2784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2785. auto se = detail::scope_exit([&] {
  2786. svr.stop();
  2787. thread.join();
  2788. ASSERT_FALSE(svr.is_running());
  2789. });
  2790. svr.wait_until_ready();
  2791. {
  2792. Client cli(HOST, PORT);
  2793. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2794. EXPECT_TRUE(res);
  2795. EXPECT_EQ(StatusCode::OK_200, res->status);
  2796. res = cli.Get("/hi%23key1=val1=key2=val2");
  2797. EXPECT_TRUE(res);
  2798. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2799. }
  2800. }
  2801. TEST(HeaderWriter, SetHeaderWriter) {
  2802. Server svr;
  2803. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2804. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2805. return detail::write_headers(strm, hdrs);
  2806. });
  2807. svr.Get("/hi", [](const Request &req, Response &res) {
  2808. auto it = req.headers.find("CustomClientHeader");
  2809. EXPECT_TRUE(it != req.headers.end());
  2810. EXPECT_EQ(it->second, "CustomClientValue");
  2811. res.set_content("Hello World!\n", "text/plain");
  2812. });
  2813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2814. auto se = detail::scope_exit([&] {
  2815. svr.stop();
  2816. thread.join();
  2817. ASSERT_FALSE(svr.is_running());
  2818. });
  2819. svr.wait_until_ready();
  2820. {
  2821. Client cli(HOST, PORT);
  2822. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2823. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2824. return detail::write_headers(strm, hdrs);
  2825. });
  2826. auto res = cli.Get("/hi");
  2827. EXPECT_TRUE(res);
  2828. EXPECT_EQ(StatusCode::OK_200, res->status);
  2829. auto it = res->headers.find("CustomServerHeader");
  2830. EXPECT_TRUE(it != res->headers.end());
  2831. EXPECT_EQ(it->second, "CustomServerValue");
  2832. }
  2833. }
  2834. class ServerTest : public ::testing::Test {
  2835. protected:
  2836. ServerTest()
  2837. : cli_(HOST, PORT)
  2838. #ifdef CPPHTTPLIB_SSL_ENABLED
  2839. ,
  2840. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2841. #endif
  2842. {
  2843. #ifdef CPPHTTPLIB_SSL_ENABLED
  2844. cli_.enable_server_certificate_verification(false);
  2845. #endif
  2846. // Allow LARGE_DATA (100MB) responses
  2847. cli_.set_payload_max_length(200 * 1024 * 1024);
  2848. }
  2849. virtual void SetUp() {
  2850. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2851. svr_.set_payload_max_length(200 * 1024 * 1024);
  2852. svr_.set_mount_point("/", "./www");
  2853. svr_.set_mount_point("/mount", "./www2");
  2854. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2855. svr_.Get("/hi",
  2856. [&](const Request & /*req*/, Response &res) {
  2857. res.set_content("Hello World!", "text/plain");
  2858. })
  2859. .Get("/file_content",
  2860. [&](const Request & /*req*/, Response &res) {
  2861. res.set_file_content("./www/dir/test.html");
  2862. })
  2863. .Get("/file_content_with_content_type",
  2864. [&](const Request & /*req*/, Response &res) {
  2865. res.set_file_content("./www/file", "text/plain");
  2866. })
  2867. .Get("/invalid_file_content",
  2868. [&](const Request & /*req*/, Response &res) {
  2869. res.set_file_content("./www/dir/invalid_file_path");
  2870. })
  2871. .Get("/http_response_splitting",
  2872. [&](const Request & /*req*/, Response &res) {
  2873. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2874. EXPECT_EQ(0U, res.headers.size());
  2875. EXPECT_FALSE(res.has_header("a"));
  2876. res.set_header("a", "1\nSet-Cookie: a=1");
  2877. EXPECT_EQ(0U, res.headers.size());
  2878. EXPECT_FALSE(res.has_header("a"));
  2879. res.set_header("a", "1\rSet-Cookie: a=1");
  2880. EXPECT_EQ(0U, res.headers.size());
  2881. EXPECT_FALSE(res.has_header("a"));
  2882. res.set_header("a\r\nb", "0");
  2883. EXPECT_EQ(0U, res.headers.size());
  2884. EXPECT_FALSE(res.has_header("a"));
  2885. res.set_header("a\rb", "0");
  2886. EXPECT_EQ(0U, res.headers.size());
  2887. EXPECT_FALSE(res.has_header("a"));
  2888. res.set_header("a\nb", "0");
  2889. EXPECT_EQ(0U, res.headers.size());
  2890. EXPECT_FALSE(res.has_header("a"));
  2891. res.set_redirect("1\r\nSet-Cookie: a=1");
  2892. EXPECT_EQ(0U, res.headers.size());
  2893. EXPECT_FALSE(res.has_header("Location"));
  2894. })
  2895. .Get("/slow",
  2896. [&](const Request & /*req*/, Response &res) {
  2897. std::this_thread::sleep_for(std::chrono::seconds(4));
  2898. res.set_content("slow", "text/plain");
  2899. })
  2900. #if 0
  2901. .Post("/slowpost",
  2902. [&](const Request & /*req*/, Response &res) {
  2903. std::this_thread::sleep_for(std::chrono::seconds(2));
  2904. res.set_content("slow", "text/plain");
  2905. })
  2906. #endif
  2907. .Get("/remote_addr",
  2908. [&](const Request &req, Response &res) {
  2909. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2910. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2911. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2912. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2913. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2914. #endif
  2915. res.set_content(req.remote_addr, "text/plain");
  2916. })
  2917. .Get("/local_addr",
  2918. [&](const Request &req, Response &res) {
  2919. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2920. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2921. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2922. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2923. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2924. #endif
  2925. auto local_addr = req.local_addr;
  2926. auto local_port = std::to_string(req.local_port);
  2927. res.set_content(local_addr.append(":").append(local_port),
  2928. "text/plain");
  2929. })
  2930. .Get("/endwith%",
  2931. [&](const Request & /*req*/, Response &res) {
  2932. res.set_content("Hello World!", "text/plain");
  2933. })
  2934. .Get("/a\\+\\+b",
  2935. [&](const Request &req, Response &res) {
  2936. ASSERT_TRUE(req.has_param("a +b"));
  2937. auto val = req.get_param_value("a +b");
  2938. res.set_content(val, "text/plain");
  2939. })
  2940. .Get("/", [&](const Request & /*req*/,
  2941. Response &res) { res.set_redirect("/hi"); })
  2942. .Post("/1",
  2943. [](const Request & /*req*/, Response &res) {
  2944. res.set_redirect("/2", StatusCode::SeeOther_303);
  2945. })
  2946. .Get("/2",
  2947. [](const Request & /*req*/, Response &res) {
  2948. res.set_content("redirected.", "text/plain");
  2949. res.status = StatusCode::OK_200;
  2950. })
  2951. .Post("/person",
  2952. [&](const Request &req, Response &res) {
  2953. if (req.has_param("name") && req.has_param("note")) {
  2954. persons_[req.get_param_value("name")] =
  2955. req.get_param_value("note");
  2956. } else {
  2957. res.status = StatusCode::BadRequest_400;
  2958. }
  2959. })
  2960. .Put("/person",
  2961. [&](const Request &req, Response &res) {
  2962. if (req.has_param("name") && req.has_param("note")) {
  2963. persons_[req.get_param_value("name")] =
  2964. req.get_param_value("note");
  2965. } else {
  2966. res.status = StatusCode::BadRequest_400;
  2967. }
  2968. })
  2969. .Get("/person/(.*)",
  2970. [&](const Request &req, Response &res) {
  2971. string name = req.matches[1];
  2972. if (persons_.find(name) != persons_.end()) {
  2973. auto note = persons_[name];
  2974. res.set_content(note, "text/plain");
  2975. } else {
  2976. res.status = StatusCode::NotFound_404;
  2977. }
  2978. })
  2979. .Delete("/person",
  2980. [&](const Request &req, Response &res) {
  2981. if (req.has_param("name")) {
  2982. string name = req.get_param_value("name");
  2983. if (persons_.find(name) != persons_.end()) {
  2984. persons_.erase(name);
  2985. res.set_content("DELETED", "text/plain");
  2986. } else {
  2987. res.status = StatusCode::NotFound_404;
  2988. }
  2989. } else {
  2990. res.status = StatusCode::BadRequest_400;
  2991. }
  2992. })
  2993. .Post("/x-www-form-urlencoded-json",
  2994. [&](const Request &req, Response &res) {
  2995. auto json = req.get_param_value("json");
  2996. ASSERT_EQ(JSON_DATA, json);
  2997. res.set_content(json, "appliation/json");
  2998. res.status = StatusCode::OK_200;
  2999. })
  3000. .Get("/streamed-chunked",
  3001. [&](const Request & /*req*/, Response &res) {
  3002. res.set_chunked_content_provider(
  3003. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3004. sink.os << "123";
  3005. sink.os << "456";
  3006. sink.os << "789";
  3007. sink.done();
  3008. return true;
  3009. });
  3010. })
  3011. .Get("/streamed-chunked-with-prohibited-trailer",
  3012. [&](const Request & /*req*/, Response &res) {
  3013. auto i = new int(0);
  3014. // Declare both a prohibited trailer (Content-Length) and an
  3015. // allowed one
  3016. res.set_header("Trailer", "Content-Length, X-Allowed");
  3017. res.set_chunked_content_provider(
  3018. "text/plain",
  3019. [i](size_t /*offset*/, DataSink &sink) {
  3020. switch (*i) {
  3021. case 0: sink.os << "123"; break;
  3022. case 1: sink.os << "456"; break;
  3023. case 2: sink.os << "789"; break;
  3024. case 3: {
  3025. sink.done_with_trailer(
  3026. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3027. } break;
  3028. }
  3029. (*i)++;
  3030. return true;
  3031. },
  3032. [i](bool success) {
  3033. EXPECT_TRUE(success);
  3034. delete i;
  3035. });
  3036. })
  3037. .Get("/streamed-chunked2",
  3038. [&](const Request & /*req*/, Response &res) {
  3039. auto i = new int(0);
  3040. res.set_chunked_content_provider(
  3041. "text/plain",
  3042. [i](size_t /*offset*/, DataSink &sink) {
  3043. switch (*i) {
  3044. case 0: sink.os << "123"; break;
  3045. case 1: sink.os << "456"; break;
  3046. case 2: sink.os << "789"; break;
  3047. case 3: sink.done(); break;
  3048. }
  3049. (*i)++;
  3050. return true;
  3051. },
  3052. [i](bool success) {
  3053. EXPECT_TRUE(success);
  3054. delete i;
  3055. });
  3056. })
  3057. .Get("/streamed-chunked-with-trailer",
  3058. [&](const Request & /*req*/, Response &res) {
  3059. auto i = new int(0);
  3060. res.set_header("Trailer", "Dummy1, Dummy2");
  3061. res.set_chunked_content_provider(
  3062. "text/plain",
  3063. [i](size_t /*offset*/, DataSink &sink) {
  3064. switch (*i) {
  3065. case 0: sink.os << "123"; break;
  3066. case 1: sink.os << "456"; break;
  3067. case 2: sink.os << "789"; break;
  3068. case 3: {
  3069. sink.done_with_trailer(
  3070. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3071. } break;
  3072. }
  3073. (*i)++;
  3074. return true;
  3075. },
  3076. [i](bool success) {
  3077. EXPECT_TRUE(success);
  3078. delete i;
  3079. });
  3080. })
  3081. .Get("/streamed",
  3082. [&](const Request & /*req*/, Response &res) {
  3083. res.set_content_provider(
  3084. 6, "text/plain",
  3085. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3086. sink.os << (offset < 3 ? "a" : "b");
  3087. return true;
  3088. });
  3089. })
  3090. .Get("/streamed-with-range",
  3091. [&](const Request &req, Response &res) {
  3092. auto data = new std::string("abcdefg");
  3093. res.set_content_provider(
  3094. data->size(), "text/plain",
  3095. [data](size_t offset, size_t length, DataSink &sink) {
  3096. size_t DATA_CHUNK_SIZE = 4;
  3097. const auto &d = *data;
  3098. auto out_len =
  3099. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3100. auto ret =
  3101. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3102. EXPECT_TRUE(ret);
  3103. return true;
  3104. },
  3105. [data, &req](bool success) {
  3106. EXPECT_EQ(success, !req.has_param("error"));
  3107. delete data;
  3108. });
  3109. })
  3110. .Get("/streamed-cancel",
  3111. [&](const Request & /*req*/, Response &res) {
  3112. res.set_content_provider(
  3113. size_t(-1), "text/plain",
  3114. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3115. sink.os << "data_chunk";
  3116. return true;
  3117. });
  3118. })
  3119. .Get("/regex-with-delimiter",
  3120. [&](const Request &req, Response & /*res*/) {
  3121. ASSERT_TRUE(req.has_param("key"));
  3122. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3123. })
  3124. .Get("/with-range",
  3125. [&](const Request & /*req*/, Response &res) {
  3126. res.set_content("abcdefg", "text/plain");
  3127. })
  3128. .Get("/test-start-time",
  3129. [&](const Request &req, Response & /*res*/) {
  3130. EXPECT_NE(req.start_time_,
  3131. std::chrono::steady_clock::time_point::min());
  3132. })
  3133. .Get("/with-range-customized-response",
  3134. [&](const Request & /*req*/, Response &res) {
  3135. res.status = StatusCode::BadRequest_400;
  3136. res.set_content(JSON_DATA, "application/json");
  3137. })
  3138. .Post("/chunked",
  3139. [&](const Request &req, Response & /*res*/) {
  3140. EXPECT_EQ(req.body, "dechunked post body");
  3141. })
  3142. .Post("/large-chunked",
  3143. [&](const Request &req, Response & /*res*/) {
  3144. std::string expected(6 * 30 * 1024u, 'a');
  3145. EXPECT_EQ(req.body, expected);
  3146. })
  3147. .Post("/multipart",
  3148. [&](const Request &req, Response & /*res*/) {
  3149. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3150. req.form.get_field_count("text2") +
  3151. req.form.get_field_count("file3") +
  3152. req.form.get_field_count("file4"));
  3153. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3154. req.form.get_file_count("file2"));
  3155. ASSERT_TRUE(!req.form.has_file("???"));
  3156. ASSERT_TRUE(!req.form.has_field("???"));
  3157. ASSERT_TRUE(req.body.empty());
  3158. {
  3159. const auto &text = req.form.get_field("text1");
  3160. EXPECT_EQ("text default", text);
  3161. }
  3162. {
  3163. const auto &text = req.form.get_field("text2");
  3164. EXPECT_EQ("aωb", text);
  3165. }
  3166. {
  3167. const auto &file = req.form.get_file("file1");
  3168. EXPECT_EQ("hello.txt", file.filename);
  3169. EXPECT_EQ("text/plain", file.content_type);
  3170. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3171. }
  3172. {
  3173. const auto &file = req.form.get_file("file2");
  3174. EXPECT_EQ("world.json", file.filename);
  3175. EXPECT_EQ("application/json", file.content_type);
  3176. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3177. }
  3178. {
  3179. const auto &text = req.form.get_field("file3");
  3180. EXPECT_EQ(0u, text.size());
  3181. }
  3182. {
  3183. const auto &text = req.form.get_field("file4");
  3184. EXPECT_EQ(0u, text.size());
  3185. }
  3186. })
  3187. .Post("/multipart/multi_file_values",
  3188. [&](const Request &req, Response & /*res*/) {
  3189. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3190. req.form.get_field_count("multi_text1"));
  3191. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3192. ASSERT_TRUE(!req.form.has_file("???"));
  3193. ASSERT_TRUE(!req.form.has_field("???"));
  3194. ASSERT_TRUE(req.body.empty());
  3195. {
  3196. const auto &text = req.form.get_field("text");
  3197. EXPECT_EQ("default text", text);
  3198. }
  3199. {
  3200. const auto &text1_values = req.form.get_fields("multi_text1");
  3201. EXPECT_EQ(2u, text1_values.size());
  3202. EXPECT_EQ("aaaaa", text1_values[0]);
  3203. EXPECT_EQ("bbbbb", text1_values[1]);
  3204. }
  3205. {
  3206. const auto &file1_values = req.form.get_files("multi_file1");
  3207. EXPECT_EQ(2u, file1_values.size());
  3208. auto file1 = file1_values[0];
  3209. EXPECT_EQ(file1.filename, "hello.txt");
  3210. EXPECT_EQ(file1.content_type, "text/plain");
  3211. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3212. auto file2 = file1_values[1];
  3213. EXPECT_EQ(file2.filename, "world.json");
  3214. EXPECT_EQ(file2.content_type, "application/json");
  3215. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3216. }
  3217. })
  3218. .Post("/empty",
  3219. [&](const Request &req, Response &res) {
  3220. EXPECT_EQ(req.body, "");
  3221. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3222. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3223. res.set_content("empty", "text/plain");
  3224. })
  3225. .Post("/empty-no-content-type",
  3226. [&](const Request &req, Response &res) {
  3227. EXPECT_EQ(req.body, "");
  3228. EXPECT_FALSE(req.has_header("Content-Type"));
  3229. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3230. res.set_content("empty-no-content-type", "text/plain");
  3231. })
  3232. .Post("/path-only",
  3233. [&](const Request &req, Response &res) {
  3234. EXPECT_EQ(req.body, "");
  3235. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3236. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3237. res.set_content("path-only", "text/plain");
  3238. })
  3239. .Post("/path-headers-only",
  3240. [&](const Request &req, Response &res) {
  3241. EXPECT_EQ(req.body, "");
  3242. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3243. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3244. EXPECT_EQ("world", req.get_header_value("hello"));
  3245. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3246. res.set_content("path-headers-only", "text/plain");
  3247. })
  3248. .Post("/post-large",
  3249. [&](const Request &req, Response &res) {
  3250. EXPECT_EQ(req.body, LARGE_DATA);
  3251. res.set_content(req.body, "text/plain");
  3252. })
  3253. .Post("/post-loopback",
  3254. [&](const Request &, Response &res,
  3255. ContentReader const &content_reader) {
  3256. std::string body;
  3257. content_reader([&](const char *data, size_t data_length) {
  3258. body.append(data, data_length);
  3259. return true;
  3260. });
  3261. res.set_content(body, "text/plain");
  3262. })
  3263. .Put("/put-loopback",
  3264. [&](const Request &, Response &res,
  3265. ContentReader const &content_reader) {
  3266. std::string body;
  3267. content_reader([&](const char *data, size_t data_length) {
  3268. body.append(data, data_length);
  3269. return true;
  3270. });
  3271. res.set_content(body, "text/plain");
  3272. })
  3273. .Patch("/patch-loopback",
  3274. [&](const Request &, Response &res,
  3275. ContentReader const &content_reader) {
  3276. std::string body;
  3277. content_reader([&](const char *data, size_t data_length) {
  3278. body.append(data, data_length);
  3279. return true;
  3280. });
  3281. res.set_content(body, "text/plain");
  3282. })
  3283. .Put("/empty-no-content-type",
  3284. [&](const Request &req, Response &res) {
  3285. EXPECT_EQ(req.body, "");
  3286. EXPECT_FALSE(req.has_header("Content-Type"));
  3287. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3288. res.set_content("empty-no-content-type", "text/plain");
  3289. })
  3290. .Put("/put",
  3291. [&](const Request &req, Response &res) {
  3292. EXPECT_EQ(req.body, "PUT");
  3293. res.set_content(req.body, "text/plain");
  3294. })
  3295. .Put("/put-large",
  3296. [&](const Request &req, Response &res) {
  3297. EXPECT_EQ(req.body, LARGE_DATA);
  3298. res.set_content(req.body, "text/plain");
  3299. })
  3300. .Patch("/patch",
  3301. [&](const Request &req, Response &res) {
  3302. EXPECT_EQ(req.body, "PATCH");
  3303. res.set_content(req.body, "text/plain");
  3304. })
  3305. .Delete("/delete",
  3306. [&](const Request & /*req*/, Response &res) {
  3307. res.set_content("DELETE", "text/plain");
  3308. })
  3309. .Delete("/delete-body",
  3310. [&](const Request &req, Response &res) {
  3311. EXPECT_EQ(req.body, "content");
  3312. res.set_content(req.body, "text/plain");
  3313. })
  3314. .Options(R"(\*)",
  3315. [&](const Request & /*req*/, Response &res) {
  3316. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3317. })
  3318. .Get("/request-target",
  3319. [&](const Request &req, Response & /*res*/) {
  3320. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3321. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3322. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3323. })
  3324. .Get("/long-query-value",
  3325. [&](const Request &req, Response & /*res*/) {
  3326. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3327. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3328. })
  3329. .Get("/too-long-query-value",
  3330. [&](const Request &req, Response & /*res*/) {
  3331. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3332. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3333. })
  3334. .Get("/array-param",
  3335. [&](const Request &req, Response & /*res*/) {
  3336. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3337. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3338. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3339. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3340. })
  3341. .Get("/array-param-values",
  3342. [&](const Request &req, Response & /*res*/) {
  3343. auto values = req.get_param_values("array");
  3344. EXPECT_EQ(3u, values.size());
  3345. EXPECT_EQ("value1", values[0]);
  3346. EXPECT_EQ("value2", values[1]);
  3347. EXPECT_EQ("value3", values[2]);
  3348. auto empty = req.get_param_values("nonexistent");
  3349. EXPECT_TRUE(empty.empty());
  3350. })
  3351. .Post("/validate-no-multiple-headers",
  3352. [&](const Request &req, Response & /*res*/) {
  3353. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3354. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3355. })
  3356. .Post("/content_receiver",
  3357. [&](const Request &req, Response &res,
  3358. const ContentReader &content_reader) {
  3359. if (req.is_multipart_form_data()) {
  3360. std::vector<FormData> items;
  3361. content_reader(
  3362. [&](const FormData &file) {
  3363. items.push_back(file);
  3364. return true;
  3365. },
  3366. [&](const char *data, size_t data_length) {
  3367. items.back().content.append(data, data_length);
  3368. return true;
  3369. });
  3370. EXPECT_EQ(5u, items.size());
  3371. {
  3372. const auto &file = get_file_value(items, "text1");
  3373. EXPECT_TRUE(file.filename.empty());
  3374. EXPECT_EQ("text default", file.content);
  3375. }
  3376. {
  3377. const auto &file = get_file_value(items, "text2");
  3378. EXPECT_TRUE(file.filename.empty());
  3379. EXPECT_EQ("aωb", file.content);
  3380. }
  3381. {
  3382. const auto &file = get_file_value(items, "file1");
  3383. EXPECT_EQ("hello.txt", file.filename);
  3384. EXPECT_EQ("text/plain", file.content_type);
  3385. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3386. }
  3387. {
  3388. const auto &file = get_file_value(items, "file2");
  3389. EXPECT_EQ("world.json", file.filename);
  3390. EXPECT_EQ("application/json", file.content_type);
  3391. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3392. }
  3393. {
  3394. const auto &file = get_file_value(items, "file3");
  3395. EXPECT_TRUE(file.filename.empty());
  3396. EXPECT_EQ("application/octet-stream", file.content_type);
  3397. EXPECT_EQ(0u, file.content.size());
  3398. }
  3399. } else {
  3400. std::string body;
  3401. content_reader([&](const char *data, size_t data_length) {
  3402. EXPECT_EQ(7U, data_length);
  3403. body.append(data, data_length);
  3404. return true;
  3405. });
  3406. EXPECT_EQ(body, "content");
  3407. res.set_content(body, "text/plain");
  3408. }
  3409. })
  3410. .Put("/content_receiver",
  3411. [&](const Request & /*req*/, Response &res,
  3412. const ContentReader &content_reader) {
  3413. std::string body;
  3414. content_reader([&](const char *data, size_t data_length) {
  3415. body.append(data, data_length);
  3416. return true;
  3417. });
  3418. EXPECT_EQ(body, "content");
  3419. res.set_content(body, "text/plain");
  3420. })
  3421. .Patch("/content_receiver",
  3422. [&](const Request & /*req*/, Response &res,
  3423. const ContentReader &content_reader) {
  3424. std::string body;
  3425. content_reader([&](const char *data, size_t data_length) {
  3426. body.append(data, data_length);
  3427. return true;
  3428. });
  3429. EXPECT_EQ(body, "content");
  3430. res.set_content(body, "text/plain");
  3431. })
  3432. .Post("/query-string-and-body",
  3433. [&](const Request &req, Response & /*res*/) {
  3434. ASSERT_TRUE(req.has_param("key"));
  3435. EXPECT_EQ(req.get_param_value("key"), "value");
  3436. EXPECT_EQ(req.body, "content");
  3437. })
  3438. .Get("/last-request",
  3439. [&](const Request &req, Response & /*res*/) {
  3440. EXPECT_EQ("close", req.get_header_value("Connection"));
  3441. })
  3442. .Get(R"(/redirect/(\d+))",
  3443. [&](const Request &req, Response &res) {
  3444. auto num = std::stoi(req.matches[1]) + 1;
  3445. std::string url = "/redirect/" + std::to_string(num);
  3446. res.set_redirect(url);
  3447. })
  3448. .Post("/binary",
  3449. [&](const Request &req, Response &res) {
  3450. EXPECT_EQ(4U, req.body.size());
  3451. EXPECT_EQ("application/octet-stream",
  3452. req.get_header_value("Content-Type"));
  3453. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3454. res.set_content(req.body, "application/octet-stream");
  3455. })
  3456. .Put("/binary",
  3457. [&](const Request &req, Response &res) {
  3458. EXPECT_EQ(4U, req.body.size());
  3459. EXPECT_EQ("application/octet-stream",
  3460. req.get_header_value("Content-Type"));
  3461. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3462. res.set_content(req.body, "application/octet-stream");
  3463. })
  3464. .Patch("/binary",
  3465. [&](const Request &req, Response &res) {
  3466. EXPECT_EQ(4U, req.body.size());
  3467. EXPECT_EQ("application/octet-stream",
  3468. req.get_header_value("Content-Type"));
  3469. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3470. res.set_content(req.body, "application/octet-stream");
  3471. })
  3472. .Delete("/binary",
  3473. [&](const Request &req, Response &res) {
  3474. EXPECT_EQ(4U, req.body.size());
  3475. EXPECT_EQ("application/octet-stream",
  3476. req.get_header_value("Content-Type"));
  3477. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3478. res.set_content(req.body, "application/octet-stream");
  3479. })
  3480. .Get("/issue1772",
  3481. [&](const Request & /*req*/, Response &res) {
  3482. res.status = 401;
  3483. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3484. })
  3485. .Delete("/issue609",
  3486. [](const httplib::Request &, httplib::Response &res,
  3487. const httplib::ContentReader &) {
  3488. res.set_content("ok", "text/plain");
  3489. })
  3490. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3491. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3492. .Get("/compress",
  3493. [&](const Request & /*req*/, Response &res) {
  3494. res.set_content(
  3495. "12345678901234567890123456789012345678901234567890123456789"
  3496. "01234567890123456789012345678901234567890",
  3497. "text/plain");
  3498. })
  3499. .Get("/compress-with-charset",
  3500. [&](const Request & /*req*/, Response &res) {
  3501. res.set_content(
  3502. "12345678901234567890123456789012345678901234567890123456789"
  3503. "01234567890123456789012345678901234567890",
  3504. "application/json; charset=utf-8");
  3505. })
  3506. .Get("/nocompress",
  3507. [&](const Request & /*req*/, Response &res) {
  3508. res.set_content(
  3509. "12345678901234567890123456789012345678901234567890123456789"
  3510. "01234567890123456789012345678901234567890",
  3511. "application/octet-stream");
  3512. })
  3513. .Post("/compress-multipart",
  3514. [&](const Request &req, Response & /*res*/) {
  3515. EXPECT_EQ(2u, req.form.fields.size());
  3516. ASSERT_TRUE(!req.form.has_field("???"));
  3517. {
  3518. const auto &text = req.form.get_field("key1");
  3519. EXPECT_EQ("test", text);
  3520. }
  3521. {
  3522. const auto &text = req.form.get_field("key2");
  3523. EXPECT_EQ("--abcdefg123", text);
  3524. }
  3525. })
  3526. #endif
  3527. ;
  3528. persons_["john"] = "programmer";
  3529. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3530. svr_.wait_until_ready();
  3531. }
  3532. virtual void TearDown() {
  3533. svr_.stop();
  3534. if (!request_threads_.empty()) {
  3535. std::this_thread::sleep_for(std::chrono::seconds(1));
  3536. for (auto &t : request_threads_) {
  3537. t.join();
  3538. }
  3539. }
  3540. t_.join();
  3541. }
  3542. map<string, string> persons_;
  3543. #ifdef CPPHTTPLIB_SSL_ENABLED
  3544. SSLClient cli_;
  3545. SSLServer svr_;
  3546. #else
  3547. Client cli_;
  3548. Server svr_;
  3549. #endif
  3550. thread t_;
  3551. std::vector<thread> request_threads_;
  3552. };
  3553. TEST_F(ServerTest, GetMethod200) {
  3554. auto res = cli_.Get("/hi");
  3555. ASSERT_TRUE(res);
  3556. EXPECT_EQ("HTTP/1.1", res->version);
  3557. EXPECT_EQ(StatusCode::OK_200, res->status);
  3558. EXPECT_EQ("OK", res->reason);
  3559. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3560. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3561. EXPECT_EQ("Hello World!", res->body);
  3562. }
  3563. TEST_F(ServerTest, GetEmptyFile) {
  3564. auto res = cli_.Get("/empty_file");
  3565. ASSERT_TRUE(res);
  3566. EXPECT_EQ(StatusCode::OK_200, res->status);
  3567. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3568. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3569. EXPECT_EQ("", res->body);
  3570. }
  3571. TEST_F(ServerTest, GetFileContent) {
  3572. auto res = cli_.Get("/file_content");
  3573. ASSERT_TRUE(res);
  3574. EXPECT_EQ(StatusCode::OK_200, res->status);
  3575. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3576. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3577. EXPECT_EQ("test.html", res->body);
  3578. }
  3579. TEST_F(ServerTest, GetFileContentWithRange) {
  3580. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3581. ASSERT_TRUE(res);
  3582. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3583. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3584. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3585. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3586. EXPECT_EQ("est", res->body);
  3587. }
  3588. TEST_F(ServerTest, GetFileContentWithContentType) {
  3589. auto res = cli_.Get("/file_content_with_content_type");
  3590. ASSERT_TRUE(res);
  3591. EXPECT_EQ(StatusCode::OK_200, res->status);
  3592. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3593. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3594. EXPECT_EQ("file\n", res->body);
  3595. }
  3596. TEST_F(ServerTest, GetInvalidFileContent) {
  3597. auto res = cli_.Get("/invalid_file_content");
  3598. ASSERT_TRUE(res);
  3599. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3600. }
  3601. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3602. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3603. ASSERT_TRUE(res);
  3604. EXPECT_EQ("HTTP/1.1", res->version);
  3605. EXPECT_EQ(StatusCode::OK_200, res->status);
  3606. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3607. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3608. EXPECT_EQ("Hello World!", res->body);
  3609. }
  3610. TEST_F(ServerTest, GetMethod302) {
  3611. auto res = cli_.Get("/");
  3612. ASSERT_TRUE(res);
  3613. EXPECT_EQ(StatusCode::Found_302, res->status);
  3614. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3615. }
  3616. TEST_F(ServerTest, GetMethod302Redirect) {
  3617. cli_.set_follow_location(true);
  3618. auto res = cli_.Get("/");
  3619. ASSERT_TRUE(res);
  3620. EXPECT_EQ(StatusCode::OK_200, res->status);
  3621. EXPECT_EQ("Hello World!", res->body);
  3622. EXPECT_EQ("/hi", res->location);
  3623. }
  3624. TEST_F(ServerTest, GetMethod404) {
  3625. auto res = cli_.Get("/invalid");
  3626. ASSERT_TRUE(res);
  3627. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3628. }
  3629. TEST_F(ServerTest, HeadMethod200) {
  3630. auto res = cli_.Head("/hi");
  3631. ASSERT_TRUE(res);
  3632. EXPECT_EQ(StatusCode::OK_200, res->status);
  3633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3634. EXPECT_TRUE(res->body.empty());
  3635. }
  3636. TEST_F(ServerTest, HeadMethod200Static) {
  3637. auto res = cli_.Head("/mount/dir/index.html");
  3638. ASSERT_TRUE(res);
  3639. EXPECT_EQ(StatusCode::OK_200, res->status);
  3640. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3641. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3642. EXPECT_TRUE(res->body.empty());
  3643. }
  3644. TEST_F(ServerTest, HeadMethod404) {
  3645. auto res = cli_.Head("/invalid");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3648. EXPECT_TRUE(res->body.empty());
  3649. }
  3650. TEST_F(ServerTest, GetMethodPersonJohn) {
  3651. auto res = cli_.Get("/person/john");
  3652. ASSERT_TRUE(res);
  3653. EXPECT_EQ(StatusCode::OK_200, res->status);
  3654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3655. EXPECT_EQ("programmer", res->body);
  3656. }
  3657. TEST_F(ServerTest, PostMethod1) {
  3658. auto res = cli_.Get("/person/john1");
  3659. ASSERT_TRUE(res);
  3660. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3661. res = cli_.Post("/person", "name=john1&note=coder",
  3662. "application/x-www-form-urlencoded");
  3663. ASSERT_TRUE(res);
  3664. ASSERT_EQ(StatusCode::OK_200, res->status);
  3665. res = cli_.Get("/person/john1");
  3666. ASSERT_TRUE(res);
  3667. ASSERT_EQ(StatusCode::OK_200, res->status);
  3668. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3669. ASSERT_EQ("coder", res->body);
  3670. }
  3671. TEST_F(ServerTest, PostMethod2) {
  3672. auto res = cli_.Get("/person/john2");
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3675. Params params;
  3676. params.emplace("name", "john2");
  3677. params.emplace("note", "coder");
  3678. res = cli_.Post("/person", params);
  3679. ASSERT_TRUE(res);
  3680. ASSERT_EQ(StatusCode::OK_200, res->status);
  3681. res = cli_.Get("/person/john2");
  3682. ASSERT_TRUE(res);
  3683. ASSERT_EQ(StatusCode::OK_200, res->status);
  3684. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3685. ASSERT_EQ("coder", res->body);
  3686. }
  3687. TEST_F(ServerTest, PutMethod3) {
  3688. auto res = cli_.Get("/person/john3");
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3691. Params params;
  3692. params.emplace("name", "john3");
  3693. params.emplace("note", "coder");
  3694. res = cli_.Put("/person", params);
  3695. ASSERT_TRUE(res);
  3696. ASSERT_EQ(StatusCode::OK_200, res->status);
  3697. res = cli_.Get("/person/john3");
  3698. ASSERT_TRUE(res);
  3699. ASSERT_EQ(StatusCode::OK_200, res->status);
  3700. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3701. ASSERT_EQ("coder", res->body);
  3702. }
  3703. TEST_F(ServerTest, DeleteMethod1) {
  3704. auto res = cli_.Get("/person/john4");
  3705. ASSERT_TRUE(res);
  3706. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3707. Params params;
  3708. params.emplace("name", "john4");
  3709. params.emplace("note", "coder");
  3710. res = cli_.Post("/person", params);
  3711. ASSERT_TRUE(res);
  3712. ASSERT_EQ(StatusCode::OK_200, res->status);
  3713. res = cli_.Get("/person/john4");
  3714. ASSERT_TRUE(res);
  3715. ASSERT_EQ(StatusCode::OK_200, res->status);
  3716. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3717. ASSERT_EQ("coder", res->body);
  3718. Params delete_params;
  3719. delete_params.emplace("name", "john4");
  3720. res = cli_.Delete("/person", delete_params);
  3721. ASSERT_TRUE(res);
  3722. ASSERT_EQ(StatusCode::OK_200, res->status);
  3723. ASSERT_EQ("DELETED", res->body);
  3724. res = cli_.Get("/person/john4");
  3725. ASSERT_TRUE(res);
  3726. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3727. }
  3728. TEST_F(ServerTest, DeleteMethod2) {
  3729. auto res = cli_.Get("/person/john5");
  3730. ASSERT_TRUE(res);
  3731. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3732. Params params;
  3733. params.emplace("name", "john5");
  3734. params.emplace("note", "developer");
  3735. res = cli_.Post("/person", params);
  3736. ASSERT_TRUE(res);
  3737. ASSERT_EQ(StatusCode::OK_200, res->status);
  3738. res = cli_.Get("/person/john5");
  3739. ASSERT_TRUE(res);
  3740. ASSERT_EQ(StatusCode::OK_200, res->status);
  3741. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3742. ASSERT_EQ("developer", res->body);
  3743. Params delete_params;
  3744. delete_params.emplace("name", "john5");
  3745. Headers headers;
  3746. headers.emplace("Custom-Header", "test-value");
  3747. res = cli_.Delete("/person", headers, delete_params);
  3748. ASSERT_TRUE(res);
  3749. ASSERT_EQ(StatusCode::OK_200, res->status);
  3750. ASSERT_EQ("DELETED", res->body);
  3751. res = cli_.Get("/person/john5");
  3752. ASSERT_TRUE(res);
  3753. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3754. }
  3755. TEST_F(ServerTest, DeleteMethod3) {
  3756. auto res = cli_.Get("/person/john6");
  3757. ASSERT_TRUE(res);
  3758. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3759. Params params;
  3760. params.emplace("name", "john6");
  3761. params.emplace("note", "tester");
  3762. res = cli_.Post("/person", params);
  3763. ASSERT_TRUE(res);
  3764. ASSERT_EQ(StatusCode::OK_200, res->status);
  3765. res = cli_.Get("/person/john6");
  3766. ASSERT_TRUE(res);
  3767. ASSERT_EQ(StatusCode::OK_200, res->status);
  3768. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3769. ASSERT_EQ("tester", res->body);
  3770. Params delete_params;
  3771. delete_params.emplace("name", "john6");
  3772. Headers headers;
  3773. headers.emplace("Custom-Header", "test-value");
  3774. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3775. ASSERT_TRUE(res);
  3776. ASSERT_EQ(StatusCode::OK_200, res->status);
  3777. ASSERT_EQ("DELETED", res->body);
  3778. res = cli_.Get("/person/john6");
  3779. ASSERT_TRUE(res);
  3780. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3781. }
  3782. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3783. Params params;
  3784. params.emplace("json", JSON_DATA);
  3785. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3786. ASSERT_TRUE(res);
  3787. ASSERT_EQ(StatusCode::OK_200, res->status);
  3788. ASSERT_EQ(JSON_DATA, res->body);
  3789. }
  3790. TEST_F(ServerTest, PostEmptyContent) {
  3791. auto res = cli_.Post("/empty", "", "text/plain");
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::OK_200, res->status);
  3794. ASSERT_EQ("empty", res->body);
  3795. }
  3796. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3797. auto res = cli_.Post("/empty-no-content-type");
  3798. ASSERT_TRUE(res);
  3799. ASSERT_EQ(StatusCode::OK_200, res->status);
  3800. ASSERT_EQ("empty-no-content-type", res->body);
  3801. }
  3802. TEST_F(ServerTest, PostPathOnly) {
  3803. auto res = cli_.Post("/path-only");
  3804. ASSERT_TRUE(res);
  3805. ASSERT_EQ(StatusCode::OK_200, res->status);
  3806. ASSERT_EQ("path-only", res->body);
  3807. }
  3808. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3809. auto res = cli_.Post("/path-headers-only",
  3810. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(StatusCode::OK_200, res->status);
  3813. ASSERT_EQ("path-headers-only", res->body);
  3814. }
  3815. TEST_F(ServerTest, PostLarge) {
  3816. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3817. ASSERT_TRUE(res);
  3818. ASSERT_EQ(StatusCode::OK_200, res->status);
  3819. EXPECT_EQ(LARGE_DATA, res->body);
  3820. }
  3821. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3822. auto res = cli_.Put("/empty-no-content-type");
  3823. ASSERT_TRUE(res);
  3824. ASSERT_EQ(StatusCode::OK_200, res->status);
  3825. ASSERT_EQ("empty-no-content-type", res->body);
  3826. }
  3827. TEST_F(ServerTest, GetMethodDir) {
  3828. auto res = cli_.Get("/dir/");
  3829. ASSERT_TRUE(res);
  3830. EXPECT_EQ(StatusCode::OK_200, res->status);
  3831. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3832. auto body = R"(<html>
  3833. <head>
  3834. </head>
  3835. <body>
  3836. <a href="/dir/test.html">Test</a>
  3837. <a href="/hi">hi</a>
  3838. </body>
  3839. </html>
  3840. )";
  3841. EXPECT_EQ(body, res->body);
  3842. }
  3843. TEST_F(ServerTest, GetMethodDirTest) {
  3844. auto res = cli_.Get("/dir/test.html");
  3845. ASSERT_TRUE(res);
  3846. EXPECT_EQ(StatusCode::OK_200, res->status);
  3847. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3848. EXPECT_EQ("test.html", res->body);
  3849. }
  3850. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3851. auto res = cli_.Get("/dir/../dir/test.html");
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(StatusCode::OK_200, res->status);
  3854. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3855. EXPECT_EQ("test.html", res->body);
  3856. }
  3857. TEST_F(ServerTest, GetMethodInvalidPath) {
  3858. auto res = cli_.Get("/dir/../test.html");
  3859. ASSERT_TRUE(res);
  3860. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3861. }
  3862. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3863. auto res = cli_.Get("/../www/dir/test.html");
  3864. ASSERT_TRUE(res);
  3865. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3866. }
  3867. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3868. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3869. ASSERT_TRUE(res);
  3870. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3871. }
  3872. TEST_F(ServerTest, GetMethodDirMountTest) {
  3873. auto res = cli_.Get("/mount/dir/test.html");
  3874. ASSERT_TRUE(res);
  3875. EXPECT_EQ(StatusCode::OK_200, res->status);
  3876. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3877. EXPECT_EQ("test.html", res->body);
  3878. }
  3879. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3880. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3881. ASSERT_TRUE(res);
  3882. EXPECT_EQ(StatusCode::OK_200, res->status);
  3883. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3884. EXPECT_EQ("test.html", res->body);
  3885. }
  3886. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3887. auto res = cli_.Get("/mount/dir/../test.html");
  3888. ASSERT_TRUE(res);
  3889. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3890. }
  3891. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3892. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3893. ASSERT_TRUE(res);
  3894. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3895. }
  3896. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3897. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3898. ASSERT_TRUE(res);
  3899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3900. }
  3901. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3902. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3903. ASSERT_TRUE(res);
  3904. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3905. }
  3906. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3907. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3908. ASSERT_TRUE(res);
  3909. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3910. }
  3911. TEST_F(ServerTest, PostMethod303) {
  3912. auto res = cli_.Post("/1", "body", "text/plain");
  3913. ASSERT_TRUE(res);
  3914. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3915. EXPECT_EQ("/2", res->get_header_value("Location"));
  3916. }
  3917. TEST_F(ServerTest, PostMethod303Redirect) {
  3918. cli_.set_follow_location(true);
  3919. auto res = cli_.Post("/1", "body", "text/plain");
  3920. ASSERT_TRUE(res);
  3921. EXPECT_EQ(StatusCode::OK_200, res->status);
  3922. EXPECT_EQ("redirected.", res->body);
  3923. EXPECT_EQ("/2", res->location);
  3924. }
  3925. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3926. auto res = cli_.Get("/dir/test.abcde");
  3927. ASSERT_TRUE(res);
  3928. EXPECT_EQ(StatusCode::OK_200, res->status);
  3929. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3930. EXPECT_EQ("abcde", res->body);
  3931. }
  3932. TEST_F(ServerTest, StaticFileRange) {
  3933. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3934. ASSERT_TRUE(res);
  3935. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3936. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3937. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3938. EXPECT_EQ(true, res->has_header("Content-Range"));
  3939. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3940. EXPECT_EQ(std::string("cd"), res->body);
  3941. }
  3942. TEST_F(ServerTest, StaticFileRanges) {
  3943. auto res =
  3944. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3945. ASSERT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3947. EXPECT_TRUE(
  3948. res->get_header_value("Content-Type")
  3949. .find(
  3950. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3951. 0);
  3952. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3953. }
  3954. TEST_F(ServerTest, StaticFileRangeHead) {
  3955. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3956. ASSERT_TRUE(res);
  3957. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3958. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3959. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3960. EXPECT_EQ(true, res->has_header("Content-Range"));
  3961. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3962. }
  3963. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3964. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3965. ASSERT_TRUE(res);
  3966. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3968. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3969. EXPECT_EQ(true, res->has_header("Content-Range"));
  3970. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3971. res->get_header_value("Content-Range"));
  3972. EXPECT_EQ("LAST\n", res->body);
  3973. }
  3974. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3975. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3976. ASSERT_TRUE(res);
  3977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3978. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3979. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3980. EXPECT_EQ(true, res->has_header("Content-Range"));
  3981. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3982. }
  3983. TEST_F(ServerTest, StaticFileBigFile) {
  3984. auto res = cli_.Get("/dir/1MB.txt");
  3985. ASSERT_TRUE(res);
  3986. EXPECT_EQ(StatusCode::OK_200, res->status);
  3987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3988. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3989. }
  3990. TEST_F(ServerTest, InvalidBaseDirMount) {
  3991. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3992. }
  3993. TEST_F(ServerTest, Binary) {
  3994. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3995. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3996. "application/octet-stream");
  3997. ASSERT_TRUE(res);
  3998. ASSERT_EQ(StatusCode::OK_200, res->status);
  3999. ASSERT_EQ(4U, res->body.size());
  4000. res = cli_.Put("/binary", binary.data(), binary.size(),
  4001. "application/octet-stream");
  4002. ASSERT_TRUE(res);
  4003. ASSERT_EQ(StatusCode::OK_200, res->status);
  4004. ASSERT_EQ(4U, res->body.size());
  4005. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4006. "application/octet-stream");
  4007. ASSERT_TRUE(res);
  4008. ASSERT_EQ(StatusCode::OK_200, res->status);
  4009. ASSERT_EQ(4U, res->body.size());
  4010. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4011. "application/octet-stream");
  4012. ASSERT_TRUE(res);
  4013. ASSERT_EQ(StatusCode::OK_200, res->status);
  4014. ASSERT_EQ(4U, res->body.size());
  4015. }
  4016. TEST_F(ServerTest, BinaryString) {
  4017. auto binary = std::string("\x00\x01\x02\x03", 4);
  4018. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4019. ASSERT_TRUE(res);
  4020. ASSERT_EQ(StatusCode::OK_200, res->status);
  4021. ASSERT_EQ(4U, res->body.size());
  4022. res = cli_.Put("/binary", binary, "application/octet-stream");
  4023. ASSERT_TRUE(res);
  4024. ASSERT_EQ(StatusCode::OK_200, res->status);
  4025. ASSERT_EQ(4U, res->body.size());
  4026. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4027. ASSERT_TRUE(res);
  4028. ASSERT_EQ(StatusCode::OK_200, res->status);
  4029. ASSERT_EQ(4U, res->body.size());
  4030. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4031. ASSERT_TRUE(res);
  4032. ASSERT_EQ(StatusCode::OK_200, res->status);
  4033. ASSERT_EQ(4U, res->body.size());
  4034. }
  4035. TEST_F(ServerTest, EmptyRequest) {
  4036. auto res = cli_.Get("");
  4037. ASSERT_TRUE(!res);
  4038. EXPECT_EQ(Error::Connection, res.error());
  4039. }
  4040. TEST_F(ServerTest, LongRequest) {
  4041. std::string request;
  4042. for (size_t i = 0; i < 545; i++) {
  4043. request += "/TooLongRequest";
  4044. }
  4045. request += "OK";
  4046. auto res = cli_.Get(request.c_str());
  4047. ASSERT_TRUE(res);
  4048. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4049. }
  4050. TEST_F(ServerTest, TooLongRequest) {
  4051. std::string request;
  4052. for (size_t i = 0; i < 546; i++) {
  4053. request += "/TooLongRequest";
  4054. }
  4055. request += "_NG";
  4056. auto start = std::chrono::high_resolution_clock::now();
  4057. cli_.set_keep_alive(true);
  4058. auto res = cli_.Get(request.c_str());
  4059. auto end = std::chrono::high_resolution_clock::now();
  4060. auto elapsed =
  4061. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4062. .count();
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4065. EXPECT_LE(elapsed, 1000);
  4066. EXPECT_EQ("close", res->get_header_value("Connection"));
  4067. EXPECT_FALSE(cli_.is_socket_open());
  4068. }
  4069. TEST_F(ServerTest, AlmostTooLongRequest) {
  4070. // test for #2046 - URI length check shouldn't include other content on req
  4071. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4072. // leading /, space, HTTP/1.1)
  4073. std::string request =
  4074. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4075. auto res = cli_.Get(request.c_str());
  4076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4077. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4078. }
  4079. TEST_F(ServerTest, LongHeader) {
  4080. Request req;
  4081. req.method = "GET";
  4082. req.path = "/hi";
  4083. std::string host_and_port;
  4084. host_and_port += HOST;
  4085. host_and_port += ":";
  4086. host_and_port += std::to_string(PORT);
  4087. req.headers.emplace("Host", host_and_port.c_str());
  4088. req.headers.emplace("Accept", "*/*");
  4089. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4090. req.headers.emplace(
  4091. "Header-Name",
  4092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4114. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4115. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4116. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4117. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4118. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4119. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4120. "@@@@@@@@@@@@@@@@");
  4121. auto res = std::make_shared<Response>();
  4122. auto error = Error::Success;
  4123. auto ret = cli_.send(req, *res, error);
  4124. ASSERT_TRUE(ret);
  4125. EXPECT_EQ(StatusCode::OK_200, res->status);
  4126. }
  4127. TEST_F(ServerTest, LongQueryValue) {
  4128. auto start = std::chrono::high_resolution_clock::now();
  4129. cli_.set_keep_alive(true);
  4130. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4131. auto end = std::chrono::high_resolution_clock::now();
  4132. auto elapsed =
  4133. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4134. .count();
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4137. EXPECT_LE(elapsed, 1000);
  4138. EXPECT_EQ("close", res->get_header_value("Connection"));
  4139. EXPECT_FALSE(cli_.is_socket_open());
  4140. }
  4141. TEST_F(ServerTest, TooLongQueryValue) {
  4142. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4143. ASSERT_FALSE(res);
  4144. EXPECT_EQ(Error::Read, res.error());
  4145. }
  4146. TEST_F(ServerTest, TooLongHeader) {
  4147. Request req;
  4148. req.method = "GET";
  4149. req.path = "/hi";
  4150. std::string host_and_port;
  4151. host_and_port += HOST;
  4152. host_and_port += ":";
  4153. host_and_port += std::to_string(PORT);
  4154. req.headers.emplace("Host", host_and_port.c_str());
  4155. req.headers.emplace("Accept", "*/*");
  4156. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4157. req.headers.emplace(
  4158. "Header-Name",
  4159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4181. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4182. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4183. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4184. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4185. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4186. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4187. "@@@@@@@@@@@@@@@@@");
  4188. auto res = std::make_shared<Response>();
  4189. auto error = Error::Success;
  4190. auto ret = cli_.send(req, *res, error);
  4191. ASSERT_TRUE(ret);
  4192. EXPECT_EQ(StatusCode::OK_200, res->status);
  4193. }
  4194. TEST_F(ServerTest, HeaderCountAtLimit) {
  4195. // Test with headers just under the 100 limit
  4196. httplib::Headers headers;
  4197. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4198. // This should keep us just under the 100 header limit
  4199. for (int i = 0; i < 95; i++) {
  4200. std::string name = "X-Test-Header-" + std::to_string(i);
  4201. std::string value = "value" + std::to_string(i);
  4202. headers.emplace(name, value);
  4203. }
  4204. // This should work fine as we're under the limit
  4205. auto res = cli_.Get("/hi", headers);
  4206. EXPECT_TRUE(res);
  4207. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4208. }
  4209. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4210. // Test with many headers to exceed the 100 limit
  4211. httplib::Headers headers;
  4212. // Add 150 headers to definitely exceed the 100 limit
  4213. for (int i = 0; i < 150; i++) {
  4214. std::string name = "X-Test-Header-" + std::to_string(i);
  4215. std::string value = "value" + std::to_string(i);
  4216. headers.emplace(name, value);
  4217. }
  4218. // This should fail due to exceeding header count limit
  4219. cli_.set_keep_alive(true);
  4220. auto res = cli_.Get("/hi", headers);
  4221. // The server should respond with 400 Bad Request
  4222. ASSERT_TRUE(res);
  4223. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4224. EXPECT_EQ("close", res->get_header_value("Connection"));
  4225. EXPECT_FALSE(cli_.is_socket_open());
  4226. }
  4227. TEST_F(ServerTest, PercentEncoding) {
  4228. auto res = cli_.Get("/e%6edwith%");
  4229. ASSERT_TRUE(res);
  4230. EXPECT_EQ(StatusCode::OK_200, res->status);
  4231. }
  4232. TEST_F(ServerTest, PercentEncodingUnicode) {
  4233. auto res = cli_.Get("/e%u006edwith%");
  4234. ASSERT_TRUE(res);
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. }
  4237. TEST_F(ServerTest, InvalidPercentEncoding) {
  4238. auto res = cli_.Get("/%endwith%");
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4241. }
  4242. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4243. auto res = cli_.Get("/%uendwith%");
  4244. ASSERT_TRUE(res);
  4245. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4246. }
  4247. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4248. auto res = cli_.Get("/hello?aaa=bbb%");
  4249. ASSERT_TRUE(res);
  4250. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4251. }
  4252. TEST_F(ServerTest, PlusSignEncoding) {
  4253. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4254. ASSERT_TRUE(res);
  4255. EXPECT_EQ(StatusCode::OK_200, res->status);
  4256. EXPECT_EQ("a +b", res->body);
  4257. }
  4258. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4259. // This test simulates a potential DoS attack using many headers
  4260. // to verify our security fix prevents memory exhaustion
  4261. httplib::Headers attack_headers;
  4262. // Attempt to add many headers like an attacker would (200 headers to far
  4263. // exceed limit)
  4264. for (int i = 0; i < 200; i++) {
  4265. std::string name = "X-Attack-Header-" + std::to_string(i);
  4266. std::string value = "attack_payload_" + std::to_string(i);
  4267. attack_headers.emplace(name, value);
  4268. }
  4269. // Try to POST with excessive headers
  4270. cli_.set_keep_alive(true);
  4271. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4272. // Should either fail or return 400 Bad Request due to security limit
  4273. if (res) {
  4274. // If we get a response, it should be 400 Bad Request
  4275. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4276. EXPECT_EQ("close", res->get_header_value("Connection"));
  4277. }
  4278. EXPECT_FALSE(cli_.is_socket_open());
  4279. }
  4280. TEST_F(ServerTest, MultipartFormData) {
  4281. UploadFormDataItems items = {
  4282. {"text1", "text default", "", ""},
  4283. {"text2", "aωb", "", ""},
  4284. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4285. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4286. {"file3", "", "", "application/octet-stream"},
  4287. {"file4", "", "", " application/json tmp-string "}};
  4288. auto res = cli_.Post("/multipart", items);
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::OK_200, res->status);
  4291. }
  4292. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4293. UploadFormDataItems items = {
  4294. {"text", "default text", "", ""},
  4295. {"multi_text1", "aaaaa", "", ""},
  4296. {"multi_text1", "bbbbb", "", ""},
  4297. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4298. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4299. "application/json"},
  4300. };
  4301. auto res = cli_.Post("/multipart/multi_file_values", items);
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. }
  4305. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4306. auto res = cli_.Get("/hi");
  4307. ASSERT_TRUE(res);
  4308. EXPECT_EQ(StatusCode::OK_200, res->status);
  4309. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4310. EXPECT_EQ("Hello World!", res->body);
  4311. }
  4312. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4313. Request req;
  4314. req.method = "POST";
  4315. req.path = "/chunked";
  4316. std::string host_and_port;
  4317. host_and_port += HOST;
  4318. host_and_port += ":";
  4319. host_and_port += std::to_string(PORT);
  4320. req.headers.emplace("Host", host_and_port.c_str());
  4321. req.headers.emplace("Accept", "*/*");
  4322. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4323. req.headers.emplace("Content-Type", "text/plain");
  4324. req.headers.emplace("Content-Length", "0");
  4325. req.headers.emplace(
  4326. "Transfer-Encoding",
  4327. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4328. // Client does not chunk, so make a chunked body manually.
  4329. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4330. auto res = std::make_shared<Response>();
  4331. auto error = Error::Success;
  4332. auto ret = cli_.send(req, *res, error);
  4333. ASSERT_TRUE(ret);
  4334. EXPECT_EQ(StatusCode::OK_200, res->status);
  4335. }
  4336. TEST_F(ServerTest, GetStreamed2) {
  4337. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4340. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4341. EXPECT_EQ(true, res->has_header("Content-Range"));
  4342. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4343. EXPECT_EQ(std::string("ab"), res->body);
  4344. }
  4345. TEST_F(ServerTest, GetStreamed) {
  4346. auto res = cli_.Get("/streamed");
  4347. ASSERT_TRUE(res);
  4348. EXPECT_EQ(StatusCode::OK_200, res->status);
  4349. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4350. EXPECT_EQ(std::string("aaabbb"), res->body);
  4351. }
  4352. TEST_F(ServerTest, GetStreamedWithRange1) {
  4353. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4354. ASSERT_TRUE(res);
  4355. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4356. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4357. EXPECT_EQ(true, res->has_header("Content-Range"));
  4358. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4359. EXPECT_EQ(std::string("def"), res->body);
  4360. }
  4361. TEST_F(ServerTest, GetStreamedWithRange2) {
  4362. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4363. ASSERT_TRUE(res);
  4364. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4365. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4366. EXPECT_EQ(true, res->has_header("Content-Range"));
  4367. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4368. EXPECT_EQ(std::string("bcdefg"), res->body);
  4369. }
  4370. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4371. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4372. ASSERT_TRUE(res);
  4373. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4374. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4375. EXPECT_EQ(true, res->has_header("Content-Range"));
  4376. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4377. EXPECT_EQ(std::string("efg"), res->body);
  4378. }
  4379. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4380. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4381. ASSERT_TRUE(res);
  4382. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4383. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4384. EXPECT_EQ(false, res->has_header("Content-Range"));
  4385. EXPECT_EQ(0U, res->body.size());
  4386. }
  4387. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4388. auto res = cli_.Get("/streamed-with-range",
  4389. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4390. "92233720368547758079223372036854775807"}});
  4391. ASSERT_TRUE(res);
  4392. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4393. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4394. EXPECT_EQ(false, res->has_header("Content-Range"));
  4395. EXPECT_EQ(0U, res->body.size());
  4396. }
  4397. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4398. auto res = cli_.Get(
  4399. "/with-range",
  4400. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4401. {"Accept-Encoding", ""}});
  4402. ASSERT_TRUE(res);
  4403. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4404. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4405. EXPECT_EQ(true, res->has_header("Content-Range"));
  4406. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4407. EXPECT_EQ(std::string("abcdefg"), res->body);
  4408. }
  4409. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4410. auto res = cli_.Get("/with-range", {
  4411. {"Range", "bytes=0-"},
  4412. {"Accept-Encoding", ""},
  4413. });
  4414. ASSERT_TRUE(res);
  4415. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4416. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4417. EXPECT_EQ(true, res->has_header("Content-Range"));
  4418. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4419. EXPECT_EQ(std::string("abcdefg"), res->body);
  4420. }
  4421. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4422. auto res =
  4423. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4424. ASSERT_TRUE(res);
  4425. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4426. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4427. EXPECT_EQ(false, res->has_header("Content-Range"));
  4428. EXPECT_EQ(267U, res->body.size());
  4429. // Check that both range contents are present
  4430. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4431. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4432. // Check that Content-Range headers are present for both ranges
  4433. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4434. std::string::npos);
  4435. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4436. std::string::npos);
  4437. }
  4438. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4439. Ranges ranges;
  4440. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4441. ranges.emplace_back(0, -1);
  4442. }
  4443. auto res =
  4444. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4445. ASSERT_TRUE(res);
  4446. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4447. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4448. EXPECT_EQ(false, res->has_header("Content-Range"));
  4449. EXPECT_EQ(0U, res->body.size());
  4450. }
  4451. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4452. auto res =
  4453. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4454. ASSERT_TRUE(res);
  4455. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4456. EXPECT_EQ(5U, res->body.size());
  4457. // Check that overlapping ranges are coalesced into a single range
  4458. EXPECT_EQ("bcdef", res->body);
  4459. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4460. // Should be single range, not multipart
  4461. EXPECT_TRUE(res->has_header("Content-Range"));
  4462. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4463. }
  4464. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4465. auto res =
  4466. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4469. EXPECT_EQ(268U, res->body.size());
  4470. // Check that both range contents are present
  4471. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4472. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4473. // Check that Content-Range headers are present for both ranges
  4474. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4475. std::string::npos);
  4476. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4477. std::string::npos);
  4478. }
  4479. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4480. auto res =
  4481. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4482. ASSERT_TRUE(res);
  4483. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4484. EXPECT_EQ(269U, res->body.size());
  4485. // Check that both duplicate range contents are present
  4486. size_t first_abc = res->body.find("abc\r\n");
  4487. EXPECT_TRUE(first_abc != std::string::npos);
  4488. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4489. EXPECT_TRUE(second_abc != std::string::npos);
  4490. // Check that Content-Range headers are present for both ranges
  4491. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4492. EXPECT_TRUE(first_range != std::string::npos);
  4493. size_t second_range =
  4494. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4495. EXPECT_TRUE(second_range != std::string::npos);
  4496. }
  4497. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4498. auto res = cli_.Get("/streamed-with-range?error",
  4499. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4500. ASSERT_TRUE(res);
  4501. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4502. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4503. EXPECT_EQ(false, res->has_header("Content-Range"));
  4504. EXPECT_EQ(0U, res->body.size());
  4505. }
  4506. TEST_F(ServerTest, GetStreamedEndless) {
  4507. uint64_t offset = 0;
  4508. auto res = cli_.Get("/streamed-cancel",
  4509. [&](const char * /*data*/, uint64_t data_length) {
  4510. if (offset < 100) {
  4511. offset += data_length;
  4512. return true;
  4513. }
  4514. return false;
  4515. });
  4516. ASSERT_TRUE(!res);
  4517. EXPECT_EQ(Error::Canceled, res.error());
  4518. }
  4519. TEST_F(ServerTest, ClientStop) {
  4520. std::atomic_size_t count{4};
  4521. std::vector<std::thread> threads;
  4522. for (auto i = count.load(); i != 0; --i) {
  4523. threads.emplace_back([&]() {
  4524. auto res = cli_.Get("/streamed-cancel",
  4525. [&](const char *, uint64_t) { return true; });
  4526. --count;
  4527. ASSERT_TRUE(!res);
  4528. EXPECT_TRUE(res.error() == Error::Canceled ||
  4529. res.error() == Error::Read || res.error() == Error::Write);
  4530. });
  4531. }
  4532. std::this_thread::sleep_for(std::chrono::seconds(2));
  4533. while (count != 0) {
  4534. cli_.stop();
  4535. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4536. }
  4537. for (auto &t : threads) {
  4538. t.join();
  4539. }
  4540. }
  4541. TEST_F(ServerTest, GetWithRange1) {
  4542. auto res = cli_.Get("/with-range", {
  4543. make_range_header({{3, 5}}),
  4544. {"Accept-Encoding", ""},
  4545. });
  4546. ASSERT_TRUE(res);
  4547. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4548. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4549. EXPECT_EQ(true, res->has_header("Content-Range"));
  4550. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4551. EXPECT_EQ(std::string("def"), res->body);
  4552. }
  4553. TEST_F(ServerTest, GetWithRange2) {
  4554. auto res = cli_.Get("/with-range", {
  4555. make_range_header({{1, -1}}),
  4556. {"Accept-Encoding", ""},
  4557. });
  4558. ASSERT_TRUE(res);
  4559. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4560. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4561. EXPECT_EQ(true, res->has_header("Content-Range"));
  4562. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4563. EXPECT_EQ(std::string("bcdefg"), res->body);
  4564. }
  4565. TEST_F(ServerTest, GetWithRange3) {
  4566. auto res = cli_.Get("/with-range", {
  4567. make_range_header({{0, 0}}),
  4568. {"Accept-Encoding", ""},
  4569. });
  4570. ASSERT_TRUE(res);
  4571. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4572. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4573. EXPECT_EQ(true, res->has_header("Content-Range"));
  4574. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4575. EXPECT_EQ(std::string("a"), res->body);
  4576. }
  4577. TEST_F(ServerTest, GetWithRange4) {
  4578. auto res = cli_.Get("/with-range", {
  4579. make_range_header({{-1, 2}}),
  4580. {"Accept-Encoding", ""},
  4581. });
  4582. ASSERT_TRUE(res);
  4583. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4584. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4585. EXPECT_EQ(true, res->has_header("Content-Range"));
  4586. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4587. EXPECT_EQ(std::string("fg"), res->body);
  4588. }
  4589. TEST_F(ServerTest, GetWithRange5) {
  4590. auto res = cli_.Get("/with-range", {
  4591. make_range_header({{0, 5}}),
  4592. {"Accept-Encoding", ""},
  4593. });
  4594. ASSERT_TRUE(res);
  4595. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4596. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4597. EXPECT_EQ(true, res->has_header("Content-Range"));
  4598. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4599. EXPECT_EQ(std::string("abcdef"), res->body);
  4600. }
  4601. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4602. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4603. ASSERT_TRUE(res);
  4604. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4605. }
  4606. TEST_F(ServerTest, GetWithRangeMultipart) {
  4607. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4608. ASSERT_TRUE(res);
  4609. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4610. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4611. EXPECT_EQ(false, res->has_header("Content-Range"));
  4612. EXPECT_EQ(267U, res->body.size());
  4613. }
  4614. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4615. auto res =
  4616. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4617. ASSERT_TRUE(res);
  4618. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4619. }
  4620. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4621. auto res = cli_.Get("/with-range-customized-response",
  4622. {{make_range_header({{1, 2}})}});
  4623. ASSERT_TRUE(res);
  4624. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4625. EXPECT_EQ(true, res->has_header("Content-Length"));
  4626. EXPECT_EQ(false, res->has_header("Content-Range"));
  4627. EXPECT_EQ(JSON_DATA, res->body);
  4628. }
  4629. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4630. auto res = cli_.Get("/with-range-customized-response",
  4631. {{make_range_header({{1, 2}, {4, 5}})}});
  4632. ASSERT_TRUE(res);
  4633. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4634. EXPECT_EQ(true, res->has_header("Content-Length"));
  4635. EXPECT_EQ(false, res->has_header("Content-Range"));
  4636. EXPECT_EQ(JSON_DATA, res->body);
  4637. }
  4638. TEST_F(ServerTest, Issue1772) {
  4639. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4640. ASSERT_TRUE(res);
  4641. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4642. }
  4643. TEST_F(ServerTest, Issue609) {
  4644. auto res = cli_.Delete("/issue609");
  4645. ASSERT_TRUE(res);
  4646. EXPECT_EQ(StatusCode::OK_200, res->status);
  4647. EXPECT_EQ(std::string("ok"), res->body);
  4648. }
  4649. TEST_F(ServerTest, GetStreamedChunked) {
  4650. auto res = cli_.Get("/streamed-chunked");
  4651. ASSERT_TRUE(res);
  4652. EXPECT_EQ(StatusCode::OK_200, res->status);
  4653. EXPECT_EQ(std::string("123456789"), res->body);
  4654. }
  4655. TEST_F(ServerTest, GetStreamedChunked2) {
  4656. auto res = cli_.Get("/streamed-chunked2");
  4657. ASSERT_TRUE(res);
  4658. EXPECT_EQ(StatusCode::OK_200, res->status);
  4659. EXPECT_EQ(std::string("123456789"), res->body);
  4660. }
  4661. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4662. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4663. ASSERT_TRUE(res);
  4664. EXPECT_EQ(StatusCode::OK_200, res->status);
  4665. EXPECT_EQ(std::string("123456789"), res->body);
  4666. EXPECT_TRUE(res->has_header("Trailer"));
  4667. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4668. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4669. // Trailers are now stored separately from headers (security fix)
  4670. EXPECT_EQ(2U, res->trailers.size());
  4671. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4672. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4673. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4674. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4675. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4676. // Verify trailers are NOT in headers (security verification)
  4677. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4678. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4679. }
  4680. TEST_F(ServerTest, LargeChunkedPost) {
  4681. Request req;
  4682. req.method = "POST";
  4683. req.path = "/large-chunked";
  4684. std::string host_and_port;
  4685. host_and_port += HOST;
  4686. host_and_port += ":";
  4687. host_and_port += std::to_string(PORT);
  4688. req.headers.emplace("Host", host_and_port.c_str());
  4689. req.headers.emplace("Accept", "*/*");
  4690. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4691. req.headers.emplace("Content-Type", "text/plain");
  4692. req.headers.emplace("Content-Length", "0");
  4693. req.headers.emplace("Transfer-Encoding", "chunked");
  4694. std::string long_string(30 * 1024u, 'a');
  4695. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4696. // Attempt to make a large enough post to exceed OS buffers, to test that
  4697. // the server handles short reads if the full chunk data isn't available.
  4698. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4699. auto res = std::make_shared<Response>();
  4700. auto error = Error::Success;
  4701. auto ret = cli_.send(req, *res, error);
  4702. ASSERT_TRUE(ret);
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. }
  4705. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4706. auto res = cli_.Get("/remote_addr");
  4707. ASSERT_TRUE(res);
  4708. EXPECT_EQ(StatusCode::OK_200, res->status);
  4709. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4710. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4711. }
  4712. TEST_F(ServerTest, GetMethodLocalAddr) {
  4713. auto res = cli_.Get("/local_addr");
  4714. ASSERT_TRUE(res);
  4715. EXPECT_EQ(StatusCode::OK_200, res->status);
  4716. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4717. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4718. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4719. }
  4720. TEST_F(ServerTest, HTTPResponseSplitting) {
  4721. auto res = cli_.Get("/http_response_splitting");
  4722. ASSERT_TRUE(res);
  4723. EXPECT_EQ(StatusCode::OK_200, res->status);
  4724. }
  4725. TEST_F(ServerTest, SlowRequest) {
  4726. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4727. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4728. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4729. }
  4730. #if 0
  4731. TEST_F(ServerTest, SlowPost) {
  4732. char buffer[64 * 1024];
  4733. memset(buffer, 0x42, sizeof(buffer));
  4734. auto res = cli_.Post(
  4735. "/slowpost", 64 * 1024 * 1024,
  4736. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4737. auto ret = sink.write(buffer, sizeof(buffer));
  4738. EXPECT_TRUE(ret);
  4739. return true;
  4740. },
  4741. "text/plain");
  4742. ASSERT_TRUE(res);
  4743. EXPECT_EQ(StatusCode::OK_200, res->status);
  4744. }
  4745. TEST_F(ServerTest, SlowPostFail) {
  4746. char buffer[64 * 1024];
  4747. memset(buffer, 0x42, sizeof(buffer));
  4748. cli_.set_write_timeout(std::chrono::seconds(0));
  4749. auto res = cli_.Post(
  4750. "/slowpost", 64 * 1024 * 1024,
  4751. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4752. sink.write(buffer, sizeof(buffer));
  4753. return true;
  4754. },
  4755. "text/plain");
  4756. ASSERT_TRUE(!res);
  4757. EXPECT_EQ(Error::Write, res.error());
  4758. }
  4759. #endif
  4760. TEST_F(ServerTest, Put) {
  4761. auto res = cli_.Put("/put", "PUT", "text/plain");
  4762. ASSERT_TRUE(res);
  4763. EXPECT_EQ(StatusCode::OK_200, res->status);
  4764. EXPECT_EQ("PUT", res->body);
  4765. }
  4766. TEST_F(ServerTest, PutWithContentProvider) {
  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, PostWithContentProviderAbort) {
  4779. auto res = cli_.Post(
  4780. "/post", 42,
  4781. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4782. return false;
  4783. },
  4784. "text/plain");
  4785. ASSERT_TRUE(!res);
  4786. EXPECT_EQ(Error::Canceled, res.error());
  4787. }
  4788. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4789. auto res = cli_.Put(
  4790. "/put",
  4791. [](size_t /*offset*/, DataSink &sink) {
  4792. sink.os << "PUT";
  4793. sink.done();
  4794. return true;
  4795. },
  4796. "text/plain");
  4797. ASSERT_TRUE(res);
  4798. EXPECT_EQ(StatusCode::OK_200, res->status);
  4799. EXPECT_EQ("PUT", res->body);
  4800. }
  4801. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4802. auto res = cli_.Post(
  4803. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4804. "text/plain");
  4805. ASSERT_TRUE(!res);
  4806. EXPECT_EQ(Error::Canceled, res.error());
  4807. }
  4808. TEST_F(ServerTest, PostLoopBack) {
  4809. std::string body;
  4810. auto res = cli_.Post(
  4811. "/post-loopback", 9,
  4812. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4813. EXPECT_EQ(9u, length);
  4814. sink.write("123", 3);
  4815. sink.write("456", 3);
  4816. sink.write("789", 3);
  4817. return true;
  4818. },
  4819. "text/plain",
  4820. [&body](const char *data, size_t data_length) {
  4821. body.append(data, data_length);
  4822. return true;
  4823. });
  4824. ASSERT_TRUE(res);
  4825. EXPECT_EQ(StatusCode::OK_200, res->status);
  4826. EXPECT_EQ("123456789", body);
  4827. }
  4828. TEST_F(ServerTest, PutLoopBack) {
  4829. std::string body;
  4830. auto res = cli_.Put(
  4831. "/put-loopback", 9,
  4832. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4833. EXPECT_EQ(9u, length);
  4834. sink.write("123", 3);
  4835. sink.write("456", 3);
  4836. sink.write("789", 3);
  4837. return true;
  4838. },
  4839. "text/plain",
  4840. [&body](const char *data, size_t data_length) {
  4841. body.append(data, data_length);
  4842. return true;
  4843. });
  4844. ASSERT_TRUE(res);
  4845. EXPECT_EQ(StatusCode::OK_200, res->status);
  4846. EXPECT_EQ("123456789", body);
  4847. }
  4848. TEST_F(ServerTest, PatchLoopBack) {
  4849. std::string body;
  4850. auto res = cli_.Patch(
  4851. "/patch-loopback", 9,
  4852. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4853. EXPECT_EQ(9u, length);
  4854. sink.write("123", 3);
  4855. sink.write("456", 3);
  4856. sink.write("789", 3);
  4857. return true;
  4858. },
  4859. "text/plain",
  4860. [&body](const char *data, size_t data_length) {
  4861. body.append(data, data_length);
  4862. return true;
  4863. });
  4864. ASSERT_TRUE(res);
  4865. EXPECT_EQ(StatusCode::OK_200, res->status);
  4866. EXPECT_EQ("123456789", body);
  4867. }
  4868. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4869. std::string body;
  4870. auto res = cli_.Post(
  4871. "/post-loopback",
  4872. [](size_t /*offset*/, DataSink &sink) {
  4873. sink.write("123", 3);
  4874. sink.write("456", 3);
  4875. sink.write("789", 3);
  4876. sink.done();
  4877. return true;
  4878. },
  4879. "text/plain",
  4880. [&body](const char *data, size_t data_length) {
  4881. body.append(data, data_length);
  4882. return true;
  4883. });
  4884. ASSERT_TRUE(res);
  4885. EXPECT_EQ(StatusCode::OK_200, res->status);
  4886. EXPECT_EQ("123456789", body);
  4887. }
  4888. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4889. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4890. cli_.set_compress(true);
  4891. auto res = cli_.Put(
  4892. "/put", 3,
  4893. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4894. sink.os << "PUT";
  4895. return true;
  4896. },
  4897. "text/plain");
  4898. ASSERT_TRUE(res);
  4899. EXPECT_EQ(StatusCode::OK_200, res->status);
  4900. EXPECT_EQ("PUT", res->body);
  4901. }
  4902. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4903. cli_.set_compress(true);
  4904. auto res = cli_.Post(
  4905. "/post", 42,
  4906. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4907. return false;
  4908. },
  4909. "text/plain");
  4910. ASSERT_TRUE(!res);
  4911. EXPECT_EQ(Error::Canceled, res.error());
  4912. }
  4913. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4914. cli_.set_compress(true);
  4915. auto res = cli_.Put(
  4916. "/put",
  4917. [](size_t /*offset*/, DataSink &sink) {
  4918. sink.os << "PUT";
  4919. sink.done();
  4920. return true;
  4921. },
  4922. "text/plain");
  4923. ASSERT_TRUE(res);
  4924. EXPECT_EQ(StatusCode::OK_200, res->status);
  4925. EXPECT_EQ("PUT", res->body);
  4926. }
  4927. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4928. cli_.set_compress(true);
  4929. auto res = cli_.Post(
  4930. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4931. "text/plain");
  4932. ASSERT_TRUE(!res);
  4933. EXPECT_EQ(Error::Canceled, res.error());
  4934. }
  4935. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4936. cli_.set_compress(true);
  4937. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4938. ASSERT_TRUE(res);
  4939. EXPECT_EQ(StatusCode::OK_200, res->status);
  4940. EXPECT_EQ(LARGE_DATA, res->body);
  4941. }
  4942. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4943. #ifdef CPPHTTPLIB_SSL_ENABLED
  4944. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4945. Client cli(s.c_str());
  4946. cli.enable_server_certificate_verification(false);
  4947. #else
  4948. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4949. Client cli(s.c_str());
  4950. #endif
  4951. cli.set_compress(true);
  4952. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4953. ASSERT_TRUE(res);
  4954. EXPECT_EQ(StatusCode::OK_200, res->status);
  4955. EXPECT_EQ(LARGE_DATA, res->body);
  4956. // The compressed size should be less than a 10th of the original. May vary
  4957. // depending on the zlib library.
  4958. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4959. static_cast<uint64_t>(10 * 1024 * 1024));
  4960. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4961. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4962. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4963. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4964. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4965. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4966. #endif
  4967. }
  4968. TEST_F(ServerTest, PutContentWithDeflate) {
  4969. cli_.set_compress(false);
  4970. Headers headers;
  4971. headers.emplace("Content-Encoding", "deflate");
  4972. // PUT in deflate format:
  4973. auto res = cli_.Put("/put", headers,
  4974. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4975. ASSERT_TRUE(res);
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. EXPECT_EQ("PUT", res->body);
  4978. }
  4979. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4980. Headers headers;
  4981. headers.emplace("Accept-Encoding", "gzip, deflate");
  4982. auto res = cli_.Get("/streamed-chunked", headers);
  4983. ASSERT_TRUE(res);
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. EXPECT_EQ(std::string("123456789"), res->body);
  4986. }
  4987. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4988. Headers headers;
  4989. headers.emplace("Accept-Encoding", "gzip, deflate");
  4990. auto res = cli_.Get("/streamed-chunked2", headers);
  4991. ASSERT_TRUE(res);
  4992. EXPECT_EQ(StatusCode::OK_200, res->status);
  4993. EXPECT_EQ(std::string("123456789"), res->body);
  4994. }
  4995. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4996. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4997. ASSERT_TRUE(res);
  4998. EXPECT_EQ(StatusCode::OK_200, res->status);
  4999. }
  5000. TEST(GzipDecompressor, ChunkedDecompression) {
  5001. std::string data;
  5002. for (size_t i = 0; i < 32 * 1024; ++i) {
  5003. data.push_back(static_cast<char>('a' + i % 26));
  5004. }
  5005. std::string compressed_data;
  5006. {
  5007. httplib::detail::gzip_compressor compressor;
  5008. bool result = compressor.compress(
  5009. data.data(), data.size(),
  5010. /*last=*/true,
  5011. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5012. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5013. compressed_data_size);
  5014. return true;
  5015. });
  5016. ASSERT_TRUE(result);
  5017. }
  5018. std::string decompressed_data;
  5019. {
  5020. httplib::detail::gzip_decompressor decompressor;
  5021. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5022. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5023. size_t chunk_size = 130;
  5024. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5025. chunk_begin += chunk_size) {
  5026. size_t current_chunk_size =
  5027. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5028. bool result = decompressor.decompress(
  5029. compressed_data.data() + chunk_begin, current_chunk_size,
  5030. [&](const char *decompressed_data_chunk,
  5031. size_t decompressed_data_chunk_size) {
  5032. decompressed_data.insert(decompressed_data.size(),
  5033. decompressed_data_chunk,
  5034. decompressed_data_chunk_size);
  5035. return true;
  5036. });
  5037. ASSERT_TRUE(result);
  5038. }
  5039. }
  5040. ASSERT_EQ(data, decompressed_data);
  5041. }
  5042. TEST(GzipDecompressor, DeflateDecompression) {
  5043. std::string original_text = "Raw deflate without gzip";
  5044. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5045. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5046. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5047. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5048. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5049. std::string decompressed_data;
  5050. {
  5051. httplib::detail::gzip_decompressor decompressor;
  5052. bool result = decompressor.decompress(
  5053. compressed_data.data(), compressed_data.size(),
  5054. [&](const char *decompressed_data_chunk,
  5055. size_t decompressed_data_chunk_size) {
  5056. decompressed_data.insert(decompressed_data.size(),
  5057. decompressed_data_chunk,
  5058. decompressed_data_chunk_size);
  5059. return true;
  5060. });
  5061. ASSERT_TRUE(result);
  5062. }
  5063. ASSERT_EQ(original_text, decompressed_data);
  5064. }
  5065. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5066. std::string original_text = "Raw deflate without gzip";
  5067. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5068. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5069. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5070. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5071. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5072. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5073. std::string decompressed_data;
  5074. {
  5075. httplib::detail::gzip_decompressor decompressor;
  5076. bool result = decompressor.decompress(
  5077. compressed_data.data(), compressed_data.size(),
  5078. [&](const char *decompressed_data_chunk,
  5079. size_t decompressed_data_chunk_size) {
  5080. decompressed_data.insert(decompressed_data.size(),
  5081. decompressed_data_chunk,
  5082. decompressed_data_chunk_size);
  5083. return true;
  5084. });
  5085. ASSERT_TRUE(result);
  5086. }
  5087. ASSERT_EQ(original_text, decompressed_data);
  5088. }
  5089. #endif
  5090. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5091. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5092. Headers headers;
  5093. headers.emplace("Accept-Encoding", "br");
  5094. auto res = cli_.Get("/streamed-chunked", headers);
  5095. ASSERT_TRUE(res);
  5096. EXPECT_EQ(StatusCode::OK_200, res->status);
  5097. EXPECT_EQ(std::string("123456789"), res->body);
  5098. }
  5099. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5100. Headers headers;
  5101. headers.emplace("Accept-Encoding", "br");
  5102. auto res = cli_.Get("/streamed-chunked2", headers);
  5103. ASSERT_TRUE(res);
  5104. EXPECT_EQ(StatusCode::OK_200, res->status);
  5105. EXPECT_EQ(std::string("123456789"), res->body);
  5106. }
  5107. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5108. cli_.set_compress(true);
  5109. auto res = cli_.Put(
  5110. "/put", 3,
  5111. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5112. sink.os << "PUT";
  5113. return true;
  5114. },
  5115. "text/plain");
  5116. ASSERT_TRUE(res);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. EXPECT_EQ("PUT", res->body);
  5119. }
  5120. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5121. cli_.set_compress(true);
  5122. auto res = cli_.Put(
  5123. "/put",
  5124. [](size_t /*offset*/, DataSink &sink) {
  5125. sink.os << "PUT";
  5126. sink.done();
  5127. return true;
  5128. },
  5129. "text/plain");
  5130. ASSERT_TRUE(res);
  5131. EXPECT_EQ(StatusCode::OK_200, res->status);
  5132. EXPECT_EQ("PUT", res->body);
  5133. }
  5134. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5135. cli_.set_compress(true);
  5136. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5137. ASSERT_TRUE(res);
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ(LARGE_DATA, res->body);
  5140. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5141. }
  5142. #endif
  5143. TEST_F(ServerTest, Patch) {
  5144. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5145. ASSERT_TRUE(res);
  5146. EXPECT_EQ(StatusCode::OK_200, res->status);
  5147. EXPECT_EQ("PATCH", res->body);
  5148. }
  5149. TEST_F(ServerTest, Delete) {
  5150. auto res = cli_.Delete("/delete");
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("DELETE", res->body);
  5154. }
  5155. TEST_F(ServerTest, DeleteContentReceiver) {
  5156. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5157. ASSERT_TRUE(res);
  5158. EXPECT_EQ(StatusCode::OK_200, res->status);
  5159. EXPECT_EQ("content", res->body);
  5160. }
  5161. TEST_F(ServerTest, Options) {
  5162. auto res = cli_.Options("*");
  5163. ASSERT_TRUE(res);
  5164. EXPECT_EQ(StatusCode::OK_200, res->status);
  5165. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5166. EXPECT_TRUE(res->body.empty());
  5167. }
  5168. TEST_F(ServerTest, URL) {
  5169. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5170. ASSERT_TRUE(res);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. }
  5173. TEST_F(ServerTest, ArrayParam) {
  5174. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5175. ASSERT_TRUE(res);
  5176. EXPECT_EQ(StatusCode::OK_200, res->status);
  5177. }
  5178. TEST_F(ServerTest, ArrayParamValues) {
  5179. auto res =
  5180. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5181. ASSERT_TRUE(res);
  5182. EXPECT_EQ(StatusCode::OK_200, res->status);
  5183. }
  5184. TEST_F(ServerTest, NoMultipleHeaders) {
  5185. Headers headers = {{"Content-Length", "5"}};
  5186. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5187. "text/plain");
  5188. ASSERT_TRUE(res);
  5189. EXPECT_EQ(StatusCode::OK_200, res->status);
  5190. }
  5191. TEST_F(ServerTest, PostContentReceiver) {
  5192. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5193. ASSERT_TRUE(res);
  5194. ASSERT_EQ(StatusCode::OK_200, res->status);
  5195. ASSERT_EQ("content", res->body);
  5196. }
  5197. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5198. UploadFormDataItems items = {
  5199. {"text1", "text default", "", ""},
  5200. {"text2", "aωb", "", ""},
  5201. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5202. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5203. {"file3", "", "", "application/octet-stream"},
  5204. };
  5205. auto res = cli_.Post("/content_receiver", items);
  5206. ASSERT_TRUE(res);
  5207. EXPECT_EQ(StatusCode::OK_200, res->status);
  5208. }
  5209. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5210. UploadFormDataItems items = {
  5211. {"text1", "text default", "", ""},
  5212. {"text2", "aωb", "", ""},
  5213. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5214. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5215. {"file3", "", "", "application/octet-stream"},
  5216. };
  5217. auto boundary = std::string("+++++");
  5218. std::string body;
  5219. for (const auto &item : items) {
  5220. body += "--" + boundary + "\r\n";
  5221. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5222. if (!item.filename.empty()) {
  5223. body += "; filename=\"" + item.filename + "\"";
  5224. }
  5225. body += "\r\n";
  5226. if (!item.content_type.empty()) {
  5227. body += "Content-Type: " + item.content_type + "\r\n";
  5228. }
  5229. body += "\r\n";
  5230. body += item.content + "\r\n";
  5231. }
  5232. body += "--" + boundary + "--\r\n";
  5233. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5234. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5235. ASSERT_TRUE(res);
  5236. EXPECT_EQ(StatusCode::OK_200, res->status);
  5237. }
  5238. TEST_F(ServerTest, PostContentReceiverGzip) {
  5239. cli_.set_compress(true);
  5240. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5241. ASSERT_TRUE(res);
  5242. ASSERT_EQ(StatusCode::OK_200, res->status);
  5243. ASSERT_EQ("content", res->body);
  5244. }
  5245. TEST_F(ServerTest, PutContentReceiver) {
  5246. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5247. ASSERT_TRUE(res);
  5248. ASSERT_EQ(StatusCode::OK_200, res->status);
  5249. ASSERT_EQ("content", res->body);
  5250. }
  5251. TEST_F(ServerTest, PatchContentReceiver) {
  5252. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5253. ASSERT_TRUE(res);
  5254. ASSERT_EQ(StatusCode::OK_200, res->status);
  5255. ASSERT_EQ("content", res->body);
  5256. }
  5257. template <typename ClientType>
  5258. void TestWithHeadersAndContentReceiver(
  5259. ClientType &cli,
  5260. std::function<Result(ClientType &, const std::string &, const Headers &,
  5261. const std::string &, const std::string &,
  5262. ContentReceiver, DownloadProgress)>
  5263. request_func) {
  5264. Headers headers;
  5265. headers.emplace("X-Custom-Header", "test-value");
  5266. std::string received_body;
  5267. auto res = request_func(
  5268. cli, "/content_receiver", headers, "content", "application/json",
  5269. [&](const char *data, size_t data_length) {
  5270. received_body.append(data, data_length);
  5271. return true;
  5272. },
  5273. nullptr);
  5274. ASSERT_TRUE(res);
  5275. EXPECT_EQ(StatusCode::OK_200, res->status);
  5276. EXPECT_EQ("content", received_body);
  5277. }
  5278. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5279. #ifdef CPPHTTPLIB_SSL_ENABLED
  5280. using ClientT = SSLClient;
  5281. #else
  5282. using ClientT = Client;
  5283. #endif
  5284. TestWithHeadersAndContentReceiver<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, DownloadProgress progress) {
  5288. return cli.Post(path, headers, body, content_type, receiver, progress);
  5289. });
  5290. }
  5291. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5292. #ifdef CPPHTTPLIB_SSL_ENABLED
  5293. using ClientT = SSLClient;
  5294. #else
  5295. using ClientT = Client;
  5296. #endif
  5297. TestWithHeadersAndContentReceiver<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, DownloadProgress progress) {
  5301. return cli.Put(path, headers, body, content_type, receiver, progress);
  5302. });
  5303. }
  5304. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5305. #ifdef CPPHTTPLIB_SSL_ENABLED
  5306. using ClientT = SSLClient;
  5307. #else
  5308. using ClientT = Client;
  5309. #endif
  5310. TestWithHeadersAndContentReceiver<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, DownloadProgress progress) {
  5314. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5315. });
  5316. }
  5317. template <typename ClientType>
  5318. void TestWithHeadersAndContentReceiverWithProgress(
  5319. ClientType &cli,
  5320. std::function<Result(ClientType &, const std::string &, const Headers &,
  5321. const std::string &, const std::string &,
  5322. ContentReceiver, DownloadProgress)>
  5323. request_func) {
  5324. Headers headers;
  5325. headers.emplace("X-Test-Header", "progress-test");
  5326. std::string received_body;
  5327. auto progress_called = false;
  5328. auto res = request_func(
  5329. cli, "/content_receiver", headers, "content", "text/plain",
  5330. [&](const char *data, size_t data_length) {
  5331. received_body.append(data, data_length);
  5332. return true;
  5333. },
  5334. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5335. progress_called = true;
  5336. return true;
  5337. });
  5338. ASSERT_TRUE(res);
  5339. EXPECT_EQ(StatusCode::OK_200, res->status);
  5340. EXPECT_EQ("content", received_body);
  5341. EXPECT_TRUE(progress_called);
  5342. }
  5343. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5344. #ifdef CPPHTTPLIB_SSL_ENABLED
  5345. using ClientT = SSLClient;
  5346. #else
  5347. using ClientT = Client;
  5348. #endif
  5349. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5350. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5351. const std::string &body, const std::string &content_type,
  5352. ContentReceiver receiver, DownloadProgress progress) {
  5353. return cli.Post(path, headers, body, content_type, receiver, progress);
  5354. });
  5355. }
  5356. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5357. #ifdef CPPHTTPLIB_SSL_ENABLED
  5358. using ClientT = SSLClient;
  5359. #else
  5360. using ClientT = Client;
  5361. #endif
  5362. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5363. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5364. const std::string &body, const std::string &content_type,
  5365. ContentReceiver receiver, DownloadProgress progress) {
  5366. return cli.Put(path, headers, body, content_type, receiver, progress);
  5367. });
  5368. }
  5369. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5370. #ifdef CPPHTTPLIB_SSL_ENABLED
  5371. using ClientT = SSLClient;
  5372. #else
  5373. using ClientT = Client;
  5374. #endif
  5375. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5376. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5377. const std::string &body, const std::string &content_type,
  5378. ContentReceiver receiver, DownloadProgress progress) {
  5379. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5380. });
  5381. }
  5382. template <typename ClientType>
  5383. void TestWithHeadersAndContentReceiverError(
  5384. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5385. const Headers &, const std::string &,
  5386. const std::string &, ContentReceiver)>
  5387. request_func) {
  5388. Headers headers;
  5389. headers.emplace("X-Error-Test", "true");
  5390. std::string received_body;
  5391. auto receiver_failed = false;
  5392. auto res =
  5393. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5394. [&](const char *data, size_t data_length) {
  5395. received_body.append(data, data_length);
  5396. receiver_failed = true;
  5397. return false;
  5398. });
  5399. ASSERT_FALSE(res);
  5400. EXPECT_TRUE(receiver_failed);
  5401. }
  5402. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5403. #ifdef CPPHTTPLIB_SSL_ENABLED
  5404. using ClientT = SSLClient;
  5405. #else
  5406. using ClientT = Client;
  5407. #endif
  5408. TestWithHeadersAndContentReceiverError<ClientT>(
  5409. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5410. const std::string &body, const std::string &content_type,
  5411. ContentReceiver receiver) {
  5412. return cli.Post(path, headers, body, content_type, receiver);
  5413. });
  5414. }
  5415. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5416. #ifdef CPPHTTPLIB_SSL_ENABLED
  5417. using ClientT = SSLClient;
  5418. #else
  5419. using ClientT = Client;
  5420. #endif
  5421. TestWithHeadersAndContentReceiverError<ClientT>(
  5422. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5423. const std::string &body, const std::string &content_type,
  5424. ContentReceiver receiver) {
  5425. return cli.Put(path, headers, body, content_type, receiver);
  5426. });
  5427. }
  5428. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5429. #ifdef CPPHTTPLIB_SSL_ENABLED
  5430. using ClientT = SSLClient;
  5431. #else
  5432. using ClientT = Client;
  5433. #endif
  5434. TestWithHeadersAndContentReceiverError<ClientT>(
  5435. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5436. const std::string &body, const std::string &content_type,
  5437. ContentReceiver receiver) {
  5438. return cli.Patch(path, headers, body, content_type, receiver);
  5439. });
  5440. }
  5441. TEST_F(ServerTest, PostQueryStringAndBody) {
  5442. auto res =
  5443. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5444. ASSERT_TRUE(res);
  5445. ASSERT_EQ(StatusCode::OK_200, res->status);
  5446. }
  5447. TEST_F(ServerTest, HTTP2Magic) {
  5448. Request req;
  5449. req.method = "PRI";
  5450. req.path = "*";
  5451. req.body = "SM";
  5452. auto res = std::make_shared<Response>();
  5453. auto error = Error::Success;
  5454. auto ret = cli_.send(req, *res, error);
  5455. ASSERT_TRUE(ret);
  5456. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5457. }
  5458. TEST_F(ServerTest, KeepAlive) {
  5459. auto res = cli_.Get("/hi");
  5460. ASSERT_TRUE(res);
  5461. EXPECT_EQ(StatusCode::OK_200, res->status);
  5462. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5463. EXPECT_EQ("Hello World!", res->body);
  5464. res = cli_.Get("/hi");
  5465. ASSERT_TRUE(res);
  5466. EXPECT_EQ(StatusCode::OK_200, res->status);
  5467. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5468. EXPECT_EQ("Hello World!", res->body);
  5469. res = cli_.Get("/hi");
  5470. ASSERT_TRUE(res);
  5471. EXPECT_EQ(StatusCode::OK_200, res->status);
  5472. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5473. EXPECT_EQ("Hello World!", res->body);
  5474. res = cli_.Get("/not-exist");
  5475. ASSERT_TRUE(res);
  5476. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5477. res = cli_.Post("/empty", "", "text/plain");
  5478. ASSERT_TRUE(res);
  5479. EXPECT_EQ(StatusCode::OK_200, res->status);
  5480. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5481. EXPECT_EQ("empty", res->body);
  5482. EXPECT_EQ("close", res->get_header_value("Connection"));
  5483. res = cli_.Post(
  5484. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5485. "text/plain");
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5489. EXPECT_EQ("empty", res->body);
  5490. cli_.set_keep_alive(false);
  5491. res = cli_.Get("/last-request");
  5492. ASSERT_TRUE(res);
  5493. EXPECT_EQ(StatusCode::OK_200, res->status);
  5494. EXPECT_EQ("close", res->get_header_value("Connection"));
  5495. }
  5496. TEST_F(ServerTest, TooManyRedirect) {
  5497. cli_.set_follow_location(true);
  5498. auto res = cli_.Get("/redirect/0");
  5499. ASSERT_TRUE(!res);
  5500. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5501. }
  5502. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5503. Request req;
  5504. req.method = "FOOBAR";
  5505. req.path = "/hi";
  5506. cli_.set_keep_alive(true);
  5507. auto res = cli_.send(req);
  5508. ASSERT_TRUE(res);
  5509. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5510. EXPECT_EQ("close", res->get_header_value("Connection"));
  5511. EXPECT_FALSE(cli_.is_socket_open());
  5512. }
  5513. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5514. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5515. TEST_F(ServerTest, Gzip) {
  5516. Headers headers;
  5517. headers.emplace("Accept-Encoding", "gzip, deflate");
  5518. auto res = cli_.Get("/compress", headers);
  5519. ASSERT_TRUE(res);
  5520. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5521. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5522. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5523. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5524. "7890123456789012345678901234567890",
  5525. res->body);
  5526. EXPECT_EQ(StatusCode::OK_200, res->status);
  5527. }
  5528. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5529. Headers headers;
  5530. headers.emplace("Accept-Encoding", "gzip, deflate");
  5531. auto res = cli_.Get("/compress-with-charset", headers);
  5532. ASSERT_TRUE(res);
  5533. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5534. EXPECT_EQ("application/json; charset=utf-8",
  5535. res->get_header_value("Content-Type"));
  5536. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5537. "7890123456789012345678901234567890",
  5538. res->body);
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. }
  5541. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5542. Headers headers;
  5543. headers.emplace("Accept-Encoding", "");
  5544. auto res = cli_.Get("/compress", headers);
  5545. ASSERT_TRUE(res);
  5546. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5547. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5548. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5549. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5550. "7890123456789012345678901234567890",
  5551. res->body);
  5552. EXPECT_EQ(StatusCode::OK_200, res->status);
  5553. }
  5554. TEST_F(ServerTest, GzipWithContentReceiver) {
  5555. Headers headers;
  5556. headers.emplace("Accept-Encoding", "gzip, deflate");
  5557. std::string body;
  5558. auto res = cli_.Get("/compress", headers,
  5559. [&](const char *data, uint64_t data_length) {
  5560. EXPECT_EQ(100U, data_length);
  5561. body.append(data, data_length);
  5562. return true;
  5563. });
  5564. ASSERT_TRUE(res);
  5565. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5567. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5568. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5569. "7890123456789012345678901234567890",
  5570. body);
  5571. EXPECT_EQ(StatusCode::OK_200, res->status);
  5572. }
  5573. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5574. Headers headers;
  5575. headers.emplace("Accept-Encoding", "gzip, deflate");
  5576. cli_.set_decompress(false);
  5577. auto res = cli_.Get("/compress", headers);
  5578. ASSERT_TRUE(res);
  5579. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5580. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5581. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5582. EXPECT_EQ(33U, res->body.size());
  5583. EXPECT_EQ(StatusCode::OK_200, res->status);
  5584. }
  5585. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5586. Headers headers;
  5587. headers.emplace("Accept-Encoding", "");
  5588. std::string body;
  5589. auto res = cli_.Get("/compress", headers,
  5590. [&](const char *data, uint64_t data_length) {
  5591. EXPECT_EQ(100U, data_length);
  5592. body.append(data, data_length);
  5593. return true;
  5594. });
  5595. ASSERT_TRUE(res);
  5596. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5597. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5598. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5599. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5600. "7890123456789012345678901234567890",
  5601. body);
  5602. EXPECT_EQ(StatusCode::OK_200, res->status);
  5603. }
  5604. TEST_F(ServerTest, NoGzip) {
  5605. Headers headers;
  5606. headers.emplace("Accept-Encoding", "gzip, deflate");
  5607. auto res = cli_.Get("/nocompress", headers);
  5608. ASSERT_TRUE(res);
  5609. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5610. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5611. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5612. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5613. "7890123456789012345678901234567890",
  5614. res->body);
  5615. EXPECT_EQ(StatusCode::OK_200, res->status);
  5616. }
  5617. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5618. Headers headers;
  5619. headers.emplace("Accept-Encoding", "gzip, deflate");
  5620. std::string body;
  5621. auto res = cli_.Get("/nocompress", headers,
  5622. [&](const char *data, uint64_t data_length) {
  5623. EXPECT_EQ(100U, data_length);
  5624. body.append(data, data_length);
  5625. return true;
  5626. });
  5627. ASSERT_TRUE(res);
  5628. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5629. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5630. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5631. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5632. "7890123456789012345678901234567890",
  5633. body);
  5634. EXPECT_EQ(StatusCode::OK_200, res->status);
  5635. }
  5636. TEST_F(ServerTest, MultipartFormDataGzip) {
  5637. UploadFormDataItems items = {
  5638. {"key1", "test", "", ""},
  5639. {"key2", "--abcdefg123", "", ""},
  5640. };
  5641. cli_.set_compress(true);
  5642. auto res = cli_.Post("/compress-multipart", items);
  5643. ASSERT_TRUE(res);
  5644. EXPECT_EQ(StatusCode::OK_200, res->status);
  5645. }
  5646. #endif
  5647. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5648. TEST_F(ServerTest, Brotli) {
  5649. Headers headers;
  5650. headers.emplace("Accept-Encoding", "br");
  5651. auto res = cli_.Get("/compress", headers);
  5652. ASSERT_TRUE(res);
  5653. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5655. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5656. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5657. "7890123456789012345678901234567890",
  5658. res->body);
  5659. EXPECT_EQ(StatusCode::OK_200, res->status);
  5660. }
  5661. #endif
  5662. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5663. TEST_F(ServerTest, Zstd) {
  5664. Headers headers;
  5665. headers.emplace("Accept-Encoding", "zstd");
  5666. auto res = cli_.Get("/compress", headers);
  5667. ASSERT_TRUE(res);
  5668. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5669. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5670. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5671. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5672. "7890123456789012345678901234567890",
  5673. res->body);
  5674. EXPECT_EQ(StatusCode::OK_200, res->status);
  5675. }
  5676. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5677. Headers headers;
  5678. headers.emplace("Accept-Encoding", "");
  5679. auto res = cli_.Get("/compress", headers);
  5680. ASSERT_TRUE(res);
  5681. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5682. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5683. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5684. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5685. "7890123456789012345678901234567890",
  5686. res->body);
  5687. EXPECT_EQ(StatusCode::OK_200, res->status);
  5688. }
  5689. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5690. Headers headers;
  5691. headers.emplace("Accept-Encoding", "zstd");
  5692. std::string body;
  5693. auto res = cli_.Get("/compress", headers,
  5694. [&](const char *data, uint64_t data_length) {
  5695. EXPECT_EQ(100U, data_length);
  5696. body.append(data, data_length);
  5697. return true;
  5698. });
  5699. ASSERT_TRUE(res);
  5700. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5701. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5702. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5703. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5704. "7890123456789012345678901234567890",
  5705. body);
  5706. EXPECT_EQ(StatusCode::OK_200, res->status);
  5707. }
  5708. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5709. Headers headers;
  5710. headers.emplace("Accept-Encoding", "zstd");
  5711. cli_.set_decompress(false);
  5712. auto res = cli_.Get("/compress", headers);
  5713. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5714. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5715. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5716. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5717. ASSERT_TRUE(res);
  5718. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5719. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5720. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5721. EXPECT_EQ(StatusCode::OK_200, res->status);
  5722. ASSERT_EQ(26U, res->body.size());
  5723. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5724. 0);
  5725. }
  5726. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5727. Headers headers;
  5728. headers.emplace("Accept-Encoding", "");
  5729. std::string body;
  5730. auto res = cli_.Get("/compress", headers,
  5731. [&](const char *data, uint64_t data_length) {
  5732. EXPECT_EQ(100U, data_length);
  5733. body.append(data, data_length);
  5734. return true;
  5735. });
  5736. ASSERT_TRUE(res);
  5737. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5738. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5739. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5740. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5741. "7890123456789012345678901234567890",
  5742. body);
  5743. EXPECT_EQ(StatusCode::OK_200, res->status);
  5744. }
  5745. TEST_F(ServerTest, NoZstd) {
  5746. Headers headers;
  5747. headers.emplace("Accept-Encoding", "zstd");
  5748. auto res = cli_.Get("/nocompress", headers);
  5749. ASSERT_TRUE(res);
  5750. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5751. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5752. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5753. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5754. "7890123456789012345678901234567890",
  5755. res->body);
  5756. EXPECT_EQ(StatusCode::OK_200, res->status);
  5757. }
  5758. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5759. Headers headers;
  5760. headers.emplace("Accept-Encoding", "zstd");
  5761. std::string body;
  5762. auto res = cli_.Get("/nocompress", headers,
  5763. [&](const char *data, uint64_t data_length) {
  5764. EXPECT_EQ(100U, data_length);
  5765. body.append(data, data_length);
  5766. return true;
  5767. });
  5768. ASSERT_TRUE(res);
  5769. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5770. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5771. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5772. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5773. "7890123456789012345678901234567890",
  5774. body);
  5775. EXPECT_EQ(StatusCode::OK_200, res->status);
  5776. }
  5777. // TODO: How to enable zstd ??
  5778. TEST_F(ServerTest, MultipartFormDataZstd) {
  5779. UploadFormDataItems items = {
  5780. {"key1", "test", "", ""},
  5781. {"key2", "--abcdefg123", "", ""},
  5782. };
  5783. Headers headers;
  5784. headers.emplace("Accept-Encoding", "zstd");
  5785. cli_.set_compress(true);
  5786. auto res = cli_.Post("/compress-multipart", headers, items);
  5787. ASSERT_TRUE(res);
  5788. EXPECT_EQ(StatusCode::OK_200, res->status);
  5789. }
  5790. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5791. Headers headers;
  5792. headers.emplace("Accept-Encoding", "zstd");
  5793. cli_.set_compress(true);
  5794. auto res = cli_.Put(
  5795. "/put", headers, 3,
  5796. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5797. sink.os << "PUT";
  5798. return true;
  5799. },
  5800. "text/plain");
  5801. ASSERT_TRUE(res);
  5802. EXPECT_EQ(StatusCode::OK_200, res->status);
  5803. EXPECT_EQ("PUT", res->body);
  5804. }
  5805. // Pre-compression logging tests
  5806. TEST_F(ServerTest, PreCompressionLogging) {
  5807. // Test data for compression (matches the actual /compress endpoint content)
  5808. const std::string test_content =
  5809. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5810. "3456789012345678901234567890";
  5811. // Variables to capture logging data
  5812. std::string pre_compression_body;
  5813. std::string pre_compression_content_type;
  5814. std::string pre_compression_content_encoding;
  5815. std::string post_compression_body;
  5816. std::string post_compression_content_type;
  5817. std::string post_compression_content_encoding;
  5818. // Set up pre-compression logger
  5819. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5820. const Response &res) {
  5821. pre_compression_body = res.body;
  5822. pre_compression_content_type = res.get_header_value("Content-Type");
  5823. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5824. });
  5825. // Set up post-compression logger
  5826. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5827. post_compression_body = res.body;
  5828. post_compression_content_type = res.get_header_value("Content-Type");
  5829. post_compression_content_encoding =
  5830. res.get_header_value("Content-Encoding");
  5831. });
  5832. // Test with gzip compression
  5833. Headers headers;
  5834. headers.emplace("Accept-Encoding", "gzip");
  5835. auto res = cli_.Get("/compress", headers);
  5836. // Verify response was compressed
  5837. ASSERT_TRUE(res);
  5838. EXPECT_EQ(StatusCode::OK_200, res->status);
  5839. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5840. // Verify pre-compression logger captured uncompressed content
  5841. EXPECT_EQ(test_content, pre_compression_body);
  5842. EXPECT_EQ("text/plain", pre_compression_content_type);
  5843. EXPECT_TRUE(pre_compression_content_encoding
  5844. .empty()); // No encoding header before compression
  5845. // Verify post-compression logger captured compressed content
  5846. EXPECT_NE(test_content,
  5847. post_compression_body); // Should be different after compression
  5848. EXPECT_EQ("text/plain", post_compression_content_type);
  5849. EXPECT_EQ("gzip", post_compression_content_encoding);
  5850. // Verify compressed content is smaller
  5851. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5852. }
  5853. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5854. const std::string test_content =
  5855. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5856. "3456789012345678901234567890";
  5857. std::string pre_compression_body;
  5858. std::string post_compression_body;
  5859. svr_.set_pre_compression_logger(
  5860. [&](const Request & /*req*/, const Response &res) {
  5861. pre_compression_body = res.body;
  5862. });
  5863. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5864. post_compression_body = res.body;
  5865. });
  5866. Headers headers;
  5867. headers.emplace("Accept-Encoding", "br");
  5868. auto res = cli_.Get("/compress", headers);
  5869. ASSERT_TRUE(res);
  5870. EXPECT_EQ(StatusCode::OK_200, res->status);
  5871. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5872. // Verify pre-compression content is uncompressed
  5873. EXPECT_EQ(test_content, pre_compression_body);
  5874. // Verify post-compression content is compressed
  5875. EXPECT_NE(test_content, post_compression_body);
  5876. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5877. }
  5878. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5879. const std::string test_content =
  5880. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5881. "3456789012345678901234567890";
  5882. std::string pre_compression_body;
  5883. std::string post_compression_body;
  5884. svr_.set_pre_compression_logger(
  5885. [&](const Request & /*req*/, const Response &res) {
  5886. pre_compression_body = res.body;
  5887. });
  5888. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5889. post_compression_body = res.body;
  5890. });
  5891. // Request without compression (use /nocompress endpoint)
  5892. Headers headers;
  5893. auto res = cli_.Get("/nocompress", headers);
  5894. ASSERT_TRUE(res);
  5895. EXPECT_EQ(StatusCode::OK_200, res->status);
  5896. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5897. // Pre-compression logger should not be called when no compression is applied
  5898. EXPECT_TRUE(
  5899. pre_compression_body.empty()); // Pre-compression logger not called
  5900. EXPECT_EQ(
  5901. test_content,
  5902. post_compression_body); // Post-compression logger captures final content
  5903. }
  5904. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5905. const std::string test_content =
  5906. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5907. "3456789012345678901234567890";
  5908. std::string pre_compression_body;
  5909. bool pre_logger_called = false;
  5910. // Set only pre-compression logger
  5911. svr_.set_pre_compression_logger(
  5912. [&](const Request & /*req*/, const Response &res) {
  5913. pre_compression_body = res.body;
  5914. pre_logger_called = true;
  5915. });
  5916. Headers headers;
  5917. headers.emplace("Accept-Encoding", "gzip");
  5918. auto res = cli_.Get("/compress", headers);
  5919. ASSERT_TRUE(res);
  5920. EXPECT_EQ(StatusCode::OK_200, res->status);
  5921. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5922. // Verify pre-compression logger was called
  5923. EXPECT_TRUE(pre_logger_called);
  5924. EXPECT_EQ(test_content, pre_compression_body);
  5925. }
  5926. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5927. {
  5928. // Test with Expect: 100-continue header - success case
  5929. // Server returns 100 Continue, client sends body, server returns 200 OK
  5930. Request req;
  5931. req.method = "POST";
  5932. req.path = "/post-large";
  5933. req.set_header("Expect", "100-continue");
  5934. req.body = LARGE_DATA;
  5935. Response res;
  5936. auto error = Error::Success;
  5937. cli_.set_keep_alive(true);
  5938. auto ret = cli_.send(req, res, error);
  5939. EXPECT_TRUE(ret);
  5940. EXPECT_EQ(StatusCode::OK_200, res.status);
  5941. EXPECT_EQ(LARGE_DATA, res.body);
  5942. }
  5943. {
  5944. // Test with Expect: 100-continue header - error case
  5945. // Client should not send the body when server returns an error
  5946. Request req;
  5947. req.method = "POST";
  5948. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5949. req.set_header("Expect", "100-continue");
  5950. req.body = LARGE_DATA;
  5951. Response res;
  5952. auto error = Error::Success;
  5953. auto start = std::chrono::high_resolution_clock::now();
  5954. cli_.set_keep_alive(true);
  5955. auto ret = cli_.send(req, res, error);
  5956. auto end = std::chrono::high_resolution_clock::now();
  5957. auto elapsed =
  5958. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5959. .count();
  5960. // With Expect: 100-continue, request completes successfully but with error
  5961. EXPECT_TRUE(ret);
  5962. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5963. EXPECT_EQ("close", res.get_header_value("Connection"));
  5964. EXPECT_FALSE(cli_.is_socket_open());
  5965. EXPECT_LE(elapsed, 2000);
  5966. }
  5967. {
  5968. // Send an extra GET request to ensure error recovery without hanging
  5969. Request req;
  5970. req.method = "GET";
  5971. req.path = "/hi";
  5972. auto start = std::chrono::high_resolution_clock::now();
  5973. auto res = cli_.send(req);
  5974. auto end = std::chrono::high_resolution_clock::now();
  5975. auto elapsed =
  5976. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5977. .count();
  5978. ASSERT_TRUE(res);
  5979. EXPECT_EQ(StatusCode::OK_200, res->status);
  5980. EXPECT_EQ("Hello World!", res->body);
  5981. EXPECT_LE(elapsed, 500);
  5982. }
  5983. }
  5984. TEST(ZstdDecompressor, ChunkedDecompression) {
  5985. std::string data;
  5986. for (size_t i = 0; i < 32 * 1024; ++i) {
  5987. data.push_back(static_cast<char>('a' + i % 26));
  5988. }
  5989. std::string compressed_data;
  5990. {
  5991. httplib::detail::zstd_compressor compressor;
  5992. bool result = compressor.compress(
  5993. data.data(), data.size(),
  5994. /*last=*/true,
  5995. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5996. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5997. compressed_data_size);
  5998. return true;
  5999. });
  6000. ASSERT_TRUE(result);
  6001. }
  6002. std::string decompressed_data;
  6003. {
  6004. httplib::detail::zstd_decompressor decompressor;
  6005. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6006. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6007. size_t chunk_size = 130;
  6008. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6009. chunk_begin += chunk_size) {
  6010. size_t current_chunk_size =
  6011. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6012. bool result = decompressor.decompress(
  6013. compressed_data.data() + chunk_begin, current_chunk_size,
  6014. [&](const char *decompressed_data_chunk,
  6015. size_t decompressed_data_chunk_size) {
  6016. decompressed_data.insert(decompressed_data.size(),
  6017. decompressed_data_chunk,
  6018. decompressed_data_chunk_size);
  6019. return true;
  6020. });
  6021. ASSERT_TRUE(result);
  6022. }
  6023. }
  6024. ASSERT_EQ(data, decompressed_data);
  6025. }
  6026. TEST(ZstdDecompressor, Decompress) {
  6027. std::string original_text = "Compressed with ZSTD";
  6028. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6029. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6030. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6031. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6032. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6033. std::string decompressed_data;
  6034. {
  6035. httplib::detail::zstd_decompressor decompressor;
  6036. bool result = decompressor.decompress(
  6037. compressed_data.data(), compressed_data.size(),
  6038. [&](const char *decompressed_data_chunk,
  6039. size_t decompressed_data_chunk_size) {
  6040. decompressed_data.insert(decompressed_data.size(),
  6041. decompressed_data_chunk,
  6042. decompressed_data_chunk_size);
  6043. return true;
  6044. });
  6045. ASSERT_TRUE(result);
  6046. }
  6047. ASSERT_EQ(original_text, decompressed_data);
  6048. }
  6049. #endif
  6050. // Sends a raw request to a server listening at HOST:PORT.
  6051. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6052. std::string *resp = nullptr) {
  6053. auto error = Error::Success;
  6054. auto client_sock = detail::create_client_socket(
  6055. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6056. /*connection_timeout_sec=*/5, 0,
  6057. /*read_timeout_sec=*/5, 0,
  6058. /*write_timeout_sec=*/5, 0, std::string(), error);
  6059. if (client_sock == INVALID_SOCKET) { return false; }
  6060. auto ret = detail::process_client_socket(
  6061. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6062. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6063. if (req.size() !=
  6064. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6065. return false;
  6066. }
  6067. char buf[512];
  6068. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6069. while (line_reader.getline()) {
  6070. if (resp) { *resp += line_reader.ptr(); }
  6071. }
  6072. return true;
  6073. });
  6074. detail::close_socket(client_sock);
  6075. return ret;
  6076. }
  6077. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6078. Server svr;
  6079. std::string header_value;
  6080. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6081. header_value = req.get_header_value("foo");
  6082. res.set_content("ok", "text/plain");
  6083. });
  6084. thread t = thread([&] { svr.listen(HOST, PORT); });
  6085. auto se = detail::scope_exit([&] {
  6086. svr.stop();
  6087. t.join();
  6088. ASSERT_FALSE(svr.is_running());
  6089. });
  6090. svr.wait_until_ready();
  6091. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6092. // like characters are not treated the same - use vertical tab and escape.
  6093. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6094. "foo: \t \v bar \x1B\t \r\n"
  6095. "Connection: close\r\n"
  6096. "\r\n";
  6097. std::string res;
  6098. ASSERT_TRUE(send_request(5, req, &res));
  6099. EXPECT_EQ(header_value, "");
  6100. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6101. }
  6102. // Sends a raw request and verifies that there isn't a crash or exception.
  6103. static void test_raw_request(const std::string &req,
  6104. std::string *out = nullptr) {
  6105. Server svr;
  6106. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6107. res.set_content("ok", "text/plain");
  6108. });
  6109. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6110. res.set_content("ok", "text/plain");
  6111. });
  6112. svr.Get("/header_field_value_check",
  6113. [&](const Request & /*req*/, Response &res) {
  6114. res.set_content("ok", "text/plain");
  6115. });
  6116. // Server read timeout must be longer than the client read timeout for the
  6117. // bug to reproduce, probably to force the server to process a request
  6118. // without a trailing blank line.
  6119. const time_t client_read_timeout_sec = 1;
  6120. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6121. bool listen_thread_ok = false;
  6122. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6123. auto se = detail::scope_exit([&] {
  6124. svr.stop();
  6125. t.join();
  6126. ASSERT_FALSE(svr.is_running());
  6127. EXPECT_TRUE(listen_thread_ok);
  6128. });
  6129. svr.wait_until_ready();
  6130. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6131. }
  6132. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6133. // A certain header line causes an exception if the header property is parsed
  6134. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6135. test_raw_request(
  6136. "GET /hi HTTP/1.1\r\n"
  6137. " : "
  6138. " "
  6139. " ");
  6140. }
  6141. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6142. // A certain header line causes an exception if the header property *name* is
  6143. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6144. // greedy matcher and requires backtracking when there are a lot of ":"
  6145. // characters.
  6146. // This occurs with libc++ but not libstdc++.
  6147. test_raw_request(
  6148. "GET /hi HTTP/1.1\r\n"
  6149. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6150. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6151. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6152. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6153. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6154. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6155. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6156. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6157. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6158. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6159. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6160. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6161. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6162. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6163. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6164. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6165. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6166. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6167. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6168. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6169. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6170. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6171. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6172. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6173. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6174. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6175. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6176. "&&&%%%");
  6177. }
  6178. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6179. // Make sure this doesn't crash the server.
  6180. // In a previous version of the header line regex, the "\r" rendered the line
  6181. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6182. // a new position where the leading white space ended and the field value
  6183. // began.
  6184. // The crash occurs with libc++ but not libstdc++.
  6185. test_raw_request("GET /hi HTTP/1.1\r\n"
  6186. "a:" +
  6187. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6188. "\r\n"
  6189. "\r\n");
  6190. }
  6191. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6192. std::string out;
  6193. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6194. "Content-Type: text/plain\r\n"
  6195. "Transfer-Encoding: chunked\r\n"
  6196. "\r\n"
  6197. "nothex\r\n",
  6198. &out);
  6199. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6200. }
  6201. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6202. std::string out;
  6203. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6204. "Content-Type: text/plain\r\n"
  6205. "Transfer-Encoding: chunked\r\n"
  6206. "\r\n"
  6207. "3\r\n"
  6208. "xyz\r\n"
  6209. "NaN\r\n",
  6210. &out);
  6211. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6212. }
  6213. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6214. std::string out;
  6215. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6216. "Content-Type: text/plain\r\n"
  6217. "Transfer-Encoding: chunked\r\n"
  6218. "\r\n"
  6219. // Length is too large for 64 bits.
  6220. "1ffffffffffffffff\r\n"
  6221. "xyz\r\n",
  6222. &out);
  6223. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6224. }
  6225. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6226. test_raw_request("GET /hi HTTP/1.1\r\n"
  6227. "Content-Type: text/plain\r\n\r");
  6228. }
  6229. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6230. std::string out;
  6231. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6232. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6233. }
  6234. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6235. Server svr;
  6236. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6237. EXPECT_TRUE(!req.remote_addr.empty());
  6238. });
  6239. thread t = thread([&] { svr.listen(HOST, PORT); });
  6240. auto se = detail::scope_exit([&] {
  6241. svr.stop();
  6242. t.join();
  6243. ASSERT_FALSE(svr.is_running());
  6244. });
  6245. svr.wait_until_ready();
  6246. // Send an invalid request line to trigger Bad Request
  6247. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6248. std::string out;
  6249. ASSERT_TRUE(send_request(5, bad_req, &out));
  6250. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6251. }
  6252. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6253. std::string out;
  6254. std::string request(
  6255. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6256. test_raw_request(request, &out);
  6257. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6258. }
  6259. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6260. std::string out;
  6261. std::string request(
  6262. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6263. test_raw_request(request, &out);
  6264. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6265. }
  6266. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6267. std::string out;
  6268. std::string request(
  6269. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6270. test_raw_request(request, &out);
  6271. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6272. }
  6273. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6274. std::string out;
  6275. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6276. "Test: \r\n\r\n",
  6277. &out);
  6278. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6279. }
  6280. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6281. Server svr;
  6282. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6283. res.set_header("Cache-Control", "no-cache");
  6284. res.set_chunked_content_provider(
  6285. "text/event-stream", [](size_t offset, DataSink &sink) {
  6286. std::string s = "data:";
  6287. s += std::to_string(offset);
  6288. s += "\n\n";
  6289. auto ret = sink.write(s.data(), s.size());
  6290. EXPECT_TRUE(ret);
  6291. std::this_thread::sleep_for(std::chrono::seconds(1));
  6292. return true;
  6293. });
  6294. });
  6295. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6296. svr.wait_until_ready();
  6297. Client client(HOST, PORT);
  6298. const Headers headers = {{"Accept", "text/event-stream"}};
  6299. auto get_thread = std::thread([&client, &headers]() {
  6300. auto res = client.Get(
  6301. "/events", headers,
  6302. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6303. });
  6304. auto se = detail::scope_exit([&] {
  6305. svr.stop();
  6306. get_thread.join();
  6307. listen_thread.join();
  6308. ASSERT_FALSE(svr.is_running());
  6309. });
  6310. // Give GET time to get a few messages.
  6311. std::this_thread::sleep_for(std::chrono::seconds(2));
  6312. }
  6313. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6314. httplib::Server svr;
  6315. svr.Post("/hi",
  6316. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6317. res.status = StatusCode::OK_200;
  6318. });
  6319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6320. svr.wait_until_ready();
  6321. Client cli(HOST, PORT);
  6322. auto res = cli.Post("/hi", "data", "text/plain");
  6323. ASSERT_TRUE(res);
  6324. EXPECT_EQ(StatusCode::OK_200, res->status);
  6325. svr.stop();
  6326. thread.join();
  6327. ASSERT_FALSE(svr.is_running());
  6328. res = cli.Post("/hi", "data", "text/plain");
  6329. ASSERT_FALSE(res);
  6330. }
  6331. TEST(ServerStopTest, ListenFailure) {
  6332. Server svr;
  6333. auto t = thread([&]() {
  6334. auto ret = svr.listen("????", PORT);
  6335. EXPECT_FALSE(ret);
  6336. });
  6337. svr.wait_until_ready();
  6338. svr.stop();
  6339. t.join();
  6340. }
  6341. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6342. TEST(ServerStopTest, Decommision) {
  6343. Server svr;
  6344. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6345. for (int i = 0; i < 4; i++) {
  6346. auto is_even = !(i % 2);
  6347. std::thread t{[&] {
  6348. try {
  6349. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6350. if (is_even) {
  6351. throw std::runtime_error("Some thing that happens to go wrong.");
  6352. }
  6353. svr.listen(HOST, PORT);
  6354. } catch (...) { svr.decommission(); }
  6355. }};
  6356. svr.wait_until_ready();
  6357. // Server is up
  6358. {
  6359. Client cli(HOST, PORT);
  6360. auto res = cli.Get("/hi");
  6361. if (is_even) {
  6362. EXPECT_FALSE(res);
  6363. } else {
  6364. EXPECT_TRUE(res);
  6365. EXPECT_EQ("hi...", res->body);
  6366. }
  6367. }
  6368. svr.stop();
  6369. t.join();
  6370. // Server is down...
  6371. {
  6372. Client cli(HOST, PORT);
  6373. auto res = cli.Get("/hi");
  6374. EXPECT_FALSE(res);
  6375. }
  6376. }
  6377. }
  6378. #endif
  6379. // Helper function for string body upload progress tests
  6380. template <typename SetupHandler, typename ClientCall>
  6381. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6382. ClientCall &&client_call,
  6383. const string &body) {
  6384. Server svr;
  6385. setup_handler(svr);
  6386. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6387. auto se = detail::scope_exit([&] {
  6388. svr.stop();
  6389. t.join();
  6390. });
  6391. svr.wait_until_ready();
  6392. Client cli(HOST, PORT);
  6393. vector<uint64_t> progress_values;
  6394. bool progress_called = false;
  6395. auto res =
  6396. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6397. progress_values.push_back(current);
  6398. progress_called = true;
  6399. return true;
  6400. });
  6401. ASSERT_TRUE(res);
  6402. EXPECT_EQ(200, res->status);
  6403. EXPECT_TRUE(progress_called);
  6404. }
  6405. TEST(UploadProgressTest, PostStringBodyBasic) {
  6406. TestStringBodyUploadProgress(
  6407. [](Server &svr) {
  6408. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6409. res.set_content("received", "text/plain");
  6410. });
  6411. },
  6412. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6413. return cli.Post("/test", body, "text/plain", progress_callback);
  6414. },
  6415. "test data for upload progress");
  6416. }
  6417. TEST(UploadProgressTest, PutStringBodyBasic) {
  6418. TestStringBodyUploadProgress(
  6419. [](Server &svr) {
  6420. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6421. res.set_content("put received", "text/plain");
  6422. });
  6423. },
  6424. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6425. return cli.Put("/test", body, "text/plain", progress_callback);
  6426. },
  6427. "put test data for upload progress");
  6428. }
  6429. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6430. TestStringBodyUploadProgress(
  6431. [](Server &svr) {
  6432. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6433. res.set_content("patch received", "text/plain");
  6434. });
  6435. },
  6436. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6437. return cli.Patch("/test", body, "text/plain", progress_callback);
  6438. },
  6439. "patch test data for upload progress");
  6440. }
  6441. // Helper function for content provider upload progress tests
  6442. template <typename SetupHandler, typename ClientCall>
  6443. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6444. ClientCall &&client_call) {
  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. auto res =
  6456. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6457. progress_values.push_back(current);
  6458. return true;
  6459. });
  6460. ASSERT_TRUE(res);
  6461. EXPECT_EQ(200, res->status);
  6462. EXPECT_FALSE(progress_values.empty());
  6463. }
  6464. TEST(UploadProgressTest, PostContentProviderProgress) {
  6465. TestContentProviderUploadProgress(
  6466. [](Server &svr) {
  6467. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6468. res.set_content("provider received", "text/plain");
  6469. });
  6470. },
  6471. [](Client &cli, UploadProgress progress_callback) {
  6472. return cli.Post(
  6473. "/test", 10,
  6474. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6475. sink.os << "test data";
  6476. return true;
  6477. },
  6478. "text/plain", progress_callback);
  6479. });
  6480. }
  6481. // Helper function for multipart upload progress tests
  6482. template <typename SetupHandler, typename ClientCall>
  6483. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6484. ClientCall &&client_call,
  6485. const string &endpoint) {
  6486. Server svr;
  6487. setup_handler(svr);
  6488. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6489. auto se = detail::scope_exit([&] {
  6490. svr.stop();
  6491. t.join();
  6492. });
  6493. svr.wait_until_ready();
  6494. Client cli(HOST, PORT);
  6495. vector<uint64_t> progress_values;
  6496. UploadFormDataItems items = {
  6497. {"field1", "value1", "", ""},
  6498. {"field2", "longer value for progress tracking test", "", ""},
  6499. {"file1", "file content data for upload progress", "test.txt",
  6500. "text/plain"}};
  6501. auto res = client_call(cli, endpoint, items,
  6502. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6503. progress_values.push_back(current);
  6504. return true;
  6505. });
  6506. ASSERT_TRUE(res);
  6507. EXPECT_EQ(200, res->status);
  6508. EXPECT_FALSE(progress_values.empty());
  6509. }
  6510. TEST(UploadProgressTest, PostMultipartProgress) {
  6511. TestMultipartUploadProgress(
  6512. [](Server &svr) {
  6513. svr.Post("/multipart", [](const Request &req, Response &res) {
  6514. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6515. res.set_content("multipart received", "text/plain");
  6516. });
  6517. },
  6518. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6519. UploadProgress progress_callback) {
  6520. return cli.Post(endpoint, items, progress_callback);
  6521. },
  6522. "/multipart");
  6523. }
  6524. // Helper function for basic download progress tests
  6525. template <typename SetupHandler, typename ClientCall>
  6526. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6527. ClientCall &&client_call, const string &endpoint,
  6528. size_t expected_content_size) {
  6529. Server svr;
  6530. setup_handler(svr);
  6531. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6532. auto se = detail::scope_exit([&] {
  6533. svr.stop();
  6534. t.join();
  6535. });
  6536. svr.wait_until_ready();
  6537. Client cli(HOST, PORT);
  6538. vector<uint64_t> progress_values;
  6539. auto res = client_call(cli, endpoint,
  6540. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6541. progress_values.push_back(current);
  6542. return true;
  6543. });
  6544. ASSERT_TRUE(res);
  6545. EXPECT_EQ(200, res->status);
  6546. EXPECT_FALSE(progress_values.empty());
  6547. EXPECT_EQ(expected_content_size, res->body.size());
  6548. }
  6549. TEST(DownloadProgressTest, GetBasic) {
  6550. TestBasicDownloadProgress(
  6551. [](Server &svr) {
  6552. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6553. string content(1000, 'D');
  6554. res.set_content(content, "text/plain");
  6555. });
  6556. },
  6557. [](Client &cli, const string &endpoint,
  6558. DownloadProgress progress_callback) {
  6559. return cli.Get(endpoint, progress_callback);
  6560. },
  6561. "/download", 1000u);
  6562. }
  6563. // Helper function for content receiver download progress tests
  6564. template <typename SetupHandler, typename ClientCall>
  6565. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6566. ClientCall &&client_call,
  6567. const string &endpoint,
  6568. size_t expected_content_size) {
  6569. Server svr;
  6570. setup_handler(svr);
  6571. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6572. auto se = detail::scope_exit([&] {
  6573. svr.stop();
  6574. t.join();
  6575. });
  6576. svr.wait_until_ready();
  6577. Client cli(HOST, PORT);
  6578. vector<uint64_t> progress_values;
  6579. string received_body;
  6580. auto res = client_call(
  6581. cli, endpoint,
  6582. [&](const char *data, size_t data_length) -> bool {
  6583. received_body.append(data, data_length);
  6584. return true;
  6585. },
  6586. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6587. progress_values.push_back(current);
  6588. return true;
  6589. });
  6590. ASSERT_TRUE(res);
  6591. EXPECT_EQ(200, res->status);
  6592. EXPECT_FALSE(progress_values.empty());
  6593. EXPECT_EQ(expected_content_size, received_body.size());
  6594. EXPECT_TRUE(res->body.empty());
  6595. }
  6596. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6597. TestContentReceiverDownloadProgress(
  6598. [](Server &svr) {
  6599. svr.Get("/download-receiver",
  6600. [](const Request & /*req*/, Response &res) {
  6601. string content(2000, 'R');
  6602. res.set_content(content, "text/plain");
  6603. });
  6604. },
  6605. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6606. DownloadProgress progress_callback) {
  6607. return cli.Get(endpoint, content_receiver, progress_callback);
  6608. },
  6609. "/download-receiver", 2000u);
  6610. }
  6611. TEST(StreamingTest, NoContentLengthStreaming) {
  6612. Server svr;
  6613. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6614. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6615. if (offset < 6) {
  6616. sink.os << (offset < 3 ? "a" : "b");
  6617. } else {
  6618. sink.done();
  6619. }
  6620. return true;
  6621. });
  6622. });
  6623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6624. auto listen_se = detail::scope_exit([&] {
  6625. svr.stop();
  6626. listen_thread.join();
  6627. ASSERT_FALSE(svr.is_running());
  6628. });
  6629. svr.wait_until_ready();
  6630. Client client(HOST, PORT);
  6631. auto get_thread = std::thread([&client]() {
  6632. std::string s;
  6633. auto res =
  6634. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6635. s += std::string(data, len);
  6636. return true;
  6637. });
  6638. ASSERT_TRUE(res);
  6639. EXPECT_EQ(StatusCode::OK_200, res->status);
  6640. EXPECT_EQ("aaabbb", s);
  6641. });
  6642. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6643. // Give GET time to get a few messages.
  6644. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6645. }
  6646. TEST(MountTest, Unmount) {
  6647. Server svr;
  6648. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6649. auto se = detail::scope_exit([&] {
  6650. svr.stop();
  6651. listen_thread.join();
  6652. ASSERT_FALSE(svr.is_running());
  6653. });
  6654. svr.wait_until_ready();
  6655. Client cli("localhost", PORT);
  6656. svr.set_mount_point("/mount2", "./www2");
  6657. auto res = cli.Get("/");
  6658. ASSERT_TRUE(res);
  6659. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6660. res = cli.Get("/mount2/dir/test.html");
  6661. ASSERT_TRUE(res);
  6662. EXPECT_EQ(StatusCode::OK_200, res->status);
  6663. svr.set_mount_point("/", "./www");
  6664. res = cli.Get("/dir/");
  6665. ASSERT_TRUE(res);
  6666. EXPECT_EQ(StatusCode::OK_200, res->status);
  6667. svr.remove_mount_point("/");
  6668. res = cli.Get("/dir/");
  6669. ASSERT_TRUE(res);
  6670. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6671. svr.remove_mount_point("/mount2");
  6672. res = cli.Get("/mount2/dir/test.html");
  6673. ASSERT_TRUE(res);
  6674. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6675. }
  6676. TEST(MountTest, Redicect) {
  6677. Server svr;
  6678. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6679. auto se = detail::scope_exit([&] {
  6680. svr.stop();
  6681. listen_thread.join();
  6682. ASSERT_FALSE(svr.is_running());
  6683. });
  6684. svr.set_mount_point("/", "./www");
  6685. svr.wait_until_ready();
  6686. Client cli("localhost", PORT);
  6687. auto res = cli.Get("/dir/");
  6688. ASSERT_TRUE(res);
  6689. EXPECT_EQ(StatusCode::OK_200, res->status);
  6690. res = cli.Get("/dir");
  6691. ASSERT_TRUE(res);
  6692. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6693. res = cli.Get("/file");
  6694. ASSERT_TRUE(res);
  6695. EXPECT_EQ(StatusCode::OK_200, res->status);
  6696. res = cli.Get("/file/");
  6697. ASSERT_TRUE(res);
  6698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6699. cli.set_follow_location(true);
  6700. res = cli.Get("/dir");
  6701. ASSERT_TRUE(res);
  6702. EXPECT_EQ(StatusCode::OK_200, res->status);
  6703. }
  6704. TEST(MountTest, MultibytesPathName) {
  6705. Server svr;
  6706. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6707. auto se = detail::scope_exit([&] {
  6708. svr.stop();
  6709. listen_thread.join();
  6710. ASSERT_FALSE(svr.is_running());
  6711. });
  6712. svr.set_mount_point("/", "./www");
  6713. svr.wait_until_ready();
  6714. Client cli("localhost", PORT);
  6715. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6716. ASSERT_TRUE(res);
  6717. EXPECT_EQ(StatusCode::OK_200, res->status);
  6718. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6719. }
  6720. #ifdef _WIN32
  6721. // Issue #2435: mmap::open() must succeed even when another handle holds
  6722. // the file open for writing (e.g. an active log file).
  6723. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  6724. const char *path = "mmap_concurrent_writer_test.txt";
  6725. const char *content = "hello";
  6726. {
  6727. std::ofstream f(path, std::ios::binary);
  6728. f.write(content, static_cast<std::streamsize>(strlen(content)));
  6729. }
  6730. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  6731. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  6732. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  6733. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  6734. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  6735. detail::mmap m(path);
  6736. ASSERT_TRUE(m.is_open());
  6737. EXPECT_EQ(strlen(content), m.size());
  6738. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  6739. }
  6740. #endif
  6741. TEST(KeepAliveTest, ReadTimeout) {
  6742. Server svr;
  6743. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6744. std::this_thread::sleep_for(std::chrono::seconds(2));
  6745. res.set_content("a", "text/plain");
  6746. });
  6747. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6748. res.set_content("b", "text/plain");
  6749. });
  6750. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6751. auto se = detail::scope_exit([&] {
  6752. svr.stop();
  6753. listen_thread.join();
  6754. ASSERT_FALSE(svr.is_running());
  6755. });
  6756. svr.wait_until_ready();
  6757. Client cli("localhost", PORT);
  6758. cli.set_keep_alive(true);
  6759. cli.set_read_timeout(std::chrono::seconds(1));
  6760. auto resa = cli.Get("/a");
  6761. ASSERT_FALSE(resa);
  6762. EXPECT_EQ(Error::Read, resa.error());
  6763. auto resb = cli.Get("/b");
  6764. ASSERT_TRUE(resb);
  6765. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6766. EXPECT_EQ("b", resb->body);
  6767. }
  6768. TEST(KeepAliveTest, MaxCount) {
  6769. size_t keep_alive_max_count = 3;
  6770. Server svr;
  6771. svr.set_keep_alive_max_count(keep_alive_max_count);
  6772. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6773. res.set_content("Hello World!", "text/plain");
  6774. });
  6775. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6776. auto se = detail::scope_exit([&] {
  6777. svr.stop();
  6778. listen_thread.join();
  6779. ASSERT_FALSE(svr.is_running());
  6780. });
  6781. svr.wait_until_ready();
  6782. Client cli(HOST, PORT);
  6783. cli.set_keep_alive(true);
  6784. for (size_t i = 0; i < 5; i++) {
  6785. auto result = cli.Get("/hi");
  6786. ASSERT_TRUE(result);
  6787. EXPECT_EQ(StatusCode::OK_200, result->status);
  6788. if (i == keep_alive_max_count - 1) {
  6789. EXPECT_EQ("close", result->get_header_value("Connection"));
  6790. } else {
  6791. EXPECT_FALSE(result->has_header("Connection"));
  6792. }
  6793. }
  6794. }
  6795. TEST(KeepAliveTest, Issue1041) {
  6796. Server svr;
  6797. svr.set_keep_alive_timeout(3);
  6798. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6799. res.set_content("Hello World!", "text/plain");
  6800. });
  6801. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6802. auto se = detail::scope_exit([&] {
  6803. svr.stop();
  6804. listen_thread.join();
  6805. ASSERT_FALSE(svr.is_running());
  6806. });
  6807. svr.wait_until_ready();
  6808. Client cli(HOST, PORT);
  6809. cli.set_keep_alive(true);
  6810. auto result = cli.Get("/hi");
  6811. ASSERT_TRUE(result);
  6812. EXPECT_EQ(StatusCode::OK_200, result->status);
  6813. std::this_thread::sleep_for(std::chrono::seconds(5));
  6814. result = cli.Get("/hi");
  6815. ASSERT_TRUE(result);
  6816. EXPECT_EQ(StatusCode::OK_200, result->status);
  6817. }
  6818. TEST(KeepAliveTest, Issue1959) {
  6819. Server svr;
  6820. svr.set_keep_alive_timeout(5);
  6821. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6822. res.set_content("a", "text/plain");
  6823. });
  6824. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. if (!svr.is_running()) return;
  6827. svr.stop();
  6828. listen_thread.join();
  6829. ASSERT_FALSE(svr.is_running());
  6830. });
  6831. svr.wait_until_ready();
  6832. Client cli("localhost", PORT);
  6833. cli.set_keep_alive(true);
  6834. using namespace std::chrono;
  6835. auto start = steady_clock::now();
  6836. cli.Get("/a");
  6837. svr.stop();
  6838. listen_thread.join();
  6839. auto end = steady_clock::now();
  6840. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6841. EXPECT_LT(elapsed, 5000);
  6842. }
  6843. #ifdef CPPHTTPLIB_SSL_ENABLED
  6844. TEST(KeepAliveTest, SSLClientReconnection) {
  6845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6846. ASSERT_TRUE(svr.is_valid());
  6847. svr.set_keep_alive_timeout(1);
  6848. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6849. res.set_content("Hello World!", "text/plain");
  6850. });
  6851. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6852. auto se = detail::scope_exit([&] {
  6853. svr.stop();
  6854. listen_thread.join();
  6855. ASSERT_FALSE(svr.is_running());
  6856. });
  6857. svr.wait_until_ready();
  6858. SSLClient cli(HOST, PORT);
  6859. cli.enable_server_certificate_verification(false);
  6860. cli.set_keep_alive(true);
  6861. auto result = cli.Get("/hi");
  6862. ASSERT_TRUE(result);
  6863. EXPECT_EQ(StatusCode::OK_200, result->status);
  6864. result = cli.Get("/hi");
  6865. ASSERT_TRUE(result);
  6866. EXPECT_EQ(StatusCode::OK_200, result->status);
  6867. std::this_thread::sleep_for(std::chrono::seconds(2));
  6868. // Recoonect
  6869. result = cli.Get("/hi");
  6870. ASSERT_TRUE(result);
  6871. EXPECT_EQ(StatusCode::OK_200, result->status);
  6872. result = cli.Get("/hi");
  6873. ASSERT_TRUE(result);
  6874. EXPECT_EQ(StatusCode::OK_200, result->status);
  6875. }
  6876. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6878. ASSERT_TRUE(svr.is_valid());
  6879. svr.set_keep_alive_timeout(1);
  6880. std::string content = "reconnect";
  6881. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6882. res.set_content("Hello World!", "text/plain");
  6883. });
  6884. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6885. auto se = detail::scope_exit([&] {
  6886. svr.stop();
  6887. listen_thread.join();
  6888. ASSERT_FALSE(svr.is_running());
  6889. });
  6890. svr.wait_until_ready();
  6891. SSLClient cli(HOST, PORT);
  6892. cli.enable_server_certificate_verification(false);
  6893. cli.set_keep_alive(true);
  6894. auto result = cli.Post(
  6895. "/hi", content.size(),
  6896. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6897. sink.write(content.c_str(), content.size());
  6898. return true;
  6899. },
  6900. "text/plain");
  6901. ASSERT_TRUE(result);
  6902. EXPECT_EQ(200, result->status);
  6903. std::this_thread::sleep_for(std::chrono::seconds(2));
  6904. // Recoonect
  6905. result = cli.Post(
  6906. "/hi", content.size(),
  6907. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6908. sink.write(content.c_str(), content.size());
  6909. return true;
  6910. },
  6911. "text/plain");
  6912. ASSERT_TRUE(result);
  6913. EXPECT_EQ(200, result->status);
  6914. result = cli.Post(
  6915. "/hi", content.size(),
  6916. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6917. sink.write(content.c_str(), content.size());
  6918. return true;
  6919. },
  6920. "text/plain");
  6921. ASSERT_TRUE(result);
  6922. EXPECT_EQ(200, result->status);
  6923. }
  6924. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6925. using namespace httplib::tls;
  6926. {
  6927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6928. ASSERT_TRUE(svr.is_valid());
  6929. svr.Get("/sni", [&](const Request &req, Response &res) {
  6930. std::string expected = req.sni();
  6931. EXPECT_EQ(expected, req.get_param_value("expected"));
  6932. res.set_content("ok", "text/plain");
  6933. });
  6934. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6935. auto se = detail::scope_exit([&] {
  6936. svr.stop();
  6937. listen_thread.join();
  6938. ASSERT_FALSE(svr.is_running());
  6939. });
  6940. svr.wait_until_ready();
  6941. {
  6942. SSLClient cli("localhost", PORT);
  6943. cli.enable_server_certificate_verification(false);
  6944. auto res = cli.Get("/sni?expected=localhost");
  6945. ASSERT_TRUE(res);
  6946. }
  6947. {
  6948. SSLClient cli("::1", PORT);
  6949. cli.enable_server_certificate_verification(false);
  6950. auto res = cli.Get("/sni?expected=");
  6951. // NOTE: This may fail if the server is listening on IPv4 only
  6952. // (e.g., when localhost resolves to 127.0.0.1 only)
  6953. if (res) {
  6954. EXPECT_EQ(StatusCode::OK_200, res->status);
  6955. } else {
  6956. EXPECT_EQ(Error::Connection, res.error());
  6957. }
  6958. }
  6959. }
  6960. }
  6961. #endif
  6962. TEST(ClientProblemDetectionTest, ContentProvider) {
  6963. Server svr;
  6964. size_t content_length = 1024 * 1024;
  6965. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6966. res.set_content_provider(
  6967. content_length, "text/plain",
  6968. [&](size_t offset, size_t length, DataSink &sink) {
  6969. auto out_len = std::min(length, static_cast<size_t>(1024));
  6970. std::string out(out_len, '@');
  6971. sink.write(out.data(), out_len);
  6972. return offset < 4096;
  6973. },
  6974. [](bool success) { ASSERT_FALSE(success); });
  6975. });
  6976. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6977. res.set_content_provider(
  6978. 0, "text/plain",
  6979. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6980. EXPECT_TRUE(false);
  6981. return true;
  6982. },
  6983. [](bool success) { ASSERT_FALSE(success); });
  6984. });
  6985. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6986. auto se = detail::scope_exit([&] {
  6987. svr.stop();
  6988. listen_thread.join();
  6989. ASSERT_FALSE(svr.is_running());
  6990. });
  6991. svr.wait_until_ready();
  6992. Client cli("localhost", PORT);
  6993. {
  6994. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6995. size_t /*data_length*/) { return false; });
  6996. ASSERT_FALSE(res);
  6997. }
  6998. {
  6999. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7000. size_t /*data_length*/) { return false; });
  7001. ASSERT_TRUE(res);
  7002. }
  7003. }
  7004. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7005. Server svr;
  7006. svr.set_error_handler([](Request const &, Response &res) -> void {
  7007. res.set_chunked_content_provider(
  7008. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7009. sink.os << "hello";
  7010. sink.os << "world";
  7011. sink.done();
  7012. return true;
  7013. });
  7014. });
  7015. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7016. auto se = detail::scope_exit([&] {
  7017. svr.stop();
  7018. listen_thread.join();
  7019. ASSERT_FALSE(svr.is_running());
  7020. });
  7021. svr.wait_until_ready();
  7022. Client cli("localhost", PORT);
  7023. auto res = cli.Get("/");
  7024. ASSERT_TRUE(res);
  7025. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7026. EXPECT_EQ("helloworld", res->body);
  7027. }
  7028. TEST(LongPollingTest, ClientCloseDetection) {
  7029. Server svr;
  7030. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7031. res.set_chunked_content_provider(
  7032. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7033. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7034. sink.os << "hello";
  7035. auto count = 10;
  7036. while (count > 0 && sink.is_writable()) {
  7037. this_thread::sleep_for(chrono::milliseconds(10));
  7038. count--;
  7039. }
  7040. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7041. return true;
  7042. });
  7043. });
  7044. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7045. auto se = detail::scope_exit([&] {
  7046. svr.stop();
  7047. listen_thread.join();
  7048. ASSERT_FALSE(svr.is_running());
  7049. });
  7050. svr.wait_until_ready();
  7051. Client cli("localhost", PORT);
  7052. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7053. EXPECT_EQ("hello", string(data, data_length));
  7054. return false; // close the socket immediately.
  7055. });
  7056. ASSERT_FALSE(res);
  7057. }
  7058. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7059. Server svr;
  7060. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7061. res.set_chunked_content_provider(
  7062. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7063. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7064. sink.os << "hello";
  7065. EXPECT_TRUE(sink.os.good());
  7066. // Wait for the client to close the connection
  7067. auto count = 10;
  7068. while (count > 0 && sink.is_writable()) {
  7069. this_thread::sleep_for(chrono::milliseconds(10));
  7070. count--;
  7071. }
  7072. // After client disconnect, write repeatedly until the socket
  7073. // write actually fails (small writes may be absorbed by the
  7074. // kernel buffer)
  7075. std::string chunk(1024, 'x');
  7076. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7077. sink.os << chunk;
  7078. }
  7079. EXPECT_TRUE(sink.os.fail());
  7080. return true;
  7081. });
  7082. });
  7083. auto port = svr.bind_to_any_port("localhost");
  7084. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7085. auto se = detail::scope_exit([&] {
  7086. svr.stop();
  7087. listen_thread.join();
  7088. ASSERT_FALSE(svr.is_running());
  7089. });
  7090. svr.wait_until_ready();
  7091. Client cli("localhost", port);
  7092. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7093. EXPECT_EQ("hello", string(data, data_length));
  7094. return false; // close the socket immediately.
  7095. });
  7096. ASSERT_FALSE(res);
  7097. }
  7098. TEST(GetWithParametersTest, GetWithParameters) {
  7099. Server svr;
  7100. svr.Get("/", [&](const Request &req, Response &) {
  7101. EXPECT_EQ("world", req.get_param_value("hello"));
  7102. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7103. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7104. });
  7105. svr.Get("/params", [&](const Request &req, Response &) {
  7106. EXPECT_EQ("world", req.get_param_value("hello"));
  7107. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7108. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7109. });
  7110. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7111. EXPECT_EQ("resource-id", req.matches[1]);
  7112. EXPECT_EQ("foo", req.get_param_value("param1"));
  7113. EXPECT_EQ("bar", req.get_param_value("param2"));
  7114. });
  7115. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7116. EXPECT_EQ("user-id", req.path_params.at("id"));
  7117. EXPECT_EQ("foo", req.get_param_value("param1"));
  7118. EXPECT_EQ("bar", req.get_param_value("param2"));
  7119. });
  7120. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7121. auto se = detail::scope_exit([&] {
  7122. svr.stop();
  7123. listen_thread.join();
  7124. ASSERT_FALSE(svr.is_running());
  7125. });
  7126. svr.wait_until_ready();
  7127. {
  7128. Client cli(HOST, PORT);
  7129. Params params;
  7130. params.emplace("hello", "world");
  7131. params.emplace("hello2", "world2");
  7132. params.emplace("hello3", "world3");
  7133. auto res = cli.Get("/", params, Headers{});
  7134. ASSERT_TRUE(res);
  7135. EXPECT_EQ(StatusCode::OK_200, res->status);
  7136. }
  7137. {
  7138. Client cli(HOST, PORT);
  7139. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7140. ASSERT_TRUE(res);
  7141. EXPECT_EQ(StatusCode::OK_200, res->status);
  7142. }
  7143. {
  7144. Client cli(HOST, PORT);
  7145. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7146. ASSERT_TRUE(res);
  7147. EXPECT_EQ(StatusCode::OK_200, res->status);
  7148. }
  7149. {
  7150. Client cli(HOST, PORT);
  7151. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7152. ASSERT_TRUE(res);
  7153. EXPECT_EQ(StatusCode::OK_200, res->status);
  7154. }
  7155. }
  7156. TEST(GetWithParametersTest, GetWithParameters2) {
  7157. Server svr;
  7158. svr.Get("/", [&](const Request &req, Response &res) {
  7159. auto text = req.get_param_value("hello");
  7160. res.set_content(text, "text/plain");
  7161. });
  7162. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7163. auto se = detail::scope_exit([&] {
  7164. svr.stop();
  7165. listen_thread.join();
  7166. ASSERT_FALSE(svr.is_running());
  7167. });
  7168. svr.wait_until_ready();
  7169. Client cli("localhost", PORT);
  7170. Params params;
  7171. params.emplace("hello", "world");
  7172. std::string body;
  7173. auto res = cli.Get("/", params, Headers{},
  7174. [&](const char *data, size_t data_length) {
  7175. body.append(data, data_length);
  7176. return true;
  7177. });
  7178. ASSERT_TRUE(res);
  7179. EXPECT_EQ(StatusCode::OK_200, res->status);
  7180. EXPECT_EQ("world", body);
  7181. }
  7182. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7183. auto host = "httpbingo.org";
  7184. auto path = std::string{"/range/32"};
  7185. #ifdef CPPHTTPLIB_SSL_ENABLED
  7186. SSLClient cli(host);
  7187. #else
  7188. Client cli(host);
  7189. #endif
  7190. cli.set_default_headers({make_range_header({{1, 10}})});
  7191. cli.set_connection_timeout(5);
  7192. {
  7193. auto res = cli.Get(path);
  7194. ASSERT_TRUE(res);
  7195. EXPECT_EQ("bcdefghijk", res->body);
  7196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7197. }
  7198. {
  7199. auto res = cli.Get(path);
  7200. ASSERT_TRUE(res);
  7201. EXPECT_EQ("bcdefghijk", res->body);
  7202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7203. }
  7204. }
  7205. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7206. Server svr;
  7207. svr.set_default_headers({{"Hello", "World"}});
  7208. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7209. res.set_content("ok", "text/plain");
  7210. });
  7211. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7212. auto se = detail::scope_exit([&] {
  7213. svr.stop();
  7214. listen_thread.join();
  7215. ASSERT_FALSE(svr.is_running());
  7216. });
  7217. svr.wait_until_ready();
  7218. Client cli("localhost", PORT);
  7219. auto res = cli.Get("/");
  7220. ASSERT_TRUE(res);
  7221. EXPECT_EQ(StatusCode::OK_200, res->status);
  7222. EXPECT_EQ("ok", res->body);
  7223. EXPECT_EQ("World", res->get_header_value("Hello"));
  7224. }
  7225. #ifdef CPPHTTPLIB_SSL_ENABLED
  7226. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7227. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7228. ASSERT_TRUE(svr.is_valid());
  7229. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7230. std::this_thread::sleep_for(std::chrono::seconds(2));
  7231. res.set_content("a", "text/plain");
  7232. });
  7233. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7234. res.set_content("b", "text/plain");
  7235. });
  7236. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7237. auto se = detail::scope_exit([&] {
  7238. svr.stop();
  7239. listen_thread.join();
  7240. ASSERT_FALSE(svr.is_running());
  7241. });
  7242. svr.wait_until_ready();
  7243. SSLClient cli("localhost", PORT);
  7244. cli.enable_server_certificate_verification(false);
  7245. cli.set_keep_alive(true);
  7246. cli.set_read_timeout(std::chrono::seconds(1));
  7247. auto resa = cli.Get("/a");
  7248. ASSERT_TRUE(!resa);
  7249. EXPECT_EQ(Error::Read, resa.error());
  7250. auto resb = cli.Get("/b");
  7251. ASSERT_TRUE(resb);
  7252. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7253. EXPECT_EQ("b", resb->body);
  7254. }
  7255. #endif
  7256. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7257. protected:
  7258. ServerTestWithAI_PASSIVE()
  7259. : cli_(HOST, PORT)
  7260. #ifdef CPPHTTPLIB_SSL_ENABLED
  7261. ,
  7262. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7263. #endif
  7264. {
  7265. #ifdef CPPHTTPLIB_SSL_ENABLED
  7266. cli_.enable_server_certificate_verification(false);
  7267. #endif
  7268. }
  7269. virtual void SetUp() {
  7270. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7271. res.set_content("Hello World!", "text/plain");
  7272. });
  7273. t_ = thread(
  7274. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7275. svr_.wait_until_ready();
  7276. }
  7277. virtual void TearDown() {
  7278. svr_.stop();
  7279. t_.join();
  7280. }
  7281. #ifdef CPPHTTPLIB_SSL_ENABLED
  7282. SSLClient cli_;
  7283. SSLServer svr_;
  7284. #else
  7285. Client cli_;
  7286. Server svr_;
  7287. #endif
  7288. thread t_;
  7289. };
  7290. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7291. auto res = cli_.Get("/hi");
  7292. ASSERT_TRUE(res);
  7293. EXPECT_EQ(StatusCode::OK_200, res->status);
  7294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7295. EXPECT_EQ("Hello World!", res->body);
  7296. }
  7297. class ServerUpDownTest : public ::testing::Test {
  7298. protected:
  7299. ServerUpDownTest() : cli_(HOST, PORT) {}
  7300. virtual void SetUp() {
  7301. t_ = thread([&]() {
  7302. svr_.bind_to_any_port(HOST);
  7303. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7304. ASSERT_TRUE(svr_.listen_after_bind());
  7305. });
  7306. svr_.wait_until_ready();
  7307. }
  7308. virtual void TearDown() {
  7309. svr_.stop();
  7310. t_.join();
  7311. }
  7312. Client cli_;
  7313. Server svr_;
  7314. thread t_;
  7315. };
  7316. TEST_F(ServerUpDownTest, QuickStartStop) {
  7317. // Should not crash, especially when run with
  7318. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7319. }
  7320. class PayloadMaxLengthTest : public ::testing::Test {
  7321. protected:
  7322. PayloadMaxLengthTest()
  7323. : cli_(HOST, PORT)
  7324. #ifdef CPPHTTPLIB_SSL_ENABLED
  7325. ,
  7326. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7327. #endif
  7328. {
  7329. #ifdef CPPHTTPLIB_SSL_ENABLED
  7330. cli_.enable_server_certificate_verification(false);
  7331. #endif
  7332. }
  7333. virtual void SetUp() {
  7334. svr_.set_payload_max_length(8);
  7335. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7336. res.set_content("test", "text/plain");
  7337. });
  7338. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7339. svr_.wait_until_ready();
  7340. }
  7341. virtual void TearDown() {
  7342. svr_.stop();
  7343. t_.join();
  7344. }
  7345. #ifdef CPPHTTPLIB_SSL_ENABLED
  7346. SSLClient cli_;
  7347. SSLServer svr_;
  7348. #else
  7349. Client cli_;
  7350. Server svr_;
  7351. #endif
  7352. thread t_;
  7353. };
  7354. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7355. auto res = cli_.Post("/test", "123456789", "text/plain");
  7356. ASSERT_TRUE(res);
  7357. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7358. res = cli_.Post("/test", "12345678", "text/plain");
  7359. ASSERT_TRUE(res);
  7360. EXPECT_EQ(StatusCode::OK_200, res->status);
  7361. }
  7362. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7363. // Test chunked encoding with payload exceeding the 8-byte limit
  7364. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7365. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7366. ASSERT_TRUE(res);
  7367. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7368. }
  7369. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7370. // Test chunked encoding with payload within the 8-byte limit
  7371. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7372. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7373. ASSERT_TRUE(res);
  7374. EXPECT_EQ(StatusCode::OK_200, res->status);
  7375. }
  7376. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7377. // Test using send_request to send chunked data exceeding payload limit
  7378. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7379. "Host: " +
  7380. std::string(HOST) + ":" + std::to_string(PORT) +
  7381. "\r\n"
  7382. "Transfer-Encoding: chunked\r\n"
  7383. "Connection: close\r\n"
  7384. "\r\n"
  7385. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7386. "0123456789\r\n"
  7387. "0\r\n" // End chunk
  7388. "\r\n";
  7389. std::string response;
  7390. bool result = send_request(1, chunked_request, &response);
  7391. if (!result) {
  7392. // If send_request fails, it might be because the server closed the
  7393. // connection due to payload limit enforcement, which is acceptable
  7394. SUCCEED()
  7395. << "Server rejected oversized chunked request (connection closed)";
  7396. } else {
  7397. // If we got a response, check if it's an error response or connection was
  7398. // closed early Short response length indicates connection was closed due to
  7399. // payload limit
  7400. if (response.length() <= 10) {
  7401. SUCCEED() << "Server closed connection for oversized chunked request";
  7402. } else {
  7403. // Check for error status codes
  7404. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7405. response.find("Payload Too Large") != std::string::npos ||
  7406. response.find("400") != std::string::npos);
  7407. }
  7408. }
  7409. }
  7410. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7411. // Test request without Content-Length header exceeding payload limit
  7412. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7413. "Host: " +
  7414. std::string(HOST) + ":" +
  7415. std::to_string(PORT) +
  7416. "\r\n"
  7417. "Connection: close\r\n"
  7418. "\r\n";
  7419. // Add payload exceeding the 8-byte limit
  7420. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7421. request_without_content_length += large_payload;
  7422. std::string response;
  7423. bool result = send_request(1, request_without_content_length, &response);
  7424. if (!result) {
  7425. // If send_request fails, server likely closed connection due to payload
  7426. // limit
  7427. SUCCEED() << "Server rejected oversized request without Content-Length "
  7428. "(connection closed)";
  7429. } else {
  7430. // Check if server responded with error or closed connection early
  7431. if (response.length() <= 10) {
  7432. SUCCEED() << "Server closed connection for oversized request without "
  7433. "Content-Length";
  7434. } else {
  7435. // Check for error status codes
  7436. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7437. response.find("Payload Too Large") != std::string::npos ||
  7438. response.find("400") != std::string::npos);
  7439. }
  7440. }
  7441. }
  7442. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7443. // Test request without Content-Length header within payload limit
  7444. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7445. "Host: " +
  7446. std::string(HOST) + ":" +
  7447. std::to_string(PORT) +
  7448. "\r\n"
  7449. "Connection: close\r\n"
  7450. "\r\n";
  7451. // Add payload within the 8-byte limit
  7452. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7453. request_without_content_length += small_payload;
  7454. std::string response;
  7455. bool result = send_request(1, request_without_content_length, &response);
  7456. // For requests without Content-Length, the server may have different behavior
  7457. // The key is that it should not reject due to payload limit for small
  7458. // payloads
  7459. if (result) {
  7460. // Check for any HTTP response (success or error, but not connection closed)
  7461. if (response.length() > 10) {
  7462. SUCCEED()
  7463. << "Server processed request without Content-Length within limit";
  7464. } else {
  7465. // Short response might indicate connection closed, which is acceptable
  7466. SUCCEED() << "Server closed connection for request without "
  7467. "Content-Length (acceptable behavior)";
  7468. }
  7469. } else {
  7470. // Connection failure might be due to protocol requirements
  7471. SUCCEED() << "Connection issue with request without Content-Length "
  7472. "(environment-specific)";
  7473. }
  7474. }
  7475. class LargePayloadMaxLengthTest : public ::testing::Test {
  7476. protected:
  7477. LargePayloadMaxLengthTest()
  7478. : cli_(HOST, PORT)
  7479. #ifdef CPPHTTPLIB_SSL_ENABLED
  7480. ,
  7481. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7482. #endif
  7483. {
  7484. #ifdef CPPHTTPLIB_SSL_ENABLED
  7485. cli_.enable_server_certificate_verification(false);
  7486. #endif
  7487. }
  7488. virtual void SetUp() {
  7489. // Set 10MB payload limit
  7490. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7491. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7492. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7493. res.set_content("Large payload test", "text/plain");
  7494. });
  7495. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7496. svr_.wait_until_ready();
  7497. }
  7498. virtual void TearDown() {
  7499. svr_.stop();
  7500. t_.join();
  7501. }
  7502. #ifdef CPPHTTPLIB_SSL_ENABLED
  7503. SSLClient cli_;
  7504. SSLServer svr_;
  7505. #else
  7506. Client cli_;
  7507. Server svr_;
  7508. #endif
  7509. thread t_;
  7510. };
  7511. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7512. // Test chunked encoding with payload within 10MB limit
  7513. std::string medium_payload(5 * 1024 * 1024,
  7514. 'A'); // 5MB payload, within 10MB limit
  7515. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7516. ASSERT_TRUE(res);
  7517. EXPECT_EQ(StatusCode::OK_200, res->status);
  7518. }
  7519. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7520. // Test chunked encoding with payload exceeding 10MB limit
  7521. std::string large_payload(12 * 1024 * 1024,
  7522. 'B'); // 12MB payload, exceeds 10MB limit
  7523. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7524. // Server may either return 413 or close the connection
  7525. if (res) {
  7526. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7527. } else {
  7528. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7529. }
  7530. }
  7531. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7532. // Test request without Content-Length header within 10MB limit
  7533. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7534. "Host: " +
  7535. std::string(HOST) + ":" +
  7536. std::to_string(PORT) +
  7537. "\r\n"
  7538. "Connection: close\r\n"
  7539. "\r\n";
  7540. // Add 1MB payload (within 10MB limit)
  7541. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7542. request_without_content_length += medium_payload;
  7543. std::string response;
  7544. bool result = send_request(5, request_without_content_length, &response);
  7545. if (result) {
  7546. // Should get a proper HTTP response for payloads within limit
  7547. if (response.length() > 10) {
  7548. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7549. "10MB limit";
  7550. } else {
  7551. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7552. "Content-Length)";
  7553. }
  7554. } else {
  7555. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7556. }
  7557. }
  7558. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7559. // Test request without Content-Length header exceeding 10MB limit
  7560. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7561. "Host: " +
  7562. std::string(HOST) + ":" +
  7563. std::to_string(PORT) +
  7564. "\r\n"
  7565. "Connection: close\r\n"
  7566. "\r\n";
  7567. // Add 12MB payload (exceeds 10MB limit)
  7568. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7569. request_without_content_length += large_payload;
  7570. std::string response;
  7571. bool result = send_request(10, request_without_content_length, &response);
  7572. if (!result) {
  7573. // Server should close connection due to payload limit
  7574. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7575. "(connection closed)";
  7576. } else {
  7577. // Check for error response
  7578. if (response.length() <= 10) {
  7579. SUCCEED()
  7580. << "Server closed connection for 12MB request exceeding 10MB limit";
  7581. } else {
  7582. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7583. response.find("Payload Too Large") != std::string::npos ||
  7584. response.find("400") != std::string::npos);
  7585. }
  7586. }
  7587. }
  7588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7589. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7590. // path.
  7591. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7592. Server svr;
  7593. const size_t LIMIT = 64 * 1024; // 64KB
  7594. svr.set_payload_max_length(LIMIT);
  7595. size_t total = 0;
  7596. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7597. const ContentReader &content_reader) {
  7598. content_reader([&](const char * /*data*/, size_t len) {
  7599. total += len;
  7600. return true;
  7601. });
  7602. res.status = 200;
  7603. res.set_content("stream_ok", "text/plain");
  7604. });
  7605. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7606. auto se = detail::scope_exit([&] {
  7607. svr.stop();
  7608. thread.join();
  7609. ASSERT_FALSE(svr.is_running());
  7610. });
  7611. svr.wait_until_ready();
  7612. // Prepare 256KB raw data and gzip-compress it
  7613. std::string raw(256 * 1024, 'A');
  7614. std::string gz;
  7615. {
  7616. z_stream zs{};
  7617. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7618. Z_DEFAULT_STRATEGY);
  7619. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7620. zs.avail_in = static_cast<uInt>(raw.size());
  7621. char outbuf[4096];
  7622. int ret;
  7623. do {
  7624. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7625. zs.avail_out = sizeof(outbuf);
  7626. ret = deflate(&zs, Z_FINISH);
  7627. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7628. } while (ret != Z_STREAM_END);
  7629. deflateEnd(&zs);
  7630. }
  7631. Client cli(HOST, PORT);
  7632. cli.set_connection_timeout(std::chrono::seconds(5));
  7633. Headers headers = {{"Content-Encoding", "gzip"}};
  7634. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7635. "application/octet-stream");
  7636. ASSERT_TRUE(res);
  7637. // Server must reject oversized decompressed payloads with 413.
  7638. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7639. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7640. EXPECT_LE(total, LIMIT);
  7641. }
  7642. #endif
  7643. // Regression test for DoS vulnerability: a malicious server sending a response
  7644. // without Content-Length header must not cause unbounded memory consumption on
  7645. // the client side. The client should stop reading after a reasonable limit,
  7646. // similar to the server-side set_payload_max_length protection.
  7647. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7648. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7649. #ifndef _WIN32
  7650. signal(SIGPIPE, SIG_IGN);
  7651. #endif
  7652. auto server_thread = std::thread([] {
  7653. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7654. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7655. default_socket_options(srv);
  7656. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7657. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7658. sockaddr_in addr{};
  7659. addr.sin_family = AF_INET;
  7660. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7661. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7662. int opt = 1;
  7663. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7664. #ifdef _WIN32
  7665. reinterpret_cast<const char *>(&opt),
  7666. #else
  7667. &opt,
  7668. #endif
  7669. sizeof(opt));
  7670. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7671. ::listen(srv, 1);
  7672. sockaddr_in cli_addr{};
  7673. socklen_t cli_len = sizeof(cli_addr);
  7674. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7675. if (cli != INVALID_SOCKET) {
  7676. char buf[4096];
  7677. ::recv(cli, buf, sizeof(buf), 0);
  7678. // Malicious response: no Content-Length, no chunked encoding
  7679. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7680. "Connection: close\r\n"
  7681. "\r\n";
  7682. ::send(cli,
  7683. #ifdef _WIN32
  7684. static_cast<const char *>(response_header.c_str()),
  7685. static_cast<int>(response_header.size()),
  7686. #else
  7687. response_header.c_str(), response_header.size(),
  7688. #endif
  7689. 0);
  7690. // Send 10MB of data
  7691. std::string chunk(64 * 1024, 'A');
  7692. size_t total_sent = 0;
  7693. while (total_sent < MALICIOUS_DATA_SIZE) {
  7694. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7695. auto sent = ::send(cli,
  7696. #ifdef _WIN32
  7697. static_cast<const char *>(chunk.c_str()),
  7698. static_cast<int>(to_send),
  7699. #else
  7700. chunk.c_str(), to_send,
  7701. #endif
  7702. 0);
  7703. if (sent <= 0) break;
  7704. total_sent += static_cast<size_t>(sent);
  7705. }
  7706. detail::close_socket(cli);
  7707. }
  7708. detail::close_socket(srv);
  7709. });
  7710. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7711. size_t total_read = 0;
  7712. {
  7713. Client cli("127.0.0.1", PORT + 2);
  7714. cli.set_read_timeout(5, 0);
  7715. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7716. auto stream = cli.open_stream("GET", "/malicious");
  7717. ASSERT_TRUE(stream.is_valid());
  7718. char buffer[64 * 1024];
  7719. ssize_t n;
  7720. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7721. total_read += static_cast<size_t>(n);
  7722. }
  7723. } // StreamHandle and Client destroyed here, closing the socket
  7724. server_thread.join();
  7725. // With set_payload_max_length, the client must stop reading before consuming
  7726. // all 10MB. The read loop should be cut off at or near the configured limit.
  7727. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7728. << "Client read " << total_read << " bytes, exceeding the configured "
  7729. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7730. }
  7731. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7732. // the entire response body without truncation.
  7733. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7734. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7735. #ifndef _WIN32
  7736. signal(SIGPIPE, SIG_IGN);
  7737. #endif
  7738. auto server_thread = std::thread([] {
  7739. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7740. default_socket_options(srv);
  7741. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7742. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7743. sockaddr_in addr{};
  7744. addr.sin_family = AF_INET;
  7745. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7746. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7747. int opt = 1;
  7748. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7749. #ifdef _WIN32
  7750. reinterpret_cast<const char *>(&opt),
  7751. #else
  7752. &opt,
  7753. #endif
  7754. sizeof(opt));
  7755. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7756. ::listen(srv, 1);
  7757. sockaddr_in cli_addr{};
  7758. socklen_t cli_len = sizeof(cli_addr);
  7759. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7760. if (cli != INVALID_SOCKET) {
  7761. char buf[4096];
  7762. ::recv(cli, buf, sizeof(buf), 0);
  7763. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7764. "Connection: close\r\n"
  7765. "\r\n";
  7766. ::send(cli,
  7767. #ifdef _WIN32
  7768. static_cast<const char *>(response_header.c_str()),
  7769. static_cast<int>(response_header.size()),
  7770. #else
  7771. response_header.c_str(), response_header.size(),
  7772. #endif
  7773. 0);
  7774. std::string chunk(64 * 1024, 'A');
  7775. size_t total_sent = 0;
  7776. while (total_sent < DATA_SIZE) {
  7777. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7778. auto sent = ::send(cli,
  7779. #ifdef _WIN32
  7780. static_cast<const char *>(chunk.c_str()),
  7781. static_cast<int>(to_send),
  7782. #else
  7783. chunk.c_str(), to_send,
  7784. #endif
  7785. 0);
  7786. if (sent <= 0) break;
  7787. total_sent += static_cast<size_t>(sent);
  7788. }
  7789. #ifdef _WIN32
  7790. ::shutdown(cli, SD_SEND);
  7791. #else
  7792. ::shutdown(cli, SHUT_WR);
  7793. #endif
  7794. // Drain until the client closes its end, ensuring all data is delivered
  7795. char drain[1024];
  7796. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7797. detail::close_socket(cli);
  7798. }
  7799. detail::close_socket(srv);
  7800. });
  7801. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7802. size_t total_read = 0;
  7803. {
  7804. Client cli("127.0.0.1", PORT + 2);
  7805. cli.set_read_timeout(5, 0);
  7806. cli.set_payload_max_length(0); // 0 means no limit
  7807. auto stream = cli.open_stream("GET", "/data");
  7808. ASSERT_TRUE(stream.is_valid());
  7809. char buffer[64 * 1024];
  7810. ssize_t n;
  7811. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7812. total_read += static_cast<size_t>(n);
  7813. }
  7814. }
  7815. server_thread.join();
  7816. EXPECT_EQ(total_read, DATA_SIZE)
  7817. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7818. << " bytes without truncation, but only read " << total_read << " bytes.";
  7819. }
  7820. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  7821. // enormous Content-Length must not cause the client to pre-allocate a huge
  7822. // response body buffer. The reservation is capped at payload_max_length_, and
  7823. // the read itself fails when the body exceeds the limit.
  7824. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  7825. #ifndef _WIN32
  7826. signal(SIGPIPE, SIG_IGN);
  7827. #endif
  7828. auto server_thread = std::thread([] {
  7829. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7830. default_socket_options(srv);
  7831. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7832. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7833. sockaddr_in addr{};
  7834. addr.sin_family = AF_INET;
  7835. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7836. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7837. int opt = 1;
  7838. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7839. #ifdef _WIN32
  7840. reinterpret_cast<const char *>(&opt),
  7841. #else
  7842. &opt,
  7843. #endif
  7844. sizeof(opt));
  7845. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7846. ::listen(srv, 1);
  7847. sockaddr_in cli_addr{};
  7848. socklen_t cli_len = sizeof(cli_addr);
  7849. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7850. if (cli != INVALID_SOCKET) {
  7851. char buf[4096];
  7852. ::recv(cli, buf, sizeof(buf), 0);
  7853. // Malicious response: claim a 20GB body but send only a tiny payload.
  7854. std::string response = "HTTP/1.1 200 OK\r\n"
  7855. "Content-Length: 20000000000\r\n"
  7856. "\r\n"
  7857. "abc";
  7858. ::send(cli,
  7859. #ifdef _WIN32
  7860. static_cast<const char *>(response.c_str()),
  7861. static_cast<int>(response.size()),
  7862. #else
  7863. response.c_str(), response.size(),
  7864. #endif
  7865. 0);
  7866. detail::close_socket(cli);
  7867. }
  7868. detail::close_socket(srv);
  7869. });
  7870. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7871. {
  7872. Client cli("127.0.0.1", PORT + 2);
  7873. cli.set_read_timeout(5, 0);
  7874. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  7875. // result in a 20GB pre-allocation. The Get() call is expected to fail
  7876. // (server claims more bytes than payload_max_length permits), but it must
  7877. // not exhaust memory before getting there.
  7878. auto res = cli.Get("/malicious");
  7879. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  7880. }
  7881. server_thread.join();
  7882. }
  7883. // Verify that content_receiver bypasses the default payload_max_length,
  7884. // allowing streaming downloads larger than 100MB without requiring an explicit
  7885. // set_payload_max_length call.
  7886. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7887. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7888. #ifndef _WIN32
  7889. signal(SIGPIPE, SIG_IGN);
  7890. #endif
  7891. auto server_thread = std::thread([] {
  7892. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7893. default_socket_options(srv);
  7894. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7895. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7896. sockaddr_in addr{};
  7897. addr.sin_family = AF_INET;
  7898. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7899. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7900. int opt = 1;
  7901. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7902. #ifdef _WIN32
  7903. reinterpret_cast<const char *>(&opt),
  7904. #else
  7905. &opt,
  7906. #endif
  7907. sizeof(opt));
  7908. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7909. ::listen(srv, 1);
  7910. sockaddr_in cli_addr{};
  7911. socklen_t cli_len = sizeof(cli_addr);
  7912. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7913. if (cli != INVALID_SOCKET) {
  7914. char buf[4096];
  7915. ::recv(cli, buf, sizeof(buf), 0);
  7916. // Response with Content-Length larger than default 100MB limit
  7917. auto content_length = std::to_string(DATA_SIZE);
  7918. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7919. "Content-Length: " +
  7920. content_length +
  7921. "\r\n"
  7922. "Connection: close\r\n"
  7923. "\r\n";
  7924. ::send(cli,
  7925. #ifdef _WIN32
  7926. static_cast<const char *>(response_header.c_str()),
  7927. static_cast<int>(response_header.size()),
  7928. #else
  7929. response_header.c_str(), response_header.size(),
  7930. #endif
  7931. 0);
  7932. std::string chunk(64 * 1024, 'A');
  7933. size_t total_sent = 0;
  7934. while (total_sent < DATA_SIZE) {
  7935. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7936. auto sent = ::send(cli,
  7937. #ifdef _WIN32
  7938. static_cast<const char *>(chunk.c_str()),
  7939. static_cast<int>(to_send),
  7940. #else
  7941. chunk.c_str(), to_send,
  7942. #endif
  7943. 0);
  7944. if (sent <= 0) break;
  7945. total_sent += static_cast<size_t>(sent);
  7946. }
  7947. detail::close_socket(cli);
  7948. }
  7949. detail::close_socket(srv);
  7950. });
  7951. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7952. size_t total_received = 0;
  7953. {
  7954. Client cli("127.0.0.1", PORT + 2);
  7955. cli.set_read_timeout(10, 0);
  7956. // Do NOT call set_payload_max_length — use the default 100MB limit
  7957. auto res =
  7958. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7959. total_received += data_length;
  7960. return true;
  7961. });
  7962. ASSERT_TRUE(res);
  7963. EXPECT_EQ(StatusCode::OK_200, res->status);
  7964. }
  7965. server_thread.join();
  7966. EXPECT_EQ(total_received, DATA_SIZE)
  7967. << "With content_receiver, the client should read all " << DATA_SIZE
  7968. << " bytes despite the default 100MB payload_max_length, but only read "
  7969. << total_received << " bytes.";
  7970. }
  7971. // Verify that an explicit set_payload_max_length smaller than the response is
  7972. // enforced even when a content_receiver is used.
  7973. TEST(ClientVulnerabilityTest,
  7974. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7975. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7976. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7977. #ifndef _WIN32
  7978. signal(SIGPIPE, SIG_IGN);
  7979. #endif
  7980. auto server_thread = std::thread([] {
  7981. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7982. default_socket_options(srv);
  7983. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7984. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7985. sockaddr_in addr{};
  7986. addr.sin_family = AF_INET;
  7987. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7988. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7989. int opt = 1;
  7990. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7991. #ifdef _WIN32
  7992. reinterpret_cast<const char *>(&opt),
  7993. #else
  7994. &opt,
  7995. #endif
  7996. sizeof(opt));
  7997. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7998. ::listen(srv, 1);
  7999. sockaddr_in cli_addr{};
  8000. socklen_t cli_len = sizeof(cli_addr);
  8001. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8002. if (cli != INVALID_SOCKET) {
  8003. char buf[4096];
  8004. ::recv(cli, buf, sizeof(buf), 0);
  8005. auto content_length = std::to_string(DATA_SIZE);
  8006. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8007. "Content-Length: " +
  8008. content_length +
  8009. "\r\n"
  8010. "Connection: close\r\n"
  8011. "\r\n";
  8012. ::send(cli,
  8013. #ifdef _WIN32
  8014. static_cast<const char *>(response_header.c_str()),
  8015. static_cast<int>(response_header.size()),
  8016. #else
  8017. response_header.c_str(), response_header.size(),
  8018. #endif
  8019. 0);
  8020. std::string chunk(64 * 1024, 'A');
  8021. size_t total_sent = 0;
  8022. while (total_sent < DATA_SIZE) {
  8023. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8024. auto sent = ::send(cli,
  8025. #ifdef _WIN32
  8026. static_cast<const char *>(chunk.c_str()),
  8027. static_cast<int>(to_send),
  8028. #else
  8029. chunk.c_str(), to_send,
  8030. #endif
  8031. 0);
  8032. if (sent <= 0) break;
  8033. total_sent += static_cast<size_t>(sent);
  8034. }
  8035. detail::close_socket(cli);
  8036. }
  8037. detail::close_socket(srv);
  8038. });
  8039. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8040. size_t total_received = 0;
  8041. {
  8042. Client cli("127.0.0.1", PORT + 2);
  8043. cli.set_read_timeout(10, 0);
  8044. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8045. auto res =
  8046. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8047. total_received += data_length;
  8048. return true;
  8049. });
  8050. // Should fail because 200MB exceeds the explicit 150MB limit
  8051. EXPECT_FALSE(res);
  8052. }
  8053. server_thread.join();
  8054. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8055. << "Client with content_receiver should respect the explicit "
  8056. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8057. << total_received << " bytes.";
  8058. }
  8059. // Verify that an explicit set_payload_max_length larger than the response
  8060. // allows the content_receiver to read all data successfully.
  8061. TEST(ClientVulnerabilityTest,
  8062. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8063. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8064. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8065. #ifndef _WIN32
  8066. signal(SIGPIPE, SIG_IGN);
  8067. #endif
  8068. auto server_thread = std::thread([] {
  8069. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8070. default_socket_options(srv);
  8071. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8072. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8073. sockaddr_in addr{};
  8074. addr.sin_family = AF_INET;
  8075. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8076. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8077. int opt = 1;
  8078. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8079. #ifdef _WIN32
  8080. reinterpret_cast<const char *>(&opt),
  8081. #else
  8082. &opt,
  8083. #endif
  8084. sizeof(opt));
  8085. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8086. ::listen(srv, 1);
  8087. sockaddr_in cli_addr{};
  8088. socklen_t cli_len = sizeof(cli_addr);
  8089. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8090. if (cli != INVALID_SOCKET) {
  8091. char buf[4096];
  8092. ::recv(cli, buf, sizeof(buf), 0);
  8093. auto content_length = std::to_string(DATA_SIZE);
  8094. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8095. "Content-Length: " +
  8096. content_length +
  8097. "\r\n"
  8098. "Connection: close\r\n"
  8099. "\r\n";
  8100. ::send(cli,
  8101. #ifdef _WIN32
  8102. static_cast<const char *>(response_header.c_str()),
  8103. static_cast<int>(response_header.size()),
  8104. #else
  8105. response_header.c_str(), response_header.size(),
  8106. #endif
  8107. 0);
  8108. std::string chunk(64 * 1024, 'A');
  8109. size_t total_sent = 0;
  8110. while (total_sent < DATA_SIZE) {
  8111. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8112. auto sent = ::send(cli,
  8113. #ifdef _WIN32
  8114. static_cast<const char *>(chunk.c_str()),
  8115. static_cast<int>(to_send),
  8116. #else
  8117. chunk.c_str(), to_send,
  8118. #endif
  8119. 0);
  8120. if (sent <= 0) break;
  8121. total_sent += static_cast<size_t>(sent);
  8122. }
  8123. #ifdef _WIN32
  8124. ::shutdown(cli, SD_SEND);
  8125. #else
  8126. ::shutdown(cli, SHUT_WR);
  8127. #endif
  8128. char drain[1024];
  8129. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8130. detail::close_socket(cli);
  8131. }
  8132. detail::close_socket(srv);
  8133. });
  8134. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8135. size_t total_received = 0;
  8136. {
  8137. Client cli("127.0.0.1", PORT + 2);
  8138. cli.set_read_timeout(10, 0);
  8139. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8140. auto res =
  8141. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8142. total_received += data_length;
  8143. return true;
  8144. });
  8145. ASSERT_TRUE(res);
  8146. EXPECT_EQ(StatusCode::OK_200, res->status);
  8147. }
  8148. server_thread.join();
  8149. EXPECT_EQ(total_received, DATA_SIZE)
  8150. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8151. << " bytes (larger than " << DATA_SIZE
  8152. << " bytes response), content_receiver should read all data, but only "
  8153. "read "
  8154. << total_received << " bytes.";
  8155. }
  8156. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8157. // Regression test for "zip bomb" attack on the client side: a malicious server
  8158. // sends a small gzip-compressed response that decompresses to a huge payload.
  8159. // The client must enforce payload_max_length on the decompressed size.
  8160. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8161. constexpr size_t DECOMPRESSED_SIZE =
  8162. 10 * 1024 * 1024; // 10MB after decompression
  8163. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8164. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8165. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8166. std::string compressed;
  8167. {
  8168. httplib::detail::gzip_compressor compressor;
  8169. bool ok =
  8170. compressor.compress(uncompressed.data(), uncompressed.size(),
  8171. /*last=*/true, [&](const char *buf, size_t len) {
  8172. compressed.append(buf, len);
  8173. return true;
  8174. });
  8175. ASSERT_TRUE(ok);
  8176. }
  8177. // Sanity: compressed data should be much smaller than the decompressed size
  8178. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8179. #ifndef _WIN32
  8180. signal(SIGPIPE, SIG_IGN);
  8181. #endif
  8182. // Set up the listening socket in the main thread so the server is guaranteed
  8183. // to be ready before the client connects (eliminates race condition).
  8184. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8185. default_socket_options(srv);
  8186. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8187. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8188. sockaddr_in addr{};
  8189. addr.sin_family = AF_INET;
  8190. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8191. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8192. int opt = 1;
  8193. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8194. #ifdef _WIN32
  8195. reinterpret_cast<const char *>(&opt),
  8196. #else
  8197. &opt,
  8198. #endif
  8199. sizeof(opt));
  8200. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8201. ASSERT_EQ(0, ::listen(srv, 1));
  8202. auto server_thread = std::thread([&compressed, srv] {
  8203. sockaddr_in cli_addr{};
  8204. socklen_t cli_len = sizeof(cli_addr);
  8205. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8206. if (cli != INVALID_SOCKET) {
  8207. // Read the full HTTP request (until \r\n\r\n)
  8208. char buf[4096];
  8209. size_t total = 0;
  8210. while (total < sizeof(buf)) {
  8211. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8212. if (n <= 0) break;
  8213. total += static_cast<size_t>(n);
  8214. // Check for end of headers
  8215. if (total >= 4) {
  8216. std::string req(buf, total);
  8217. if (req.find("\r\n\r\n") != std::string::npos) break;
  8218. }
  8219. }
  8220. // Malicious response: gzip-compressed body, no Content-Length
  8221. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8222. "Content-Encoding: gzip\r\n"
  8223. "Connection: close\r\n"
  8224. "\r\n";
  8225. ::send(cli,
  8226. #ifdef _WIN32
  8227. static_cast<const char *>(response_header.c_str()),
  8228. static_cast<int>(response_header.size()),
  8229. #else
  8230. response_header.c_str(), response_header.size(),
  8231. #endif
  8232. 0);
  8233. // Send the compressed payload (small on the wire, huge when decompressed)
  8234. size_t total_sent = 0;
  8235. while (total_sent < compressed.size()) {
  8236. auto to_send = std::min(compressed.size() - total_sent,
  8237. static_cast<size_t>(64 * 1024));
  8238. auto sent =
  8239. ::send(cli,
  8240. #ifdef _WIN32
  8241. static_cast<const char *>(compressed.c_str() + total_sent),
  8242. static_cast<int>(to_send),
  8243. #else
  8244. compressed.c_str() + total_sent, to_send,
  8245. #endif
  8246. 0);
  8247. if (sent <= 0) break;
  8248. total_sent += static_cast<size_t>(sent);
  8249. }
  8250. detail::close_socket(cli);
  8251. }
  8252. });
  8253. auto se = detail::scope_exit([&] {
  8254. detail::close_socket(srv);
  8255. server_thread.join();
  8256. });
  8257. size_t total_decompressed = 0;
  8258. {
  8259. Client cli("127.0.0.1", PORT + 3);
  8260. cli.set_read_timeout(5, 0);
  8261. cli.set_decompress(true);
  8262. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8263. auto stream = cli.open_stream("GET", "/zipbomb");
  8264. ASSERT_TRUE(stream.is_valid());
  8265. char buffer[64 * 1024];
  8266. ssize_t n;
  8267. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8268. total_decompressed += static_cast<size_t>(n);
  8269. }
  8270. }
  8271. // The decompressed size must be capped by payload_max_length. Without
  8272. // protection, the client would decompress the full 10MB from a tiny
  8273. // compressed payload, enabling a zip bomb DoS attack.
  8274. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8275. << "Client decompressed " << total_decompressed
  8276. << " bytes from a gzip response. The decompressed size should be "
  8277. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8278. }
  8279. #endif
  8280. TEST(HostAndPortPropertiesTest, NoSSL) {
  8281. httplib::Client cli("www.google.com", 1234);
  8282. ASSERT_EQ("www.google.com", cli.host());
  8283. ASSERT_EQ(1234, cli.port());
  8284. }
  8285. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8286. httplib::Client cli("www.google.com:1234");
  8287. ASSERT_EQ("www.google.com", cli.host());
  8288. ASSERT_EQ(1234, cli.port());
  8289. }
  8290. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8291. // Port number that overflows int — should not crash, client becomes invalid
  8292. httplib::Client cli("http://www.google.com:99999999999999999999");
  8293. ASSERT_FALSE(cli.is_valid());
  8294. }
  8295. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8296. // Port 99999 exceeds valid range (1-65535) — should not crash
  8297. httplib::Client cli("http://www.google.com:99999");
  8298. ASSERT_FALSE(cli.is_valid());
  8299. }
  8300. #ifdef CPPHTTPLIB_SSL_ENABLED
  8301. TEST(HostAndPortPropertiesTest, SSL) {
  8302. httplib::SSLClient cli("www.google.com");
  8303. ASSERT_EQ("www.google.com", cli.host());
  8304. ASSERT_EQ(443, cli.port());
  8305. }
  8306. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8307. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8308. std::string cert;
  8309. read_file(CA_CERT_FILE, cert);
  8310. httplib::SSLClient httplib_client("www.google.com");
  8311. // Load CA store first time
  8312. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8313. // Load CA store second time (update)
  8314. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8315. // Verify client is still valid and can make connections
  8316. httplib_client.enable_server_certificate_verification(true);
  8317. auto res = httplib_client.Get("/");
  8318. ASSERT_TRUE(res);
  8319. // Google may return 200 or 301 depending on various factors
  8320. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8321. res->status == StatusCode::MovedPermanently_301);
  8322. }
  8323. TEST(SSLClientTest, ServerNameIndication_Online) {
  8324. auto host = "httpbingo.org";
  8325. auto path = std::string{"/get"};
  8326. SSLClient cli(host, 443);
  8327. auto res = cli.Get(path);
  8328. ASSERT_TRUE(res);
  8329. ASSERT_EQ(StatusCode::OK_200, res->status);
  8330. }
  8331. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8332. // Use a site that will cause SSL verification failure due to self-signed cert
  8333. SSLClient cli("self-signed.badssl.com", 443);
  8334. cli.enable_server_certificate_verification(true);
  8335. auto res = cli.Get("/");
  8336. ASSERT_TRUE(!res);
  8337. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8338. // Verify backend error is captured for SSLServerVerification
  8339. // This occurs when certificate verification fails
  8340. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8341. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8342. EXPECT_NE(0UL, res.ssl_backend_error());
  8343. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8344. // For OpenSSL, ssl_error is 0 for verification errors
  8345. EXPECT_EQ(0, res.ssl_error());
  8346. #if !defined(_WIN32) || \
  8347. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8348. // On non-Windows or when Windows Schannel is disabled, the error comes
  8349. // from OpenSSL's verification
  8350. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8351. res.ssl_backend_error());
  8352. #endif
  8353. #endif
  8354. }
  8355. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8356. // Use a site where hostname doesn't match the certificate
  8357. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8358. SSLClient cli("wrong.host.badssl.com", 443);
  8359. cli.enable_server_certificate_verification(true);
  8360. cli.enable_server_hostname_verification(true);
  8361. auto res = cli.Get("/");
  8362. ASSERT_TRUE(!res);
  8363. // The error type depends on when hostname verification occurs:
  8364. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8365. // - Mbed TLS: SSLServerVerification (during handshake)
  8366. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8367. res.error() == Error::SSLServerVerification);
  8368. // Verify backend error is captured for hostname verification failure
  8369. EXPECT_NE(0UL, res.ssl_backend_error());
  8370. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8371. // For OpenSSL, ssl_error is 0 for verification errors
  8372. EXPECT_EQ(0, res.ssl_error());
  8373. #if !defined(_WIN32) || \
  8374. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8375. // On non-Windows or when Windows Schannel is disabled, the error comes
  8376. // from OpenSSL's hostname verification
  8377. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8378. res.ssl_backend_error());
  8379. #endif
  8380. #endif
  8381. }
  8382. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8383. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8384. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8385. SSLClient cli("www.google.com", 443);
  8386. cli.enable_server_certificate_verification(true);
  8387. auto res = cli.Get("/");
  8388. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8389. }
  8390. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8391. SSLClient cli("www.google.com", 443);
  8392. cli.enable_server_certificate_verification(true);
  8393. cli.enable_windows_certificate_verification(false);
  8394. auto res = cli.Get("/");
  8395. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8396. }
  8397. #endif
  8398. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8399. Client cli("https://google.com");
  8400. auto res = cli.Get("/");
  8401. ASSERT_TRUE(res);
  8402. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8403. }
  8404. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8405. SSLClient cli("google.com");
  8406. cli.set_ca_cert_path(CA_CERT_FILE);
  8407. auto res = cli.Get("/");
  8408. ASSERT_TRUE(res);
  8409. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8410. }
  8411. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8412. SSLClient cli("google.com");
  8413. cli.enable_server_certificate_verification(true);
  8414. cli.set_ca_cert_path("hello");
  8415. auto res = cli.Get("/");
  8416. ASSERT_TRUE(!res);
  8417. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8418. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8419. // should be set
  8420. EXPECT_EQ(0, res.ssl_error());
  8421. // Verify backend error is captured for SSLLoadingCerts
  8422. // This error occurs when loading CA certificates fails
  8423. EXPECT_NE(0UL, res.ssl_backend_error());
  8424. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8425. // OpenSSL specific error codes:
  8426. // > openssl errstr 0x80000002
  8427. // error:80000002:system library::No such file or directory
  8428. // > openssl errstr 0xA000126
  8429. // error:0A000126:SSL routines::unexpected eof while reading
  8430. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8431. res.ssl_backend_error() == 0xA000126);
  8432. #endif
  8433. }
  8434. TEST(SSLClientTest, ServerCertificateVerification4) {
  8435. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8436. ASSERT_TRUE(svr.is_valid());
  8437. svr.Get("/test", [&](const Request &, Response &res) {
  8438. res.set_content("test", "text/plain");
  8439. svr.stop();
  8440. ASSERT_TRUE(true);
  8441. });
  8442. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8443. auto se = detail::scope_exit([&] {
  8444. t.join();
  8445. ASSERT_FALSE(svr.is_running());
  8446. });
  8447. svr.wait_until_ready();
  8448. SSLClient cli("127.0.0.1", PORT);
  8449. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8450. cli.enable_server_certificate_verification(true);
  8451. cli.set_connection_timeout(30);
  8452. auto res = cli.Get("/test");
  8453. ASSERT_TRUE(res);
  8454. ASSERT_EQ(StatusCode::OK_200, res->status);
  8455. }
  8456. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8457. std::string cert;
  8458. read_file(CA_CERT_FILE, cert);
  8459. SSLClient cli("google.com");
  8460. cli.load_ca_cert_store(cert.data(), cert.size());
  8461. const auto res = cli.Get("/");
  8462. ASSERT_TRUE(res);
  8463. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8464. }
  8465. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8466. // clang-format off
  8467. static constexpr char cert[] =
  8468. "GlobalSign Root CA\n"
  8469. "==================\n"
  8470. "-----BEGIN CERTIFICATE-----\n"
  8471. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8472. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8473. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8474. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8475. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8476. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8477. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8478. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8479. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8480. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8481. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8482. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8483. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8484. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8485. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8486. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8487. "-----END CERTIFICATE-----\n";
  8488. // clang-format on
  8489. SSLClient cli("google.com");
  8490. cli.load_ca_cert_store(cert, sizeof(cert));
  8491. const auto res = cli.Get("/");
  8492. ASSERT_TRUE(res);
  8493. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8494. }
  8495. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8496. SSLClient cli("www.youtube.com");
  8497. cli.set_ca_cert_path(CA_CERT_FILE);
  8498. cli.enable_server_certificate_verification(true);
  8499. cli.set_follow_location(true);
  8500. auto res = cli.Get("/");
  8501. ASSERT_TRUE(res);
  8502. ASSERT_EQ(StatusCode::OK_200, res->status);
  8503. }
  8504. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8505. SSLClient cli("wWw.YouTube.Com");
  8506. cli.set_ca_cert_path(CA_CERT_FILE);
  8507. cli.enable_server_certificate_verification(true);
  8508. cli.enable_server_hostname_verification(true);
  8509. cli.set_follow_location(true);
  8510. auto res = cli.Get("/");
  8511. ASSERT_TRUE(res);
  8512. ASSERT_EQ(StatusCode::OK_200, res->status);
  8513. }
  8514. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8515. SSLClient cli("gOoGlE.COm");
  8516. cli.enable_server_certificate_verification(true);
  8517. cli.enable_server_hostname_verification(true);
  8518. cli.set_follow_location(true);
  8519. auto res = cli.Get("/");
  8520. ASSERT_TRUE(res);
  8521. ASSERT_EQ(StatusCode::OK_200, res->status);
  8522. }
  8523. TEST(SSLClientTest, Issue2004_Online) {
  8524. Client client("https://google.com");
  8525. client.set_follow_location(true);
  8526. auto res = client.Get("/");
  8527. ASSERT_TRUE(res);
  8528. ASSERT_EQ(StatusCode::OK_200, res->status);
  8529. auto body = res->body;
  8530. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8531. }
  8532. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8533. // Create SSLClient with invalid cert/key to make is_valid() return false
  8534. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8535. "nonexistent_key.pem");
  8536. // is_valid() should be false due to cert loading failure
  8537. ASSERT_FALSE(cli.is_valid());
  8538. auto res = cli.Get("/");
  8539. ASSERT_FALSE(res);
  8540. EXPECT_EQ(Error::SSLConnection, res.error());
  8541. }
  8542. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8543. // Test for Issue #2251: SSL error not properly reported when client cert
  8544. // and key paths are swapped or mismatched
  8545. // This simulates the scenario where user accidentally swaps the cert and key
  8546. // files
  8547. // Using client cert file as private key and vice versa (completely wrong)
  8548. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8549. // Should fail validation due to cert/key mismatch
  8550. ASSERT_FALSE(cli.is_valid());
  8551. // Attempt to make a request should fail with proper error
  8552. auto res = cli.Get("/");
  8553. ASSERT_FALSE(res);
  8554. EXPECT_EQ(Error::SSLConnection, res.error());
  8555. // SSL error should be recorded in the Result object (this is the key fix for
  8556. // Issue #2251)
  8557. auto backend_error = res.ssl_backend_error();
  8558. EXPECT_NE(0u, backend_error);
  8559. }
  8560. // Tests cert/key mismatch detection at the TLS context level
  8561. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8562. // Test that using mismatched cert/key causes connection failure.
  8563. // We verify this at the SSLClient level rather than through internal
  8564. // TLS API functions.
  8565. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8566. cli.enable_server_certificate_verification(false);
  8567. cli.set_connection_timeout(2);
  8568. // The mismatch should cause a connection or handshake error
  8569. auto res = cli.Get("/test");
  8570. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8571. // Either way, the request should fail
  8572. EXPECT_FALSE(res);
  8573. }
  8574. #endif
  8575. #if 0
  8576. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8577. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8578. ASSERT_TRUE(cli != nullptr);
  8579. cli->set_address_family(AF_INET6);
  8580. cli->set_interface("en0");
  8581. auto res = cli->Get("/get");
  8582. ASSERT_TRUE(res);
  8583. ASSERT_EQ(StatusCode::OK_200, res->status);
  8584. }
  8585. #endif
  8586. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8587. #ifdef CPPHTTPLIB_SSL_ENABLED
  8588. void ClientCertPresent(
  8589. const std::string &client_cert_file,
  8590. const std::string &client_private_key_file,
  8591. const std::string &client_encrypted_private_key_pass = std::string()) {
  8592. using namespace httplib::tls;
  8593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8594. CLIENT_CA_CERT_DIR);
  8595. ASSERT_TRUE(svr.is_valid());
  8596. svr.Get("/test", [&](const Request &req, Response &res) {
  8597. res.set_content("test", "text/plain");
  8598. auto cert = req.peer_cert();
  8599. ASSERT_TRUE(static_cast<bool>(cert));
  8600. std::string common_name = cert.subject_cn();
  8601. EXPECT_EQ("Common Name", common_name);
  8602. });
  8603. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8604. auto se = detail::scope_exit([&] {
  8605. svr.stop();
  8606. t.join();
  8607. ASSERT_FALSE(svr.is_running());
  8608. });
  8609. svr.wait_until_ready();
  8610. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8611. client_encrypted_private_key_pass);
  8612. cli.enable_server_certificate_verification(false);
  8613. cli.set_connection_timeout(30);
  8614. auto res = cli.Get("/test");
  8615. ASSERT_TRUE(res);
  8616. ASSERT_EQ(StatusCode::OK_200, res->status);
  8617. }
  8618. TEST(SSLClientServerTest, ClientCertPresent) {
  8619. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8620. }
  8621. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8622. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8623. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8624. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8625. }
  8626. // PEM memory-based constructor tests (works with all TLS backends)
  8627. void PemMemoryClientCertPresent(
  8628. const std::string &client_cert_file,
  8629. const std::string &client_private_key_file,
  8630. const std::string &client_encrypted_private_key_pass = std::string()) {
  8631. // Read PEM files into memory
  8632. std::string server_cert_pem, server_key_pem;
  8633. std::string client_ca_pem;
  8634. std::string client_cert_pem, client_key_pem;
  8635. read_file(SERVER_CERT_FILE, server_cert_pem);
  8636. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8637. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8638. read_file(client_cert_file, client_cert_pem);
  8639. read_file(client_private_key_file, client_key_pem);
  8640. // Create server with PEM memory
  8641. SSLServer::PemMemory server_pem = {
  8642. server_cert_pem.c_str(),
  8643. server_cert_pem.size(),
  8644. server_key_pem.c_str(),
  8645. server_key_pem.size(),
  8646. client_ca_pem.c_str(),
  8647. client_ca_pem.size(),
  8648. nullptr // no password for server key
  8649. };
  8650. SSLServer svr(server_pem);
  8651. ASSERT_TRUE(svr.is_valid());
  8652. svr.Get("/test", [&](const Request &, Response &res) {
  8653. res.set_content("test", "text/plain");
  8654. });
  8655. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8656. auto se = detail::scope_exit([&] {
  8657. svr.stop();
  8658. t.join();
  8659. ASSERT_FALSE(svr.is_running());
  8660. });
  8661. svr.wait_until_ready();
  8662. // Create client with PEM memory
  8663. const char *password = client_encrypted_private_key_pass.empty()
  8664. ? nullptr
  8665. : client_encrypted_private_key_pass.c_str();
  8666. SSLClient::PemMemory client_pem = {
  8667. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8668. client_key_pem.size(), password};
  8669. SSLClient cli(HOST, PORT, client_pem);
  8670. cli.enable_server_certificate_verification(false);
  8671. cli.set_connection_timeout(30);
  8672. auto res = cli.Get("/test");
  8673. ASSERT_TRUE(res);
  8674. ASSERT_EQ(StatusCode::OK_200, res->status);
  8675. }
  8676. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8677. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8678. }
  8679. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8680. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8681. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8682. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8683. }
  8684. TEST(SSLClientServerTest, ClientCertMissing) {
  8685. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8686. CLIENT_CA_CERT_DIR);
  8687. ASSERT_TRUE(svr.is_valid());
  8688. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8689. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8690. auto se = detail::scope_exit([&] {
  8691. svr.stop();
  8692. t.join();
  8693. ASSERT_FALSE(svr.is_running());
  8694. });
  8695. svr.wait_until_ready();
  8696. SSLClient cli(HOST, PORT);
  8697. cli.set_connection_timeout(30);
  8698. auto res = cli.Get("/test");
  8699. ASSERT_TRUE(!res);
  8700. // When client cert is missing and server requires it, connection fails
  8701. // Error type depends on backend implementation
  8702. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8703. res.error() == Error::SSLConnection);
  8704. // Verify backend error is captured
  8705. // Note: This test may have different error codes depending on the exact
  8706. // verification failure
  8707. EXPECT_NE(0UL, res.ssl_backend_error());
  8708. }
  8709. TEST(SSLClientServerTest, TrustDirOptional) {
  8710. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8711. ASSERT_TRUE(svr.is_valid());
  8712. svr.Get("/test", [&](const Request &, Response &res) {
  8713. res.set_content("test", "text/plain");
  8714. });
  8715. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8716. auto se = detail::scope_exit([&] {
  8717. svr.stop();
  8718. t.join();
  8719. ASSERT_FALSE(svr.is_running());
  8720. });
  8721. svr.wait_until_ready();
  8722. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8723. cli.enable_server_certificate_verification(false);
  8724. cli.set_connection_timeout(30);
  8725. auto res = cli.Get("/test");
  8726. ASSERT_TRUE(res);
  8727. ASSERT_EQ(StatusCode::OK_200, res->status);
  8728. }
  8729. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8730. class NoListenSSLServer : public SSLServer {
  8731. public:
  8732. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8733. const char *client_ca_cert_file_path,
  8734. const char *client_ca_cert_dir_path = nullptr)
  8735. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8736. client_ca_cert_dir_path),
  8737. stop_(false) {}
  8738. std::atomic_bool stop_;
  8739. private:
  8740. bool process_and_close_socket(socket_t /*sock*/) override {
  8741. // Don't create SSL context
  8742. while (!stop_.load()) {
  8743. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8744. }
  8745. return true;
  8746. }
  8747. };
  8748. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8749. CLIENT_CA_CERT_FILE);
  8750. ASSERT_TRUE(svr.is_valid());
  8751. svr.Get("/test", [&](const Request &, Response &res) {
  8752. res.set_content("test", "text/plain");
  8753. });
  8754. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8755. auto se = detail::scope_exit([&] {
  8756. svr.stop_ = true;
  8757. svr.stop();
  8758. t.join();
  8759. ASSERT_FALSE(svr.is_running());
  8760. });
  8761. svr.wait_until_ready();
  8762. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8763. cli.enable_server_certificate_verification(false);
  8764. cli.set_connection_timeout(1);
  8765. auto res = cli.Get("/test");
  8766. ASSERT_TRUE(!res);
  8767. EXPECT_EQ(Error::SSLConnection, res.error());
  8768. // Timeout results in WantRead error code (maps to backend-specific value)
  8769. EXPECT_NE(0, res.ssl_error());
  8770. }
  8771. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8772. // Test SSLServer with client certificate verification using the standard
  8773. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8774. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8775. CLIENT_CA_CERT_DIR);
  8776. ASSERT_TRUE(svr.is_valid());
  8777. svr.Get("/test", [&](const Request &req, Response &res) {
  8778. res.set_content("test", "text/plain");
  8779. auto cert = req.peer_cert();
  8780. ASSERT_TRUE(static_cast<bool>(cert));
  8781. auto common_name = cert.subject_cn();
  8782. EXPECT_EQ("Common Name", common_name);
  8783. });
  8784. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8785. auto se = detail::scope_exit([&] {
  8786. svr.stop();
  8787. t.join();
  8788. ASSERT_FALSE(svr.is_running());
  8789. });
  8790. svr.wait_until_ready();
  8791. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8792. cli.enable_server_certificate_verification(false);
  8793. cli.set_connection_timeout(30);
  8794. auto res = cli.Get("/test");
  8795. ASSERT_TRUE(res);
  8796. ASSERT_EQ(StatusCode::OK_200, res->status);
  8797. }
  8798. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8799. // Verifies that wildcard matching and exact matching work consistently
  8800. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8801. using namespace httplib::tls;
  8802. // We need a running server to test against
  8803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8804. ASSERT_TRUE(svr.is_valid());
  8805. svr.Get("/test", [](const Request &, Response &res) {
  8806. res.set_content("ok", "text/plain");
  8807. });
  8808. thread t([&]() { svr.listen(HOST, PORT); });
  8809. auto se = detail::scope_exit([&] {
  8810. svr.stop();
  8811. t.join();
  8812. });
  8813. svr.wait_until_ready();
  8814. bool verify_callback_called = false;
  8815. bool verify_result_wrong = false;
  8816. SSLClient cli(HOST, PORT);
  8817. cli.enable_server_certificate_verification(true);
  8818. cli.set_ca_cert_path(CA_CERT_FILE);
  8819. cli.set_connection_timeout(5);
  8820. // Note: Test certificate has CN="Common Name", not "localhost"
  8821. bool verify_result_cn = false;
  8822. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8823. verify_callback_called = true;
  8824. if (!ctx.cert) return false;
  8825. // Test 1: "Common Name" should match (our test server cert CN)
  8826. verify_result_cn = ctx.check_hostname("Common Name");
  8827. // Test 2: wrong hostname should not match
  8828. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8829. return true; // Accept for the purpose of this test
  8830. });
  8831. auto res = cli.Get("/test");
  8832. // The request may succeed or fail depending on cert configuration
  8833. // but the callback should have been called
  8834. ASSERT_TRUE(verify_callback_called)
  8835. << "Verify callback should have been called";
  8836. // CN="Common Name" should match our test certificate
  8837. EXPECT_TRUE(verify_result_cn)
  8838. << "verify_hostname should match 'Common Name' (certificate CN)";
  8839. // Wrong hostname should not match
  8840. EXPECT_FALSE(verify_result_wrong)
  8841. << "verify_hostname should not match 'wronghost.example.com'";
  8842. }
  8843. #endif
  8844. // mbedTLS-specific callback constructor test
  8845. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8846. #ifdef CPPHTTPLIB_SSL_ENABLED
  8847. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8849. ASSERT_TRUE(svr.is_valid());
  8850. // Set up a handler to verify client certificate is present
  8851. bool client_cert_verified = false;
  8852. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8853. // Verify that client certificate was provided
  8854. client_cert_verified = true;
  8855. res.set_content("success", "text/plain");
  8856. });
  8857. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8858. auto se = detail::scope_exit([&] {
  8859. svr.stop();
  8860. t.join();
  8861. ASSERT_FALSE(svr.is_running());
  8862. });
  8863. svr.wait_until_ready();
  8864. // Client with certificate
  8865. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8866. cli.enable_server_certificate_verification(false);
  8867. cli.set_connection_timeout(30);
  8868. auto res = cli.Get("/test");
  8869. ASSERT_TRUE(res);
  8870. ASSERT_EQ(StatusCode::OK_200, res->status);
  8871. ASSERT_TRUE(client_cert_verified);
  8872. EXPECT_EQ("success", res->body);
  8873. }
  8874. #endif
  8875. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8876. // backends
  8877. #ifdef CPPHTTPLIB_SSL_ENABLED
  8878. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8879. using namespace httplib::tls;
  8880. // Test that when client CA cert file is provided,
  8881. // the server properly requests and validates client certificates
  8882. // Create a server with client authentication
  8883. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8884. ASSERT_TRUE(svr.is_valid());
  8885. bool handler_called = false;
  8886. svr.Get("/test", [&](const Request &req, Response &res) {
  8887. handler_called = true;
  8888. // Verify that a client certificate was provided
  8889. auto cert = req.peer_cert();
  8890. ASSERT_TRUE(static_cast<bool>(cert));
  8891. // Get the issuer name
  8892. std::string issuer_str = cert.issuer_name();
  8893. ASSERT_FALSE(issuer_str.empty());
  8894. // The client certificate should be issued by our test CA
  8895. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8896. res.set_content("authenticated", "text/plain");
  8897. });
  8898. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8899. auto se = detail::scope_exit([&] {
  8900. svr.stop();
  8901. t.join();
  8902. ASSERT_FALSE(svr.is_running());
  8903. });
  8904. svr.wait_until_ready();
  8905. // Connect with a client certificate issued by the CA
  8906. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8907. cli.enable_server_certificate_verification(false);
  8908. cli.set_connection_timeout(30);
  8909. auto res = cli.Get("/test");
  8910. ASSERT_TRUE(res);
  8911. ASSERT_EQ(StatusCode::OK_200, res->status);
  8912. ASSERT_TRUE(handler_called);
  8913. EXPECT_EQ("authenticated", res->body);
  8914. }
  8915. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8916. using namespace httplib::tls;
  8917. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8918. ASSERT_TRUE(svr.is_valid());
  8919. svr.Get("/test", [](const Request &, Response &res) {
  8920. res.set_content("ok", "text/plain");
  8921. });
  8922. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8923. auto se = detail::scope_exit([&] {
  8924. svr.stop();
  8925. t.join();
  8926. });
  8927. svr.wait_until_ready();
  8928. SSLClient cli(HOST, PORT);
  8929. cli.enable_server_certificate_verification(false);
  8930. cli.set_connection_timeout(30);
  8931. bool cert_checked = false;
  8932. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8933. if (ctx.cert) {
  8934. auto sans = ctx.sans();
  8935. // Test certificate may or may not have SANs - just verify the API
  8936. // works If SANs exist, verify the types are valid
  8937. for (const auto &san : sans) {
  8938. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8939. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8940. san.type == SanType::OTHER);
  8941. EXPECT_FALSE(san.value.empty());
  8942. }
  8943. cert_checked = true;
  8944. }
  8945. return true;
  8946. });
  8947. auto res = cli.Get("/test");
  8948. ASSERT_TRUE(res);
  8949. EXPECT_TRUE(cert_checked);
  8950. }
  8951. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8952. using namespace httplib::tls;
  8953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8954. ASSERT_TRUE(svr.is_valid());
  8955. svr.Get("/test", [](const Request &, Response &res) {
  8956. res.set_content("ok", "text/plain");
  8957. });
  8958. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8959. auto se = detail::scope_exit([&] {
  8960. svr.stop();
  8961. t.join();
  8962. });
  8963. svr.wait_until_ready();
  8964. SSLClient cli(HOST, PORT);
  8965. cli.enable_server_certificate_verification(false);
  8966. cli.set_connection_timeout(30);
  8967. bool validity_checked = false;
  8968. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8969. if (ctx.cert) {
  8970. time_t not_before = 0, not_after = 0;
  8971. bool result = ctx.validity(not_before, not_after);
  8972. EXPECT_TRUE(result);
  8973. // Verify that not_before < now < not_after for a valid cert
  8974. time_t now = time(nullptr);
  8975. EXPECT_LT(not_before, now);
  8976. EXPECT_GT(not_after, now);
  8977. validity_checked = true;
  8978. }
  8979. return true;
  8980. });
  8981. auto res = cli.Get("/test");
  8982. ASSERT_TRUE(res);
  8983. EXPECT_TRUE(validity_checked);
  8984. }
  8985. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8986. using namespace httplib::tls;
  8987. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8988. ASSERT_TRUE(svr.is_valid());
  8989. svr.Get("/test", [](const Request &, Response &res) {
  8990. res.set_content("ok", "text/plain");
  8991. });
  8992. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8993. auto se = detail::scope_exit([&] {
  8994. svr.stop();
  8995. t.join();
  8996. });
  8997. svr.wait_until_ready();
  8998. SSLClient cli(HOST, PORT);
  8999. cli.enable_server_certificate_verification(false);
  9000. cli.set_connection_timeout(30);
  9001. bool serial_checked = false;
  9002. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9003. if (ctx.cert) {
  9004. std::string serial = ctx.serial();
  9005. EXPECT_FALSE(serial.empty());
  9006. // Serial should be a hex string
  9007. for (char c : serial) {
  9008. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9009. (c >= 'a' && c <= 'f'));
  9010. }
  9011. serial_checked = true;
  9012. }
  9013. return true;
  9014. });
  9015. auto res = cli.Get("/test");
  9016. ASSERT_TRUE(res);
  9017. EXPECT_TRUE(serial_checked);
  9018. }
  9019. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9020. // Test 1: Valid CA file - no error should be recorded
  9021. {
  9022. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9023. CLIENT_CA_CERT_FILE);
  9024. ASSERT_TRUE(svr.is_valid());
  9025. // With valid setup, last_ssl_error should be 0
  9026. EXPECT_EQ(0, svr.ssl_last_error());
  9027. }
  9028. // Test 2: Invalid CA file content
  9029. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9030. {
  9031. // Create a temporary file with completely invalid content
  9032. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9033. {
  9034. std::ofstream ofs(temp_invalid_ca);
  9035. ofs << "This is not a certificate file at all\n";
  9036. ofs << "Just plain text content\n";
  9037. }
  9038. // Create server with invalid CA file
  9039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9040. // Clean up temporary file
  9041. std::remove(temp_invalid_ca);
  9042. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9043. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9044. // Note: SSL_CTX_load_verify_locations typically fails first,
  9045. // but our error handling code path is still exercised
  9046. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9047. }
  9048. }
  9049. TEST(VerifyCallbackTest, VerifyContextFields) {
  9050. using namespace httplib::tls;
  9051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9052. ASSERT_TRUE(svr.is_valid());
  9053. svr.Get("/test", [](const Request &, Response &res) {
  9054. res.set_content("ok", "text/plain");
  9055. });
  9056. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9057. auto se = detail::scope_exit([&] {
  9058. svr.stop();
  9059. t.join();
  9060. });
  9061. svr.wait_until_ready();
  9062. SSLClient cli(HOST, PORT);
  9063. cli.enable_server_certificate_verification(false);
  9064. cli.set_connection_timeout(30);
  9065. int callback_count = 0;
  9066. bool saw_leaf_cert = false;
  9067. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9068. if (ctx.cert) {
  9069. callback_count++;
  9070. // We should see at least one certificate (the leaf)
  9071. std::string cn = ctx.subject_cn();
  9072. if (!cn.empty()) { saw_leaf_cert = true; }
  9073. // Verify context fields are populated
  9074. EXPECT_NE(ctx.session, nullptr);
  9075. EXPECT_GE(ctx.depth, 0);
  9076. }
  9077. return true;
  9078. });
  9079. auto res = cli.Get("/test");
  9080. ASSERT_TRUE(res);
  9081. EXPECT_GT(callback_count, 0);
  9082. EXPECT_TRUE(saw_leaf_cert);
  9083. }
  9084. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9085. using httplib::tls::TlsError;
  9086. // Test that verify_error_to_string returns empty for success
  9087. std::string success_str = TlsError::verify_error_to_string(0);
  9088. EXPECT_TRUE(success_str.empty());
  9089. // Test that verify_error_to_string returns non-empty for error codes
  9090. // Using a common error code (certificate expired)
  9091. std::string error_str =
  9092. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9093. EXPECT_FALSE(error_str.empty());
  9094. }
  9095. TEST(SessionVerifierTest, CertificateAccepted) {
  9096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9097. ASSERT_TRUE(svr.is_valid());
  9098. svr.Get("/test", [](const Request &, Response &res) {
  9099. res.set_content("ok", "text/plain");
  9100. });
  9101. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9102. auto se = detail::scope_exit([&] {
  9103. svr.stop();
  9104. t.join();
  9105. });
  9106. svr.wait_until_ready();
  9107. SSLClient cli(HOST, PORT);
  9108. cli.enable_server_certificate_verification(false);
  9109. cli.set_connection_timeout(30);
  9110. bool callback_called = false;
  9111. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9112. EXPECT_NE(session, nullptr);
  9113. callback_called = true;
  9114. return SSLVerifierResponse::CertificateAccepted;
  9115. });
  9116. auto res = cli.Get("/test");
  9117. ASSERT_TRUE(res);
  9118. EXPECT_EQ(200, res->status);
  9119. EXPECT_TRUE(callback_called);
  9120. }
  9121. TEST(SessionVerifierTest, CertificateRejected) {
  9122. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9123. ASSERT_TRUE(svr.is_valid());
  9124. svr.Get("/test", [](const Request &, Response &res) {
  9125. res.set_content("ok", "text/plain");
  9126. });
  9127. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9128. auto se = detail::scope_exit([&] {
  9129. svr.stop();
  9130. t.join();
  9131. });
  9132. svr.wait_until_ready();
  9133. SSLClient cli(HOST, PORT);
  9134. cli.enable_server_certificate_verification(false);
  9135. cli.set_connection_timeout(30);
  9136. bool callback_called = false;
  9137. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9138. EXPECT_NE(session, nullptr);
  9139. callback_called = true;
  9140. return SSLVerifierResponse::CertificateRejected;
  9141. });
  9142. auto res = cli.Get("/test");
  9143. EXPECT_FALSE(res);
  9144. EXPECT_TRUE(callback_called);
  9145. }
  9146. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9147. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9148. ASSERT_TRUE(svr.is_valid());
  9149. svr.Get("/test", [](const Request &, Response &res) {
  9150. res.set_content("ok", "text/plain");
  9151. });
  9152. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9153. auto se = detail::scope_exit([&] {
  9154. svr.stop();
  9155. t.join();
  9156. });
  9157. svr.wait_until_ready();
  9158. // NoDecisionMade with verification disabled should succeed (no default check)
  9159. SSLClient cli(HOST, PORT);
  9160. cli.enable_server_certificate_verification(false);
  9161. cli.set_connection_timeout(30);
  9162. bool callback_called = false;
  9163. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9164. EXPECT_NE(session, nullptr);
  9165. callback_called = true;
  9166. return SSLVerifierResponse::NoDecisionMade;
  9167. });
  9168. auto res = cli.Get("/test");
  9169. ASSERT_TRUE(res);
  9170. EXPECT_EQ(200, res->status);
  9171. EXPECT_TRUE(callback_called);
  9172. }
  9173. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9175. ASSERT_TRUE(svr.is_valid());
  9176. svr.Get("/test", [](const Request &, Response &res) {
  9177. res.set_content("ok", "text/plain");
  9178. });
  9179. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9180. auto se = detail::scope_exit([&] {
  9181. svr.stop();
  9182. t.join();
  9183. });
  9184. svr.wait_until_ready();
  9185. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9186. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9187. // so we only check that the request fails, not whether the callback was
  9188. // called.
  9189. SSLClient cli(HOST, PORT);
  9190. cli.enable_server_certificate_verification(true);
  9191. cli.set_connection_timeout(30);
  9192. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9193. EXPECT_NE(session, nullptr);
  9194. return SSLVerifierResponse::NoDecisionMade;
  9195. });
  9196. auto res = cli.Get("/test");
  9197. EXPECT_FALSE(res);
  9198. }
  9199. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9200. // Test SSL server using PemMemory constructor with client CA certificates
  9201. // Read PEM files
  9202. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9203. read_file(SERVER_CERT_FILE, server_cert_pem);
  9204. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9205. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9206. // Create SSLServer with PemMemory constructor including client CA
  9207. SSLServer::PemMemory server_pem = {
  9208. server_cert_pem.c_str(),
  9209. server_cert_pem.size(),
  9210. server_key_pem.c_str(),
  9211. server_key_pem.size(),
  9212. client_ca_pem.c_str(),
  9213. client_ca_pem.size(),
  9214. nullptr // no password for server key
  9215. };
  9216. SSLServer svr(server_pem);
  9217. ASSERT_TRUE(svr.is_valid());
  9218. // No SSL error should be recorded for valid setup
  9219. EXPECT_EQ(0, svr.ssl_last_error());
  9220. // Set up server endpoints
  9221. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9222. res.set_content("ok", "text/plain");
  9223. });
  9224. // Start server in a thread
  9225. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9226. svr.wait_until_ready();
  9227. // Connect with client certificate (using constructor with paths)
  9228. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9229. cli.enable_server_certificate_verification(false);
  9230. auto res = cli.Get("/test-pem-ca");
  9231. ASSERT_TRUE(res);
  9232. EXPECT_EQ(200, res->status);
  9233. EXPECT_EQ("ok", res->body);
  9234. svr.stop();
  9235. server_thread.join();
  9236. }
  9237. #endif
  9238. #ifdef _WIN32
  9239. TEST(CleanupTest, WSACleanup) {
  9240. int ret = WSACleanup();
  9241. ASSERT_EQ(0, ret);
  9242. }
  9243. #endif
  9244. #ifndef CPPHTTPLIB_SSL_ENABLED
  9245. TEST(NoSSLSupport, SimpleInterface) {
  9246. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9247. }
  9248. #endif
  9249. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9250. TEST(InvalidScheme, SimpleInterface) {
  9251. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9252. }
  9253. #endif
  9254. TEST(NoScheme, SimpleInterface) {
  9255. Client cli("yahoo.com:80");
  9256. ASSERT_TRUE(cli.is_valid());
  9257. }
  9258. TEST(SendAPI, SimpleInterface_Online) {
  9259. Client cli("http://yahoo.com");
  9260. Request req;
  9261. req.method = "GET";
  9262. req.path = "/";
  9263. auto res = cli.send(req);
  9264. ASSERT_TRUE(res);
  9265. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9266. }
  9267. TEST(SendAPI, WithParamsInRequest) {
  9268. Server svr;
  9269. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9270. EXPECT_TRUE(req.has_param("test"));
  9271. EXPECT_EQ("test_value", req.get_param_value("test"));
  9272. });
  9273. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9274. auto se = detail::scope_exit([&] {
  9275. svr.stop();
  9276. t.join();
  9277. ASSERT_FALSE(svr.is_running());
  9278. });
  9279. svr.wait_until_ready();
  9280. Client cli(HOST, PORT);
  9281. {
  9282. Request req;
  9283. req.method = "GET";
  9284. req.path = "/";
  9285. req.params.emplace("test", "test_value");
  9286. auto res = cli.send(req);
  9287. ASSERT_TRUE(res);
  9288. }
  9289. {
  9290. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9291. ASSERT_TRUE(res);
  9292. }
  9293. }
  9294. TEST(ClientImplMethods, GetSocketTest) {
  9295. httplib::Server svr;
  9296. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9297. res.status = StatusCode::OK_200;
  9298. });
  9299. auto port = svr.bind_to_any_port("127.0.0.1");
  9300. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9301. auto se = detail::scope_exit([&] {
  9302. svr.stop();
  9303. thread.join();
  9304. ASSERT_FALSE(svr.is_running());
  9305. });
  9306. svr.wait_until_ready();
  9307. {
  9308. httplib::Client cli("127.0.0.1", port);
  9309. cli.set_keep_alive(true);
  9310. // Use the behavior of cpp-httplib of opening the connection
  9311. // only when the first request happens. If that changes,
  9312. // this test would be obsolete.
  9313. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9314. // This also implicitly tests the server. But other tests would fail much
  9315. // earlier than this one to be considered.
  9316. auto res = cli.Get("/");
  9317. ASSERT_TRUE(res);
  9318. EXPECT_EQ(StatusCode::OK_200, res->status);
  9319. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9320. }
  9321. }
  9322. #ifdef CPPHTTPLIB_SSL_ENABLED
  9323. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9324. Client cli("http://yahoo.com");
  9325. auto res = cli.Get("/");
  9326. ASSERT_TRUE(res);
  9327. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9328. cli.set_follow_location(true);
  9329. res = cli.Get("/");
  9330. ASSERT_TRUE(res);
  9331. EXPECT_EQ(StatusCode::OK_200, res->status);
  9332. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9333. }
  9334. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9335. Client cli("https://yahoo.com");
  9336. auto res = cli.Get("/");
  9337. ASSERT_TRUE(res);
  9338. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9339. cli.set_follow_location(true);
  9340. res = cli.Get("/");
  9341. ASSERT_TRUE(res);
  9342. EXPECT_EQ(StatusCode::OK_200, res->status);
  9343. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9344. }
  9345. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9346. Client cli("https://yahoo.com");
  9347. auto res = cli.Get("/");
  9348. ASSERT_TRUE(res);
  9349. ASSERT_FALSE(!res);
  9350. ASSERT_TRUE(res);
  9351. ASSERT_FALSE(res == nullptr);
  9352. ASSERT_TRUE(res != nullptr);
  9353. EXPECT_EQ(Error::Success, res.error());
  9354. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9355. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9356. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9357. cli.set_follow_location(true);
  9358. res = cli.Get("/");
  9359. ASSERT_TRUE(res);
  9360. EXPECT_EQ(Error::Success, res.error());
  9361. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9362. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9363. EXPECT_EQ(StatusCode::OK_200, res->status);
  9364. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9365. }
  9366. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9367. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9368. Client cli("https://cdnjs.cloudflare.com");
  9369. auto res =
  9370. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9371. ASSERT_TRUE(res);
  9372. EXPECT_EQ(StatusCode::OK_200, res->status);
  9373. EXPECT_EQ(287630U, res->body.size());
  9374. EXPECT_EQ("application/javascript; charset=utf-8",
  9375. res->get_header_value("Content-Type"));
  9376. }
  9377. #endif
  9378. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9379. #undef REDIR_HOST // Silence compiler warning
  9380. #define REDIR_HOST "https://httpbingo.org"
  9381. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9382. Client cli(REDIR_HOST);
  9383. cli.set_follow_location(true);
  9384. auto res =
  9385. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9386. ASSERT_TRUE(res);
  9387. EXPECT_EQ(StatusCode::OK_200, res->status);
  9388. }
  9389. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9390. Client cli(REDIR_HOST);
  9391. cli.set_follow_location(true);
  9392. Params params;
  9393. params.emplace("url", "http://example.com");
  9394. params.emplace("status_code", "302");
  9395. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9396. ASSERT_TRUE(res);
  9397. EXPECT_EQ(StatusCode::OK_200, res->status);
  9398. }
  9399. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9400. Client cli(REDIR_HOST);
  9401. cli.set_follow_location(true);
  9402. Params params;
  9403. params.emplace("url", "http://example.com");
  9404. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9405. ASSERT_TRUE(res);
  9406. EXPECT_EQ(StatusCode::OK_200, res->status);
  9407. }
  9408. TEST(HttpToHttpsRedirectTest, CertFile) {
  9409. auto ssl_port = PORT + 1;
  9410. Server svr;
  9411. ASSERT_TRUE(svr.is_valid());
  9412. svr.Get("/index", [&](const Request &, Response &res) {
  9413. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9414. "/index");
  9415. svr.stop();
  9416. });
  9417. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9418. ASSERT_TRUE(ssl_svr.is_valid());
  9419. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9420. res.set_content("test", "text/plain");
  9421. ssl_svr.stop();
  9422. });
  9423. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9424. thread t2 =
  9425. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9426. auto se = detail::scope_exit([&] {
  9427. t2.join();
  9428. t.join();
  9429. ASSERT_FALSE(svr.is_running());
  9430. });
  9431. svr.wait_until_ready();
  9432. ssl_svr.wait_until_ready();
  9433. Client cli("127.0.0.1", PORT);
  9434. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9435. cli.enable_server_certificate_verification(true);
  9436. cli.set_follow_location(true);
  9437. cli.set_connection_timeout(30);
  9438. auto res = cli.Get("/index");
  9439. ASSERT_TRUE(res);
  9440. ASSERT_EQ(StatusCode::OK_200, res->status);
  9441. }
  9442. TEST(SSLClientRedirectTest, CertFile) {
  9443. auto ssl_port = PORT + 1;
  9444. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9445. ASSERT_TRUE(ssl_svr1.is_valid());
  9446. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9447. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9448. "/index");
  9449. ssl_svr1.stop();
  9450. });
  9451. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9452. ASSERT_TRUE(ssl_svr2.is_valid());
  9453. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9454. res.set_content("test", "text/plain");
  9455. ssl_svr2.stop();
  9456. });
  9457. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9458. thread t2 =
  9459. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9460. auto se = detail::scope_exit([&] {
  9461. t2.join();
  9462. t.join();
  9463. ASSERT_FALSE(ssl_svr1.is_running());
  9464. });
  9465. ssl_svr1.wait_until_ready();
  9466. ssl_svr2.wait_until_ready();
  9467. SSLClient cli("127.0.0.1", PORT);
  9468. std::string cert;
  9469. read_file(SERVER_CERT2_FILE, cert);
  9470. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9471. cli.enable_server_certificate_verification(true);
  9472. cli.set_follow_location(true);
  9473. cli.set_connection_timeout(30);
  9474. auto res = cli.Get("/index");
  9475. ASSERT_TRUE(res);
  9476. ASSERT_EQ(StatusCode::OK_200, res->status);
  9477. }
  9478. #endif
  9479. #ifdef CPPHTTPLIB_SSL_ENABLED
  9480. // Test that set_ca_cert_store() skips system certs (consistent with
  9481. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9482. // should be trusted - system certs should NOT be loaded.
  9483. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9484. // Load a specific cert that is NOT a system CA cert
  9485. std::string cert;
  9486. read_file(SERVER_CERT2_FILE, cert);
  9487. SSLClient cli("google.com");
  9488. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9489. cli.enable_server_certificate_verification(true);
  9490. // This should FAIL because:
  9491. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9492. // 2. System certs should NOT be loaded when custom store is set
  9493. // If system certs WERE loaded, this would succeed
  9494. auto res = cli.Get("/");
  9495. ASSERT_FALSE(res);
  9496. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9497. }
  9498. TEST(MultipartFormDataTest, LargeData) {
  9499. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9500. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9501. const ContentReader &content_reader) {
  9502. if (req.is_multipart_form_data()) {
  9503. std::vector<FormData> items;
  9504. content_reader(
  9505. [&](const FormData &file) {
  9506. items.push_back(file);
  9507. return true;
  9508. },
  9509. [&](const char *data, size_t data_length) {
  9510. items.back().content.append(data, data_length);
  9511. return true;
  9512. });
  9513. EXPECT_TRUE(std::string(items[0].name) == "document");
  9514. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9515. EXPECT_TRUE(items[0].filename == "2MB_data");
  9516. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9517. EXPECT_TRUE(items[1].name == "hello");
  9518. EXPECT_TRUE(items[1].content == "world");
  9519. EXPECT_TRUE(items[1].filename == "");
  9520. EXPECT_TRUE(items[1].content_type == "");
  9521. } else {
  9522. std::string body;
  9523. content_reader([&](const char *data, size_t data_length) {
  9524. body.append(data, data_length);
  9525. return true;
  9526. });
  9527. }
  9528. });
  9529. auto port = svr.bind_to_any_port(HOST);
  9530. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9531. auto se = detail::scope_exit([&] {
  9532. svr.stop();
  9533. t.join();
  9534. ASSERT_FALSE(svr.is_running());
  9535. });
  9536. svr.wait_until_ready();
  9537. {
  9538. std::string data(1024 * 1024 * 2, '.');
  9539. std::stringstream buffer;
  9540. buffer << data;
  9541. SSLClient cli(HOST, port);
  9542. cli.enable_server_certificate_verification(false);
  9543. UploadFormDataItems items{
  9544. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9545. {"hello", "world", "", ""},
  9546. };
  9547. auto res = cli.Post("/post", items);
  9548. ASSERT_TRUE(res);
  9549. ASSERT_EQ(StatusCode::OK_200, res->status);
  9550. }
  9551. }
  9552. TEST(MultipartFormDataTest, DataProviderItems) {
  9553. std::random_device seed_gen;
  9554. std::mt19937 random(seed_gen());
  9555. std::string rand1;
  9556. rand1.resize(1000);
  9557. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9558. std::string rand2;
  9559. rand2.resize(3000);
  9560. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9562. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9563. const ContentReader &content_reader) {
  9564. ASSERT_FALSE(req.is_multipart_form_data());
  9565. std::string body;
  9566. content_reader([&](const char *data, size_t data_length) {
  9567. body.append(data, data_length);
  9568. return true;
  9569. });
  9570. EXPECT_EQ(body, "");
  9571. });
  9572. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9573. const ContentReader &content_reader) {
  9574. ASSERT_TRUE(req.is_multipart_form_data());
  9575. std::vector<FormData> items;
  9576. content_reader(
  9577. [&](const FormData &file) {
  9578. items.push_back(file);
  9579. return true;
  9580. },
  9581. [&](const char *data, size_t data_length) {
  9582. items.back().content.append(data, data_length);
  9583. return true;
  9584. });
  9585. ASSERT_TRUE(items.size() == 2);
  9586. EXPECT_EQ(std::string(items[0].name), "name1");
  9587. EXPECT_EQ(items[0].content, "Testing123");
  9588. EXPECT_EQ(items[0].filename, "filename1");
  9589. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9590. EXPECT_EQ(items[1].name, "name2");
  9591. EXPECT_EQ(items[1].content, "Testing456");
  9592. EXPECT_EQ(items[1].filename, "");
  9593. EXPECT_EQ(items[1].content_type, "");
  9594. });
  9595. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9596. const ContentReader &content_reader) {
  9597. ASSERT_TRUE(req.is_multipart_form_data());
  9598. std::vector<FormData> items;
  9599. content_reader(
  9600. [&](const FormData &file) {
  9601. items.push_back(file);
  9602. return true;
  9603. },
  9604. [&](const char *data, size_t data_length) {
  9605. items.back().content.append(data, data_length);
  9606. return true;
  9607. });
  9608. ASSERT_TRUE(items.size() == 2);
  9609. EXPECT_EQ(items[0].name, "name3");
  9610. EXPECT_EQ(items[0].content, rand1);
  9611. EXPECT_EQ(items[0].filename, "filename3");
  9612. EXPECT_EQ(items[0].content_type, "");
  9613. EXPECT_EQ(items[1].name, "name4");
  9614. EXPECT_EQ(items[1].content, rand2);
  9615. EXPECT_EQ(items[1].filename, "filename4");
  9616. EXPECT_EQ(items[1].content_type, "");
  9617. });
  9618. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9619. const ContentReader &content_reader) {
  9620. ASSERT_TRUE(req.is_multipart_form_data());
  9621. std::vector<FormData> items;
  9622. content_reader(
  9623. [&](const FormData &file) {
  9624. items.push_back(file);
  9625. return true;
  9626. },
  9627. [&](const char *data, size_t data_length) {
  9628. items.back().content.append(data, data_length);
  9629. return true;
  9630. });
  9631. ASSERT_TRUE(items.size() == 4);
  9632. EXPECT_EQ(std::string(items[0].name), "name1");
  9633. EXPECT_EQ(items[0].content, "Testing123");
  9634. EXPECT_EQ(items[0].filename, "filename1");
  9635. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9636. EXPECT_EQ(items[1].name, "name2");
  9637. EXPECT_EQ(items[1].content, "Testing456");
  9638. EXPECT_EQ(items[1].filename, "");
  9639. EXPECT_EQ(items[1].content_type, "");
  9640. EXPECT_EQ(items[2].name, "name3");
  9641. EXPECT_EQ(items[2].content, rand1);
  9642. EXPECT_EQ(items[2].filename, "filename3");
  9643. EXPECT_EQ(items[2].content_type, "");
  9644. EXPECT_EQ(items[3].name, "name4");
  9645. EXPECT_EQ(items[3].content, rand2);
  9646. EXPECT_EQ(items[3].filename, "filename4");
  9647. EXPECT_EQ(items[3].content_type, "");
  9648. });
  9649. auto port = svr.bind_to_any_port("localhost");
  9650. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9651. auto se = detail::scope_exit([&] {
  9652. svr.stop();
  9653. t.join();
  9654. ASSERT_FALSE(svr.is_running());
  9655. });
  9656. svr.wait_until_ready();
  9657. {
  9658. SSLClient cli("localhost", port);
  9659. cli.enable_server_certificate_verification(false);
  9660. UploadFormDataItems items{
  9661. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9662. {"name2", "Testing456", "", ""}, // not a file
  9663. };
  9664. {
  9665. auto res = cli.Post("/post-none", {}, {}, {});
  9666. ASSERT_TRUE(res);
  9667. ASSERT_EQ(StatusCode::OK_200, res->status);
  9668. }
  9669. FormDataProviderItems providers;
  9670. {
  9671. auto res =
  9672. cli.Post("/post-items", {}, items, providers); // empty providers
  9673. ASSERT_TRUE(res);
  9674. ASSERT_EQ(StatusCode::OK_200, res->status);
  9675. }
  9676. providers.push_back({"name3",
  9677. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9678. // test the offset is given correctly at each step
  9679. if (!offset)
  9680. sink.os.write(rand1.data(), 30);
  9681. else if (offset == 30)
  9682. sink.os.write(rand1.data() + 30, 300);
  9683. else if (offset == 330)
  9684. sink.os.write(rand1.data() + 330, 670);
  9685. else if (offset == rand1.size())
  9686. sink.done();
  9687. return true;
  9688. },
  9689. "filename3",
  9690. {}});
  9691. providers.push_back({"name4",
  9692. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9693. // test the offset is given correctly at each step
  9694. if (!offset)
  9695. sink.os.write(rand2.data(), 2000);
  9696. else if (offset == 2000)
  9697. sink.os.write(rand2.data() + 2000, 1);
  9698. else if (offset == 2001)
  9699. sink.os.write(rand2.data() + 2001, 999);
  9700. else if (offset == rand2.size())
  9701. sink.done();
  9702. return true;
  9703. },
  9704. "filename4",
  9705. {}});
  9706. {
  9707. auto res = cli.Post("/post-providers", {}, {}, providers);
  9708. ASSERT_TRUE(res);
  9709. ASSERT_EQ(StatusCode::OK_200, res->status);
  9710. }
  9711. {
  9712. auto res = cli.Post("/post-both", {}, items, providers);
  9713. ASSERT_TRUE(res);
  9714. ASSERT_EQ(StatusCode::OK_200, res->status);
  9715. }
  9716. }
  9717. }
  9718. TEST(MultipartFormDataTest, BadHeader) {
  9719. Server svr;
  9720. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9721. res.set_content("ok", "text/plain");
  9722. });
  9723. thread t = thread([&] { svr.listen(HOST, PORT); });
  9724. auto se = detail::scope_exit([&] {
  9725. svr.stop();
  9726. t.join();
  9727. ASSERT_FALSE(svr.is_running());
  9728. });
  9729. svr.wait_until_ready();
  9730. const std::string body =
  9731. "This is the preamble. It is to be ignored, though it\r\n"
  9732. "is a handy place for composition agents to include an\r\n"
  9733. "explanatory note to non-MIME conformant readers.\r\n"
  9734. "\r\n"
  9735. "\r\n"
  9736. "--simple boundary\r\n"
  9737. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9738. ": BAD...\r\n"
  9739. "\r\n"
  9740. "value1\r\n"
  9741. "--simple boundary\r\n"
  9742. "Content-Disposition: form-data; name=\"field2\"; "
  9743. "filename=\"example.txt\"\r\n"
  9744. "\r\n"
  9745. "value2\r\n"
  9746. "--simple boundary--\r\n"
  9747. "This is the epilogue. It is also to be ignored.\r\n";
  9748. std::string content_type =
  9749. R"(multipart/form-data; boundary="simple boundary")";
  9750. Client cli(HOST, PORT);
  9751. auto res = cli.Post("/post", body, content_type.c_str());
  9752. ASSERT_TRUE(res);
  9753. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9754. }
  9755. TEST(MultipartFormDataTest, WithPreamble) {
  9756. Server svr;
  9757. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9758. res.set_content("ok", "text/plain");
  9759. });
  9760. thread t = thread([&] { svr.listen(HOST, PORT); });
  9761. auto se = detail::scope_exit([&] {
  9762. svr.stop();
  9763. t.join();
  9764. ASSERT_FALSE(svr.is_running());
  9765. });
  9766. svr.wait_until_ready();
  9767. const std::string body =
  9768. "This is the preamble. It is to be ignored, though it\r\n"
  9769. "is a handy place for composition agents to include an\r\n"
  9770. "explanatory note to non-MIME conformant readers.\r\n"
  9771. "\r\n"
  9772. "\r\n"
  9773. "--simple boundary\r\n"
  9774. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9775. "\r\n"
  9776. "value1\r\n"
  9777. "--simple boundary\r\n"
  9778. "Content-Disposition: form-data; name=\"field2\"; "
  9779. "filename=\"example.txt\"\r\n"
  9780. "\r\n"
  9781. "value2\r\n"
  9782. "--simple boundary--\r\n"
  9783. "This is the epilogue. It is also to be ignored.\r\n";
  9784. std::string content_type =
  9785. R"(multipart/form-data; boundary="simple boundary")";
  9786. Client cli(HOST, PORT);
  9787. auto res = cli.Post("/post", body, content_type.c_str());
  9788. ASSERT_TRUE(res);
  9789. EXPECT_EQ(StatusCode::OK_200, res->status);
  9790. }
  9791. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9792. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9793. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9794. const ContentReader &content_reader) {
  9795. if (req.is_multipart_form_data()) {
  9796. std::vector<FormData> items;
  9797. content_reader(
  9798. [&](const FormData &file) {
  9799. items.push_back(file);
  9800. return true;
  9801. },
  9802. [&](const char *data, size_t data_length) {
  9803. items.back().content.append(data, data_length);
  9804. return true;
  9805. });
  9806. EXPECT_TRUE(std::string(items[0].name) == "document");
  9807. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9808. EXPECT_TRUE(items[0].filename == "2MB_data");
  9809. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9810. EXPECT_TRUE(items[1].name == "hello");
  9811. EXPECT_TRUE(items[1].content == "world");
  9812. EXPECT_TRUE(items[1].filename == "");
  9813. EXPECT_TRUE(items[1].content_type == "");
  9814. } else {
  9815. std::string body;
  9816. content_reader([&](const char *data, size_t data_length) {
  9817. body.append(data, data_length);
  9818. return true;
  9819. });
  9820. }
  9821. });
  9822. auto port = svr.bind_to_any_port("localhost");
  9823. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9824. auto se = detail::scope_exit([&] {
  9825. svr.stop();
  9826. t.join();
  9827. ASSERT_FALSE(svr.is_running());
  9828. });
  9829. svr.wait_until_ready();
  9830. {
  9831. std::string data(1024 * 1024 * 2, '.');
  9832. std::stringstream buffer;
  9833. buffer << data;
  9834. SSLClient cli("localhost", port);
  9835. cli.enable_server_certificate_verification(false);
  9836. UploadFormDataItems items{
  9837. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9838. {"hello", "world", "", ""},
  9839. };
  9840. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9841. ASSERT_TRUE(res);
  9842. ASSERT_EQ(StatusCode::OK_200, res->status);
  9843. }
  9844. }
  9845. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9846. std::string data(1024 * 1024 * 2, '&');
  9847. std::stringstream buffer;
  9848. buffer << data;
  9849. Client cli("https://localhost:8080");
  9850. UploadFormDataItems items{
  9851. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9852. {"hello", "world", "", ""},
  9853. };
  9854. for (const char &c : " \t\r\n") {
  9855. auto res =
  9856. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9857. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9858. ASSERT_FALSE(res);
  9859. }
  9860. }
  9861. TEST(MultipartFormDataTest, PutFormData) {
  9862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9863. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9864. const ContentReader &content_reader) {
  9865. if (req.is_multipart_form_data()) {
  9866. std::vector<FormData> items;
  9867. content_reader(
  9868. [&](const FormData &file) {
  9869. items.push_back(file);
  9870. return true;
  9871. },
  9872. [&](const char *data, size_t data_length) {
  9873. items.back().content.append(data, data_length);
  9874. return true;
  9875. });
  9876. EXPECT_TRUE(std::string(items[0].name) == "document");
  9877. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9878. EXPECT_TRUE(items[0].filename == "2MB_data");
  9879. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9880. EXPECT_TRUE(items[1].name == "hello");
  9881. EXPECT_TRUE(items[1].content == "world");
  9882. EXPECT_TRUE(items[1].filename == "");
  9883. EXPECT_TRUE(items[1].content_type == "");
  9884. } else {
  9885. std::string body;
  9886. content_reader([&](const char *data, size_t data_length) {
  9887. body.append(data, data_length);
  9888. return true;
  9889. });
  9890. }
  9891. });
  9892. auto port = svr.bind_to_any_port("localhost");
  9893. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9894. auto se = detail::scope_exit([&] {
  9895. svr.stop();
  9896. t.join();
  9897. ASSERT_FALSE(svr.is_running());
  9898. });
  9899. svr.wait_until_ready();
  9900. {
  9901. std::string data(1024 * 1024 * 2, '&');
  9902. std::stringstream buffer;
  9903. buffer << data;
  9904. SSLClient cli("localhost", port);
  9905. cli.enable_server_certificate_verification(false);
  9906. UploadFormDataItems items{
  9907. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9908. {"hello", "world", "", ""},
  9909. };
  9910. auto res = cli.Put("/put", items);
  9911. ASSERT_TRUE(res);
  9912. ASSERT_EQ(StatusCode::OK_200, res->status);
  9913. }
  9914. }
  9915. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9917. svr.Put("/put_customboundary",
  9918. [&](const Request &req, const Response & /*res*/,
  9919. const ContentReader &content_reader) {
  9920. if (req.is_multipart_form_data()) {
  9921. std::vector<FormData> items;
  9922. content_reader(
  9923. [&](const FormData &file) {
  9924. items.push_back(file);
  9925. return true;
  9926. },
  9927. [&](const char *data, size_t data_length) {
  9928. items.back().content.append(data, data_length);
  9929. return true;
  9930. });
  9931. EXPECT_TRUE(std::string(items[0].name) == "document");
  9932. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9933. EXPECT_TRUE(items[0].filename == "2MB_data");
  9934. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9935. EXPECT_TRUE(items[1].name == "hello");
  9936. EXPECT_TRUE(items[1].content == "world");
  9937. EXPECT_TRUE(items[1].filename == "");
  9938. EXPECT_TRUE(items[1].content_type == "");
  9939. } else {
  9940. std::string body;
  9941. content_reader([&](const char *data, size_t data_length) {
  9942. body.append(data, data_length);
  9943. return true;
  9944. });
  9945. }
  9946. });
  9947. auto port = svr.bind_to_any_port("localhost");
  9948. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9949. auto se = detail::scope_exit([&] {
  9950. svr.stop();
  9951. t.join();
  9952. ASSERT_FALSE(svr.is_running());
  9953. });
  9954. svr.wait_until_ready();
  9955. {
  9956. std::string data(1024 * 1024 * 2, '&');
  9957. std::stringstream buffer;
  9958. buffer << data;
  9959. SSLClient cli("localhost", port);
  9960. cli.enable_server_certificate_verification(false);
  9961. UploadFormDataItems items{
  9962. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9963. {"hello", "world", "", ""},
  9964. };
  9965. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9966. ASSERT_TRUE(res);
  9967. ASSERT_EQ(StatusCode::OK_200, res->status);
  9968. }
  9969. }
  9970. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9971. std::string data(1024 * 1024 * 2, '&');
  9972. std::stringstream buffer;
  9973. buffer << data;
  9974. Client cli("https://localhost:8080");
  9975. cli.enable_server_certificate_verification(false);
  9976. UploadFormDataItems items{
  9977. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9978. {"hello", "world", "", ""},
  9979. };
  9980. for (const char &c : " \t\r\n") {
  9981. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9982. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9983. ASSERT_FALSE(res);
  9984. }
  9985. }
  9986. TEST(MultipartFormDataTest, AlternateFilename) {
  9987. auto handled = false;
  9988. Server svr;
  9989. svr.Post("/test", [&](const Request &req, Response &res) {
  9990. ASSERT_EQ(2u, req.form.files.size());
  9991. ASSERT_EQ(1u, req.form.fields.size());
  9992. // Test files
  9993. const auto &file1 = req.form.get_file("file1");
  9994. ASSERT_EQ("file1", file1.name);
  9995. ASSERT_EQ("A.txt", file1.filename);
  9996. ASSERT_EQ("text/plain", file1.content_type);
  9997. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9998. const auto &file2 = req.form.get_file("file2");
  9999. ASSERT_EQ("file2", file2.name);
  10000. ASSERT_EQ("a.html", file2.filename);
  10001. ASSERT_EQ("text/html", file2.content_type);
  10002. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10003. file2.content);
  10004. // Test text field
  10005. const auto &text = req.form.get_field("text");
  10006. ASSERT_EQ("text default", text);
  10007. res.set_content("ok", "text/plain");
  10008. handled = true;
  10009. });
  10010. thread t = thread([&] { svr.listen(HOST, PORT); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. t.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. ASSERT_TRUE(handled);
  10016. });
  10017. svr.wait_until_ready();
  10018. auto req = "POST /test HTTP/1.1\r\n"
  10019. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10020. "Content-Length: 399\r\n"
  10021. "\r\n"
  10022. "----------\r\n"
  10023. "Content-Disposition: form-data; name=\"text\"\r\n"
  10024. "\r\n"
  10025. "text default\r\n"
  10026. "----------\r\n"
  10027. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10028. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10029. "Content-Type: text/plain\r\n"
  10030. "\r\n"
  10031. "Content of a.txt.\r\n"
  10032. "\r\n"
  10033. "----------\r\n"
  10034. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10035. "\"a.html\"\r\n"
  10036. "Content-Type: text/html\r\n"
  10037. "\r\n"
  10038. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10039. "\r\n"
  10040. "------------\r\n";
  10041. ASSERT_TRUE(send_request(1, req));
  10042. }
  10043. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10044. auto handled = false;
  10045. Server svr;
  10046. svr.Post("/test", [&](const Request &req, Response &res) {
  10047. // Case-insensitive "utf-8''" prefix with a long value
  10048. const auto &file = req.form.get_file("file1");
  10049. ASSERT_EQ("file1", file.name);
  10050. // 8000 chars exercises both the Content-Disposition parser and the
  10051. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10052. // Prior to the fix, std::regex_match on this header would cause O(N)
  10053. // stack recursion in libstdc++, leading to SIGSEGV.
  10054. std::string expected_filename(8000, 'A');
  10055. ASSERT_EQ(expected_filename, file.filename);
  10056. res.set_content("ok", "text/plain");
  10057. handled = true;
  10058. });
  10059. thread t = thread([&] { svr.listen(HOST, PORT); });
  10060. auto se = detail::scope_exit([&] {
  10061. svr.stop();
  10062. t.join();
  10063. ASSERT_FALSE(svr.is_running());
  10064. ASSERT_TRUE(handled);
  10065. });
  10066. svr.wait_until_ready();
  10067. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10068. // Regression test for GHSA-qq6v-r583-3h69
  10069. std::string long_filename(8000, 'A');
  10070. std::string body = "----------\r\n"
  10071. "Content-Disposition: form-data; name=\"file1\"; "
  10072. "filename*=\"Utf-8''" +
  10073. long_filename +
  10074. "\"\r\n"
  10075. "\r\n"
  10076. "hello\r\n"
  10077. "------------\r\n";
  10078. auto req = "POST /test HTTP/1.1\r\n"
  10079. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10080. "Content-Length: " +
  10081. std::to_string(body.size()) + "\r\n\r\n" + body;
  10082. ASSERT_TRUE(send_request(1, req));
  10083. }
  10084. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10085. auto handled = false;
  10086. Server svr;
  10087. svr.Post("/test", [&](const Request &req, Response &) {
  10088. ASSERT_EQ(2u, req.form.fields.size());
  10089. const auto &text1 = req.form.get_field("text1");
  10090. ASSERT_EQ("text1", text1);
  10091. const auto &text2 = req.form.get_field("text2");
  10092. ASSERT_EQ("text2", text2);
  10093. handled = true;
  10094. });
  10095. thread t = thread([&] { svr.listen(HOST, PORT); });
  10096. auto se = detail::scope_exit([&] {
  10097. svr.stop();
  10098. t.join();
  10099. ASSERT_FALSE(svr.is_running());
  10100. ASSERT_TRUE(handled);
  10101. });
  10102. svr.wait_until_ready();
  10103. auto req = "POST /test HTTP/1.1\r\n"
  10104. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10105. "Content-Length: 146\r\n"
  10106. "\r\n----------\r\n"
  10107. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10108. "\r\n"
  10109. "text1"
  10110. "\r\n----------\r\n"
  10111. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10112. "\r\n"
  10113. "text2"
  10114. "\r\n------------";
  10115. std::string response;
  10116. ASSERT_TRUE(send_request(1, req, &response));
  10117. ASSERT_EQ("200", response.substr(9, 3));
  10118. }
  10119. TEST(MultipartFormDataTest, ContentLength) {
  10120. auto handled = false;
  10121. Server svr;
  10122. svr.Post("/test", [&](const Request &req, Response &) {
  10123. ASSERT_EQ(2u, req.form.fields.size());
  10124. const auto &text1 = req.form.get_field("text1");
  10125. ASSERT_EQ("text1", text1);
  10126. const auto &text2 = req.form.get_field("text2");
  10127. ASSERT_EQ("text2", text2);
  10128. handled = true;
  10129. });
  10130. thread t = thread([&] { svr.listen(HOST, PORT); });
  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. auto req = "POST /test HTTP/1.1\r\n"
  10139. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10140. "Content-Length: 167\r\n"
  10141. "\r\n----------\r\n"
  10142. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10143. "Content-Length: 5\r\n"
  10144. "\r\n"
  10145. "text1"
  10146. "\r\n----------\r\n"
  10147. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10148. "\r\n"
  10149. "text2"
  10150. "\r\n------------\r\n";
  10151. std::string response;
  10152. ASSERT_TRUE(send_request(1, req, &response));
  10153. ASSERT_EQ("200", response.substr(9, 3));
  10154. }
  10155. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10156. auto handled = false;
  10157. Server svr;
  10158. svr.Post("/test", [&](const Request &req, Response &) {
  10159. ASSERT_EQ(2u, req.form.fields.size());
  10160. const auto &text1 = req.form.get_field("text1");
  10161. ASSERT_EQ("text1", text1);
  10162. // TODO: Add header access for text fields if needed
  10163. const auto &text2 = req.form.get_field("text2");
  10164. ASSERT_EQ("text2", text2);
  10165. // TODO: Header access for text fields needs to be implemented
  10166. // auto &headers = it->second.headers;
  10167. // ASSERT_EQ(3U, headers.size());
  10168. // auto custom_header = headers.find("x-whatever");
  10169. // ASSERT_TRUE(custom_header != headers.end());
  10170. // ASSERT_NE("customvalue", custom_header->second);
  10171. // ASSERT_EQ("CustomValue", custom_header->second);
  10172. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10173. handled = true;
  10174. });
  10175. thread t = thread([&] { svr.listen(HOST, PORT); });
  10176. auto se = detail::scope_exit([&] {
  10177. svr.stop();
  10178. t.join();
  10179. ASSERT_FALSE(svr.is_running());
  10180. ASSERT_TRUE(handled);
  10181. });
  10182. svr.wait_until_ready();
  10183. auto req = "POST /test HTTP/1.1\r\n"
  10184. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10185. "Content-Length: 232\r\n"
  10186. "\r\n----------\r\n"
  10187. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10188. "Content-Length: 5\r\n"
  10189. "X-Test: 1\r\n"
  10190. "\r\n"
  10191. "text1"
  10192. "\r\n----------\r\n"
  10193. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10194. "Content-Type: text/plain\r\n"
  10195. "X-Whatever: CustomValue\r\n"
  10196. "\r\n"
  10197. "text2"
  10198. "\r\n------------\r\n"
  10199. "That should be disregarded. Not even read";
  10200. std::string response;
  10201. ASSERT_TRUE(send_request(1, req, &response));
  10202. ASSERT_EQ("200", response.substr(9, 3));
  10203. }
  10204. TEST(MultipartFormDataTest, LargeHeader) {
  10205. auto handled = false;
  10206. Server svr;
  10207. svr.Post("/test", [&](const Request &req, Response &) {
  10208. ASSERT_EQ(1u, req.form.fields.size());
  10209. const auto &text = req.form.get_field("name1");
  10210. ASSERT_EQ("text1", text);
  10211. handled = true;
  10212. });
  10213. thread t = thread([&] { svr.listen(HOST, PORT); });
  10214. auto se = detail::scope_exit([&] {
  10215. svr.stop();
  10216. t.join();
  10217. ASSERT_FALSE(svr.is_running());
  10218. ASSERT_TRUE(handled);
  10219. });
  10220. svr.wait_until_ready();
  10221. auto boundary = std::string("cpp-httplib-multipart-data");
  10222. std::string content = "--" + boundary +
  10223. "\r\n"
  10224. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10225. "\r\n"
  10226. "text1\r\n"
  10227. "--" +
  10228. boundary + "--\r\n";
  10229. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10230. "Content-Type: multipart/form-data;boundary=" +
  10231. boundary +
  10232. "\r\n"
  10233. "Content-Length: " +
  10234. std::to_string(content.size()) +
  10235. "\r\n"
  10236. "Dummy-Header: ";
  10237. std::string header_suffix = "\r\n"
  10238. "\r\n";
  10239. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10240. size_t header_dummy_size =
  10241. read_buff_size -
  10242. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10243. auto header_dummy = std::string(header_dummy_size, '@');
  10244. auto req = header_prefix + header_dummy + header_suffix + content;
  10245. std::string response;
  10246. ASSERT_TRUE(send_request(1, req, &response));
  10247. ASSERT_EQ("200", response.substr(9, 3));
  10248. }
  10249. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10250. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10251. // (not chunked Transfer-Encoding) after the streaming refactor.
  10252. auto handled = false;
  10253. Server svr;
  10254. svr.Post("/upload", [&](const Request &req, Response &res) {
  10255. auto cl_it = req.headers.find("Content-Length");
  10256. EXPECT_TRUE(cl_it != req.headers.end());
  10257. auto te_it = req.headers.find("Transfer-Encoding");
  10258. EXPECT_TRUE(te_it == req.headers.end());
  10259. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10260. res.set_content("ok", "text/plain");
  10261. handled = true;
  10262. });
  10263. auto port = svr.bind_to_any_port(HOST);
  10264. auto t = thread([&] { svr.listen_after_bind(); });
  10265. auto se = detail::scope_exit([&] {
  10266. svr.stop();
  10267. t.join();
  10268. ASSERT_FALSE(svr.is_running());
  10269. ASSERT_TRUE(handled);
  10270. });
  10271. svr.wait_until_ready();
  10272. UploadFormDataItems items = {
  10273. {"field1", "hello", "", "text/plain"},
  10274. {"file1", "world", "test.txt", "application/octet-stream"},
  10275. };
  10276. Client cli(HOST, port);
  10277. auto res = cli.Post("/upload", {}, items);
  10278. ASSERT_TRUE(res);
  10279. EXPECT_EQ(StatusCode::OK_200, res->status);
  10280. }
  10281. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10282. // Verify that make_multipart_content_provider coalesces many small segments
  10283. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10284. constexpr size_t kItemCount = 1000;
  10285. UploadFormDataItems items;
  10286. items.reserve(kItemCount);
  10287. for (size_t i = 0; i < kItemCount; i++) {
  10288. items.push_back(
  10289. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10290. }
  10291. const std::string boundary = "----test-boundary";
  10292. auto content_length = detail::get_multipart_content_length(items, boundary);
  10293. auto provider = detail::make_multipart_content_provider(items, boundary);
  10294. // Drive the provider the same way write_content_with_progress does
  10295. size_t write_count = 0;
  10296. size_t total_bytes = 0;
  10297. DataSink sink;
  10298. size_t offset = 0;
  10299. sink.write = [&](const char *d, size_t l) -> bool {
  10300. (void)d;
  10301. write_count++;
  10302. total_bytes += l;
  10303. offset += l;
  10304. return true;
  10305. };
  10306. sink.is_writable = []() -> bool { return true; };
  10307. while (offset < content_length) {
  10308. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10309. }
  10310. EXPECT_EQ(content_length, total_bytes);
  10311. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10312. // With buffering into 64KB blocks, write_count should be much smaller.
  10313. auto segment_count = 3 * kItemCount + 1;
  10314. EXPECT_LT(write_count, segment_count / 10);
  10315. }
  10316. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10317. // Integration test: send many UploadFormDataItems and verify the server
  10318. // receives all of them correctly (#2410).
  10319. constexpr size_t kItemCount = 500;
  10320. auto handled = false;
  10321. Server svr;
  10322. svr.Post("/upload", [&](const Request &req, Response &res) {
  10323. EXPECT_EQ(kItemCount, req.form.fields.size());
  10324. for (size_t i = 0; i < kItemCount; i++) {
  10325. auto key = "field" + std::to_string(i);
  10326. auto val = "value" + std::to_string(i);
  10327. auto it = req.form.fields.find(key);
  10328. if (it != req.form.fields.end()) {
  10329. EXPECT_EQ(val, it->second.content);
  10330. } else {
  10331. ADD_FAILURE() << "Missing field: " << key;
  10332. }
  10333. }
  10334. res.set_content("ok", "text/plain");
  10335. handled = true;
  10336. });
  10337. auto port = svr.bind_to_any_port(HOST);
  10338. auto t = thread([&] { svr.listen_after_bind(); });
  10339. auto se = detail::scope_exit([&] {
  10340. svr.stop();
  10341. t.join();
  10342. ASSERT_FALSE(svr.is_running());
  10343. ASSERT_TRUE(handled);
  10344. });
  10345. svr.wait_until_ready();
  10346. UploadFormDataItems items;
  10347. items.reserve(kItemCount);
  10348. for (size_t i = 0; i < kItemCount; i++) {
  10349. items.push_back(
  10350. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10351. }
  10352. Client cli(HOST, port);
  10353. auto res = cli.Post("/upload", items);
  10354. ASSERT_TRUE(res);
  10355. EXPECT_EQ(StatusCode::OK_200, res->status);
  10356. }
  10357. TEST(MultipartFormDataTest, MakeFileProvider) {
  10358. // Verify make_file_provider sends a file's contents correctly.
  10359. const std::string file_content(4096, 'Z');
  10360. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10361. {
  10362. std::ofstream ofs(tmp_path, std::ios::binary);
  10363. ofs.write(file_content.data(),
  10364. static_cast<std::streamsize>(file_content.size()));
  10365. }
  10366. auto handled = false;
  10367. Server svr;
  10368. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10369. const ContentReader &content_reader) {
  10370. ASSERT_TRUE(req.is_multipart_form_data());
  10371. std::vector<FormData> items;
  10372. content_reader(
  10373. [&](const FormData &file) {
  10374. items.push_back(file);
  10375. return true;
  10376. },
  10377. [&](const char *data, size_t data_length) {
  10378. items.back().content.append(data, data_length);
  10379. return true;
  10380. });
  10381. ASSERT_EQ(1u, items.size());
  10382. EXPECT_EQ("myfile", items[0].name);
  10383. EXPECT_EQ("data.bin", items[0].filename);
  10384. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10385. EXPECT_EQ(file_content, items[0].content);
  10386. handled = true;
  10387. });
  10388. auto port = svr.bind_to_any_port(HOST);
  10389. auto t = thread([&] { svr.listen_after_bind(); });
  10390. auto se = detail::scope_exit([&] {
  10391. svr.stop();
  10392. t.join();
  10393. ASSERT_FALSE(svr.is_running());
  10394. ASSERT_TRUE(handled);
  10395. std::remove(tmp_path.c_str());
  10396. });
  10397. svr.wait_until_ready();
  10398. FormDataProviderItems providers;
  10399. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10400. "application/octet-stream"));
  10401. Client cli(HOST, port);
  10402. auto res = cli.Post("/upload", {}, {}, providers);
  10403. ASSERT_TRUE(res);
  10404. EXPECT_EQ(StatusCode::OK_200, res->status);
  10405. }
  10406. TEST(MakeFileBodyTest, Basic) {
  10407. const std::string file_content(4096, 'Z');
  10408. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10409. {
  10410. std::ofstream ofs(tmp_path, std::ios::binary);
  10411. ofs.write(file_content.data(),
  10412. static_cast<std::streamsize>(file_content.size()));
  10413. }
  10414. auto handled = false;
  10415. Server svr;
  10416. svr.Post("/upload", [&](const Request &req, Response &res) {
  10417. EXPECT_EQ(file_content, req.body);
  10418. handled = true;
  10419. res.status = StatusCode::OK_200;
  10420. });
  10421. auto port = svr.bind_to_any_port(HOST);
  10422. auto t = thread([&] { svr.listen_after_bind(); });
  10423. auto se = detail::scope_exit([&] {
  10424. svr.stop();
  10425. t.join();
  10426. ASSERT_FALSE(svr.is_running());
  10427. ASSERT_TRUE(handled);
  10428. std::remove(tmp_path.c_str());
  10429. });
  10430. svr.wait_until_ready();
  10431. auto fb = make_file_body(tmp_path);
  10432. ASSERT_GT(fb.first, 0u);
  10433. Client cli(HOST, port);
  10434. auto res =
  10435. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10436. ASSERT_TRUE(res);
  10437. EXPECT_EQ(StatusCode::OK_200, res->status);
  10438. }
  10439. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10440. static constexpr unsigned int number_of_tasks{1000000};
  10441. std::atomic_uint count{0};
  10442. std::unique_ptr<TaskQueue> task_queue{
  10443. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10444. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10445. auto queued = task_queue->enqueue(
  10446. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10447. EXPECT_TRUE(queued);
  10448. }
  10449. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10450. task_queue->shutdown();
  10451. #else
  10452. EXPECT_NO_THROW(task_queue->shutdown());
  10453. #endif
  10454. EXPECT_EQ(number_of_tasks, count.load());
  10455. }
  10456. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10457. static constexpr unsigned int number_of_tasks{1000000};
  10458. static constexpr unsigned int qlimit{2};
  10459. unsigned int queued_count{0};
  10460. std::atomic_uint count{0};
  10461. std::unique_ptr<TaskQueue> task_queue{
  10462. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10463. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10464. if (task_queue->enqueue(
  10465. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10466. queued_count++;
  10467. }
  10468. }
  10469. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10470. task_queue->shutdown();
  10471. #else
  10472. EXPECT_NO_THROW(task_queue->shutdown());
  10473. #endif
  10474. EXPECT_EQ(queued_count, count.load());
  10475. EXPECT_TRUE(queued_count <= number_of_tasks);
  10476. EXPECT_TRUE(queued_count >= qlimit);
  10477. }
  10478. TEST(TaskQueueTest, MaxQueuedRequests) {
  10479. static constexpr unsigned int qlimit{3};
  10480. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10481. std::condition_variable sem_cv;
  10482. std::mutex sem_mtx;
  10483. int credits = 0;
  10484. bool queued;
  10485. /* Fill up the queue with tasks that will block until we give them credits to
  10486. * complete. */
  10487. for (unsigned int n = 0; n <= qlimit;) {
  10488. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10489. std::unique_lock<std::mutex> lock(sem_mtx);
  10490. while (credits <= 0) {
  10491. sem_cv.wait(lock);
  10492. }
  10493. /* Consume the credit and signal the test code if they are all gone. */
  10494. if (--credits == 0) { sem_cv.notify_one(); }
  10495. });
  10496. if (n < qlimit) {
  10497. /* The first qlimit enqueues must succeed. */
  10498. EXPECT_TRUE(queued);
  10499. } else {
  10500. /* The last one will succeed only when the worker thread
  10501. * starts and dequeues the first blocking task. Although
  10502. * not necessary for the correctness of this test, we sleep for
  10503. * a short while to avoid busy waiting. */
  10504. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10505. }
  10506. if (queued) { n++; }
  10507. }
  10508. /* Further enqueues must fail since the queue is full. */
  10509. for (auto i = 0; i < 4; i++) {
  10510. queued = task_queue->enqueue([] {});
  10511. EXPECT_FALSE(queued);
  10512. }
  10513. /* Give the credits to allow the previous tasks to complete. */
  10514. {
  10515. std::unique_lock<std::mutex> lock(sem_mtx);
  10516. credits += qlimit + 1;
  10517. }
  10518. sem_cv.notify_all();
  10519. /* Wait for all the credits to be consumed. */
  10520. {
  10521. std::unique_lock<std::mutex> lock(sem_mtx);
  10522. while (credits > 0) {
  10523. sem_cv.wait(lock);
  10524. }
  10525. }
  10526. /* Check that we are able again to enqueue at least qlimit tasks. */
  10527. for (unsigned int i = 0; i < qlimit; i++) {
  10528. queued = task_queue->enqueue([] {});
  10529. EXPECT_TRUE(queued);
  10530. }
  10531. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10532. task_queue->shutdown();
  10533. #else
  10534. EXPECT_NO_THROW(task_queue->shutdown());
  10535. #endif
  10536. }
  10537. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10538. Server svr;
  10539. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10540. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10541. });
  10542. svr.Get("/hello", [](const Request &req, Response &res) {
  10543. res.set_content(req.get_param_value("key"), "text/plain");
  10544. });
  10545. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10546. auto se = detail::scope_exit([&] {
  10547. svr.stop();
  10548. thread.join();
  10549. ASSERT_FALSE(svr.is_running());
  10550. });
  10551. svr.wait_until_ready();
  10552. {
  10553. Client cli(HOST, PORT);
  10554. cli.set_follow_location(true);
  10555. auto res = cli.Get("/");
  10556. ASSERT_TRUE(res);
  10557. EXPECT_EQ(StatusCode::OK_200, res->status);
  10558. EXPECT_EQ("val&key2=val2", res->body);
  10559. }
  10560. }
  10561. #endif
  10562. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10563. Server svr;
  10564. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10565. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10566. });
  10567. svr.Get("/hello", [](const Request &req, Response &res) {
  10568. res.set_content(req.get_param_value("key"), "text/plain");
  10569. });
  10570. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10571. auto se = detail::scope_exit([&] {
  10572. svr.stop();
  10573. thread.join();
  10574. ASSERT_FALSE(svr.is_running());
  10575. });
  10576. svr.wait_until_ready();
  10577. {
  10578. Client cli(HOST, PORT);
  10579. cli.set_follow_location(true);
  10580. auto res = cli.Get("/");
  10581. ASSERT_TRUE(res);
  10582. EXPECT_EQ(StatusCode::OK_200, res->status);
  10583. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10584. }
  10585. }
  10586. TEST(RedirectTest, RedirectWithPlusInPath) {
  10587. Server svr;
  10588. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10589. res.set_redirect("/a+b");
  10590. });
  10591. // Route pattern uses regex; escape + as \\+
  10592. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10593. res.set_content(req.path, "text/plain");
  10594. });
  10595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10596. auto se = detail::scope_exit([&] {
  10597. svr.stop();
  10598. thread.join();
  10599. ASSERT_FALSE(svr.is_running());
  10600. });
  10601. svr.wait_until_ready();
  10602. {
  10603. Client cli(HOST, PORT);
  10604. cli.set_follow_location(true);
  10605. auto res = cli.Get("/");
  10606. ASSERT_TRUE(res);
  10607. EXPECT_EQ(StatusCode::OK_200, res->status);
  10608. EXPECT_EQ("/a+b", res->body);
  10609. }
  10610. }
  10611. #ifdef CPPHTTPLIB_SSL_ENABLED
  10612. TEST(RedirectTest, Issue2185_Online) {
  10613. SSLClient client("github.com");
  10614. client.set_follow_location(true);
  10615. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10616. "Coollab-Windows.zip");
  10617. ASSERT_TRUE(res);
  10618. EXPECT_EQ(StatusCode::OK_200, res->status);
  10619. EXPECT_EQ(9920427U, res->body.size());
  10620. }
  10621. #endif
  10622. TEST(VulnerabilityTest, CRLFInjection) {
  10623. Server svr;
  10624. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10625. res.set_content("Hello 1", "text/plain");
  10626. });
  10627. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10628. res.set_content("Hello 2", "text/plain");
  10629. });
  10630. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10631. res.set_content("Hello 3", "text/plain");
  10632. });
  10633. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10634. res.set_content("Hello 4", "text/plain");
  10635. });
  10636. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10637. for (const auto &x : req.headers) {
  10638. auto key = x.first;
  10639. EXPECT_STRNE("evil", key.c_str());
  10640. }
  10641. });
  10642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10643. auto se = detail::scope_exit([&] {
  10644. svr.stop();
  10645. thread.join();
  10646. ASSERT_FALSE(svr.is_running());
  10647. });
  10648. svr.wait_until_ready();
  10649. {
  10650. Client cli(HOST, PORT);
  10651. cli.Post("/test1", "A=B",
  10652. "application/x-www-form-urlencoded\r\nevil: hello1");
  10653. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10654. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10655. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10656. }
  10657. }
  10658. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10659. auto server_thread = std::thread([] {
  10660. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10661. default_socket_options(srv);
  10662. sockaddr_in addr{};
  10663. addr.sin_family = AF_INET;
  10664. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10665. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10666. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10667. ::listen(srv, 1);
  10668. sockaddr_in cli_addr{};
  10669. socklen_t cli_len = sizeof(cli_addr);
  10670. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10671. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10672. std::string buf_all;
  10673. char buf[2048];
  10674. ssize_t n;
  10675. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10676. buf_all.append(buf, static_cast<size_t>(n));
  10677. size_t pos;
  10678. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10679. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10680. auto e = request_block.find("\r\n");
  10681. if (e != std::string::npos) {
  10682. auto request_line = request_block.substr(0, e);
  10683. std::string msg =
  10684. "CRLF injection detected in request line: '" + request_line + "'";
  10685. EXPECT_FALSE(true) << msg;
  10686. }
  10687. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10688. ::send(cli,
  10689. #ifdef _WIN32
  10690. static_cast<const char *>(resp.c_str()),
  10691. static_cast<int>(resp.size()),
  10692. #else
  10693. resp.c_str(), resp.size(),
  10694. #endif
  10695. 0);
  10696. buf_all.erase(0, pos + 4);
  10697. }
  10698. }
  10699. detail::close_socket(cli);
  10700. detail::close_socket(srv);
  10701. });
  10702. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10703. auto cli = Client("127.0.0.1", PORT + 1);
  10704. auto headers = Headers{
  10705. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10706. {"Connection", "keep-alive"}};
  10707. auto res = cli.Get("/hi", headers);
  10708. EXPECT_FALSE(res);
  10709. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10710. server_thread.join();
  10711. }
  10712. TEST(PathParamsTest, StaticMatch) {
  10713. const auto pattern = "/users/all";
  10714. detail::PathParamsMatcher matcher(pattern);
  10715. Request request;
  10716. request.path = "/users/all";
  10717. ASSERT_TRUE(matcher.match(request));
  10718. std::unordered_map<std::string, std::string> expected_params = {};
  10719. EXPECT_EQ(request.path_params, expected_params);
  10720. }
  10721. TEST(PathParamsTest, StaticMismatch) {
  10722. const auto pattern = "/users/all";
  10723. detail::PathParamsMatcher matcher(pattern);
  10724. Request request;
  10725. request.path = "/users/1";
  10726. ASSERT_FALSE(matcher.match(request));
  10727. }
  10728. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10729. const auto pattern = "/users/:id/subscriptions";
  10730. detail::PathParamsMatcher matcher(pattern);
  10731. Request request;
  10732. request.path = "/users/42/subscriptions";
  10733. ASSERT_TRUE(matcher.match(request));
  10734. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10735. EXPECT_EQ(request.path_params, expected_params);
  10736. }
  10737. TEST(PathParamsTest, SingleParamInTheEnd) {
  10738. const auto pattern = "/users/:id";
  10739. detail::PathParamsMatcher matcher(pattern);
  10740. Request request;
  10741. request.path = "/users/24";
  10742. ASSERT_TRUE(matcher.match(request));
  10743. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10744. EXPECT_EQ(request.path_params, expected_params);
  10745. }
  10746. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10747. const auto pattern = "/users/:id/";
  10748. detail::PathParamsMatcher matcher(pattern);
  10749. Request request;
  10750. request.path = "/users/42/";
  10751. ASSERT_TRUE(matcher.match(request));
  10752. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10753. EXPECT_EQ(request.path_params, expected_params);
  10754. }
  10755. TEST(PathParamsTest, EmptyParam) {
  10756. const auto pattern = "/users/:id/";
  10757. detail::PathParamsMatcher matcher(pattern);
  10758. Request request;
  10759. request.path = "/users//";
  10760. ASSERT_TRUE(matcher.match(request));
  10761. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10762. EXPECT_EQ(request.path_params, expected_params);
  10763. }
  10764. TEST(PathParamsTest, FragmentMismatch) {
  10765. const auto pattern = "/users/:id/";
  10766. detail::PathParamsMatcher matcher(pattern);
  10767. Request request;
  10768. request.path = "/admins/24/";
  10769. ASSERT_FALSE(matcher.match(request));
  10770. }
  10771. TEST(PathParamsTest, ExtraFragments) {
  10772. const auto pattern = "/users/:id";
  10773. detail::PathParamsMatcher matcher(pattern);
  10774. Request request;
  10775. request.path = "/users/42/subscriptions";
  10776. ASSERT_FALSE(matcher.match(request));
  10777. }
  10778. TEST(PathParamsTest, MissingTrailingParam) {
  10779. const auto pattern = "/users/:id";
  10780. detail::PathParamsMatcher matcher(pattern);
  10781. Request request;
  10782. request.path = "/users";
  10783. ASSERT_FALSE(matcher.match(request));
  10784. }
  10785. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10786. const auto pattern = "/users/:id/subscriptions";
  10787. detail::PathParamsMatcher matcher(pattern);
  10788. Request request;
  10789. request.path = "/users/subscriptions";
  10790. ASSERT_FALSE(matcher.match(request));
  10791. }
  10792. TEST(PathParamsTest, MultipleParams) {
  10793. const auto pattern = "/users/:userid/subscriptions/:subid";
  10794. detail::PathParamsMatcher matcher(pattern);
  10795. Request request;
  10796. request.path = "/users/42/subscriptions/2";
  10797. ASSERT_TRUE(matcher.match(request));
  10798. std::unordered_map<std::string, std::string> expected_params = {
  10799. {"userid", "42"}, {"subid", "2"}};
  10800. EXPECT_EQ(request.path_params, expected_params);
  10801. }
  10802. TEST(PathParamsTest, SequenceOfParams) {
  10803. const auto pattern = "/values/:x/:y/:z";
  10804. detail::PathParamsMatcher matcher(pattern);
  10805. Request request;
  10806. request.path = "/values/1/2/3";
  10807. ASSERT_TRUE(matcher.match(request));
  10808. std::unordered_map<std::string, std::string> expected_params = {
  10809. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10810. EXPECT_EQ(request.path_params, expected_params);
  10811. }
  10812. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10813. const auto pattern = "/prefix:suffix";
  10814. detail::PathParamsMatcher matcher(pattern);
  10815. Request request;
  10816. request.path = "/prefix:suffix";
  10817. ASSERT_TRUE(matcher.match(request));
  10818. const std::unordered_map<std::string, std::string> expected_params = {};
  10819. EXPECT_EQ(request.path_params, expected_params);
  10820. }
  10821. TEST(ParseUrlTest, VariousPatterns) {
  10822. {
  10823. detail::UrlComponents uc;
  10824. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  10825. EXPECT_EQ("http", uc.scheme);
  10826. EXPECT_EQ("example.com", uc.host);
  10827. EXPECT_EQ("8080", uc.port);
  10828. EXPECT_EQ("/path", uc.path);
  10829. EXPECT_EQ("?q=1", uc.query);
  10830. }
  10831. {
  10832. detail::UrlComponents uc;
  10833. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  10834. EXPECT_EQ("https", uc.scheme);
  10835. EXPECT_EQ("example.com", uc.host);
  10836. EXPECT_TRUE(uc.port.empty());
  10837. EXPECT_EQ("/path", uc.path);
  10838. }
  10839. {
  10840. detail::UrlComponents uc;
  10841. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  10842. EXPECT_EQ("::1", uc.host);
  10843. EXPECT_EQ("8080", uc.port);
  10844. EXPECT_EQ("/path", uc.path);
  10845. }
  10846. {
  10847. detail::UrlComponents uc;
  10848. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  10849. }
  10850. {
  10851. detail::UrlComponents uc;
  10852. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  10853. EXPECT_TRUE(uc.scheme.empty());
  10854. EXPECT_EQ("example.com", uc.host);
  10855. EXPECT_EQ("/path", uc.path);
  10856. EXPECT_EQ("?q=1", uc.query);
  10857. }
  10858. {
  10859. detail::UrlComponents uc;
  10860. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  10861. EXPECT_TRUE(uc.host.empty());
  10862. EXPECT_EQ("/path", uc.path);
  10863. EXPECT_EQ("?q=1", uc.query);
  10864. }
  10865. {
  10866. detail::UrlComponents uc;
  10867. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  10868. EXPECT_EQ("example.com", uc.host);
  10869. EXPECT_EQ("8080", uc.port);
  10870. }
  10871. {
  10872. // Unix socket path — must not be parsed as host
  10873. detail::UrlComponents uc;
  10874. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  10875. EXPECT_TRUE(uc.host.empty());
  10876. }
  10877. {
  10878. detail::UrlComponents uc;
  10879. ASSERT_TRUE(detail::parse_url("", uc));
  10880. EXPECT_TRUE(uc.host.empty());
  10881. EXPECT_TRUE(uc.path.empty());
  10882. }
  10883. {
  10884. detail::UrlComponents uc;
  10885. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  10886. }
  10887. {
  10888. detail::UrlComponents uc;
  10889. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  10890. }
  10891. {
  10892. // Accepted by parse_url; callers restrict to http/https
  10893. detail::UrlComponents uc;
  10894. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  10895. EXPECT_EQ("ftp", uc.scheme);
  10896. }
  10897. {
  10898. detail::UrlComponents uc;
  10899. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  10900. }
  10901. {
  10902. detail::UrlComponents uc;
  10903. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  10904. }
  10905. }
  10906. TEST(ParseUrlTest, FragmentHandling) {
  10907. {
  10908. detail::UrlComponents uc;
  10909. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  10910. EXPECT_EQ("/path", uc.path);
  10911. EXPECT_TRUE(uc.query.empty());
  10912. }
  10913. {
  10914. detail::UrlComponents uc;
  10915. ASSERT_TRUE(detail::parse_url("#frag", uc));
  10916. EXPECT_TRUE(uc.path.empty());
  10917. EXPECT_TRUE(uc.query.empty());
  10918. }
  10919. }
  10920. TEST(ParseUrlTest, UserinfoHandling) {
  10921. // Userinfo with @ but no colon — host includes @
  10922. detail::UrlComponents uc;
  10923. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  10924. EXPECT_EQ("user@host.com", uc.host);
  10925. EXPECT_EQ("/path", uc.path);
  10926. }
  10927. TEST(ParseUrlTest, IPv6EdgeCases) {
  10928. {
  10929. detail::UrlComponents uc;
  10930. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  10931. EXPECT_TRUE(uc.scheme.empty());
  10932. EXPECT_EQ("::1", uc.host);
  10933. EXPECT_EQ("8080", uc.port);
  10934. }
  10935. {
  10936. // Zone ID '%25' is not in [a-fA-F0-9:]
  10937. detail::UrlComponents uc;
  10938. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  10939. }
  10940. }
  10941. TEST(ParseUrlTest, SchemeEdgeCases) {
  10942. {
  10943. detail::UrlComponents uc;
  10944. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  10945. }
  10946. {
  10947. detail::UrlComponents uc;
  10948. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  10949. }
  10950. {
  10951. detail::UrlComponents uc;
  10952. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  10953. }
  10954. }
  10955. TEST(ParseUrlTest, PortEdgeCases) {
  10956. {
  10957. detail::UrlComponents uc;
  10958. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  10959. EXPECT_TRUE(uc.port.empty());
  10960. EXPECT_EQ("/path", uc.path);
  10961. }
  10962. {
  10963. // parse_url accepts any port string; validation is done by parse_port
  10964. detail::UrlComponents uc;
  10965. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  10966. EXPECT_EQ("abc", uc.port);
  10967. }
  10968. }
  10969. TEST(ParseUrlTest, WebSocketPatterns) {
  10970. {
  10971. detail::UrlComponents uc;
  10972. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  10973. EXPECT_EQ("ws", uc.scheme);
  10974. EXPECT_EQ("echo.example.com", uc.host);
  10975. EXPECT_EQ("8080", uc.port);
  10976. EXPECT_EQ("/ws", uc.path);
  10977. }
  10978. {
  10979. detail::UrlComponents uc;
  10980. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  10981. EXPECT_EQ("wss", uc.scheme);
  10982. EXPECT_EQ("echo.example.com", uc.host);
  10983. EXPECT_TRUE(uc.port.empty());
  10984. EXPECT_EQ("/ws", uc.path);
  10985. }
  10986. }
  10987. TEST(ParseUrlTest, QueryOnly) {
  10988. detail::UrlComponents uc;
  10989. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  10990. EXPECT_TRUE(uc.host.empty());
  10991. EXPECT_TRUE(uc.path.empty());
  10992. EXPECT_EQ("?q=1&r=2", uc.query);
  10993. }
  10994. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  10995. detail::UrlComponents uc;
  10996. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  10997. EXPECT_TRUE(uc.scheme.empty());
  10998. EXPECT_EQ("example.com", uc.host);
  10999. EXPECT_EQ("443", uc.port);
  11000. EXPECT_EQ("/path", uc.path);
  11001. }
  11002. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11003. // If ipv6 regex working, regex match codepath is taken.
  11004. // else port will default to 80 in Client impl
  11005. int clientImplMagicPort = 80;
  11006. int port = 4321;
  11007. // above ports must be different to avoid false negative
  11008. EXPECT_NE(clientImplMagicPort, port);
  11009. std::string ipV6TestURL = "http://[ff06::c3]";
  11010. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11011. CLIENT_PRIVATE_KEY_FILE);
  11012. EXPECT_EQ(cli.port(), port);
  11013. }
  11014. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11015. auto file_path = "./www/dir/index.html";
  11016. auto dir_path = "./www/dir";
  11017. detail::FileStat stat_file(file_path);
  11018. EXPECT_TRUE(stat_file.is_file());
  11019. EXPECT_FALSE(stat_file.is_dir());
  11020. detail::FileStat stat_dir(dir_path);
  11021. EXPECT_FALSE(stat_dir.is_file());
  11022. EXPECT_TRUE(stat_dir.is_dir());
  11023. }
  11024. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11025. // IPv4 with default HTTP port (80)
  11026. EXPECT_EQ("example.com",
  11027. detail::make_host_and_port_string("example.com", 80, false));
  11028. // IPv4 with default HTTPS port (443)
  11029. EXPECT_EQ("example.com",
  11030. detail::make_host_and_port_string("example.com", 443, true));
  11031. // IPv4 with non-default HTTP port
  11032. EXPECT_EQ("example.com:8080",
  11033. detail::make_host_and_port_string("example.com", 8080, false));
  11034. // IPv4 with non-default HTTPS port
  11035. EXPECT_EQ("example.com:8443",
  11036. detail::make_host_and_port_string("example.com", 8443, true));
  11037. // IPv6 with default HTTP port (80)
  11038. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11039. // IPv6 with default HTTPS port (443)
  11040. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11041. // IPv6 with non-default HTTP port
  11042. EXPECT_EQ("[::1]:8080",
  11043. detail::make_host_and_port_string("::1", 8080, false));
  11044. // IPv6 with non-default HTTPS port
  11045. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11046. // IPv6 full address with default port
  11047. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11048. detail::make_host_and_port_string(
  11049. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11050. // IPv6 full address with non-default port
  11051. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11052. detail::make_host_and_port_string(
  11053. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11054. // IPv6 localhost with non-default port
  11055. EXPECT_EQ("[::1]:3000",
  11056. detail::make_host_and_port_string("::1", 3000, false));
  11057. // IPv6 with zone ID (link-local address) with default port
  11058. EXPECT_EQ("[fe80::1%eth0]",
  11059. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11060. // IPv6 with zone ID (link-local address) with non-default port
  11061. EXPECT_EQ("[fe80::1%eth0]:8080",
  11062. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11063. // Edge case: Port 443 with is_ssl=false (should add port)
  11064. EXPECT_EQ("example.com:443",
  11065. detail::make_host_and_port_string("example.com", 443, false));
  11066. // Edge case: Port 80 with is_ssl=true (should add port)
  11067. EXPECT_EQ("example.com:80",
  11068. detail::make_host_and_port_string("example.com", 80, true));
  11069. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11070. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11071. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11072. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11073. // Security fix: Already bracketed IPv6 should not get double brackets
  11074. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11075. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11076. EXPECT_EQ("[::1]:8080",
  11077. detail::make_host_and_port_string("[::1]", 8080, false));
  11078. EXPECT_EQ("[2001:db8::1]:8080",
  11079. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11080. EXPECT_EQ("[fe80::1%eth0]",
  11081. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11082. EXPECT_EQ("[fe80::1%eth0]:8080",
  11083. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11084. // Edge case: Empty host (should return as-is)
  11085. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11086. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11087. // This is a known limitation but shouldn't crash
  11088. EXPECT_EQ("[host:name]",
  11089. detail::make_host_and_port_string("host:name", 80, false));
  11090. // Port number edge cases (no validation, but should not crash)
  11091. EXPECT_EQ("example.com:0",
  11092. detail::make_host_and_port_string("example.com", 0, false));
  11093. EXPECT_EQ("example.com:-1",
  11094. detail::make_host_and_port_string("example.com", -1, false));
  11095. EXPECT_EQ("example.com:65535",
  11096. detail::make_host_and_port_string("example.com", 65535, false));
  11097. EXPECT_EQ("example.com:65536",
  11098. detail::make_host_and_port_string("example.com", 65536, false));
  11099. }
  11100. #ifdef CPPHTTPLIB_SSL_ENABLED
  11101. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11102. httplib::SSLClient cli("roblox.com", 443);
  11103. cli.set_follow_location(true);
  11104. auto res = cli.Get("/");
  11105. ASSERT_TRUE(res);
  11106. EXPECT_EQ(StatusCode::OK_200, res->status);
  11107. }
  11108. #endif
  11109. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11110. Server svr;
  11111. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11112. EXPECT_EQ(res.status, 400);
  11113. });
  11114. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11115. auto se = detail::scope_exit([&] {
  11116. svr.stop();
  11117. thread.join();
  11118. ASSERT_FALSE(svr.is_running());
  11119. });
  11120. svr.wait_until_ready();
  11121. Client cli(HOST, PORT);
  11122. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11123. }
  11124. TEST(InvalidHeaderCharsTest, is_field_name) {
  11125. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11126. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11127. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11128. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11129. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11130. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11131. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11132. EXPECT_FALSE(detail::fields::is_field_name(""));
  11133. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11134. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11135. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11136. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11137. }
  11138. TEST(InvalidHeaderCharsTest, is_field_value) {
  11139. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11140. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11141. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11142. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11143. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11144. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11145. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11146. EXPECT_TRUE(detail::fields::is_field_value(""));
  11147. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11148. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11149. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11150. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11151. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11152. }
  11153. TEST(InvalidHeaderCharsTest, OnServer) {
  11154. Server svr;
  11155. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11156. std::string header = "Not Set";
  11157. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11158. res.set_header(header, "value");
  11159. res.set_content("Page Content Page Content", "text/plain");
  11160. });
  11161. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11162. std::string header = "Not Set";
  11163. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11164. res.set_header("X-Test", header);
  11165. res.set_content("Page Content Page Content", "text/plain");
  11166. });
  11167. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11168. auto se = detail::scope_exit([&] {
  11169. svr.stop();
  11170. thread.join();
  11171. ASSERT_FALSE(svr.is_running());
  11172. });
  11173. svr.wait_until_ready();
  11174. Client cli(HOST, PORT);
  11175. {
  11176. auto res = cli.Get(
  11177. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11178. ASSERT_TRUE(res);
  11179. EXPECT_EQ("Page Content Page Content", res->body);
  11180. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11181. }
  11182. {
  11183. auto res = cli.Get(
  11184. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11185. ASSERT_TRUE(res);
  11186. EXPECT_EQ("Page Content Page Content", res->body);
  11187. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11188. }
  11189. }
  11190. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11191. auto handled = false;
  11192. Server svr;
  11193. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11194. thread t = thread([&] { svr.listen(HOST, PORT); });
  11195. auto se = detail::scope_exit([&] {
  11196. svr.stop();
  11197. t.join();
  11198. ASSERT_FALSE(svr.is_running());
  11199. ASSERT_FALSE(handled);
  11200. });
  11201. svr.wait_until_ready();
  11202. auto req = "POST /test HTTP/1.1\r\n"
  11203. "Content-Length: x\r\n"
  11204. "\r\n";
  11205. std::string response;
  11206. ASSERT_TRUE(send_request(1, req, &response));
  11207. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11208. response.substr(0, response.find("\r\n")));
  11209. }
  11210. #ifndef _WIN32
  11211. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11212. static constexpr char reject[] = "Unauthorized";
  11213. static constexpr char accept[] = "Upload accepted";
  11214. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11215. Server svr;
  11216. svr.set_expect_100_continue_handler(
  11217. [](const Request & /*req*/, Response &res) {
  11218. res.status = StatusCode::Unauthorized_401;
  11219. res.set_content(reject, "text/plain");
  11220. return res.status;
  11221. });
  11222. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11223. res.set_content(accept, "text/plain");
  11224. });
  11225. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11226. auto se = detail::scope_exit([&] {
  11227. svr.stop();
  11228. thread.join();
  11229. ASSERT_FALSE(svr.is_running());
  11230. });
  11231. svr.wait_until_ready();
  11232. {
  11233. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11234. curl_easy_init(), &curl_easy_cleanup};
  11235. ASSERT_NE(curl, nullptr);
  11236. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11237. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11238. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11239. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11240. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11241. &curl_slist_free_all};
  11242. ASSERT_NE(list, nullptr);
  11243. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11244. struct read_data {
  11245. size_t read_size;
  11246. size_t total_size;
  11247. } data = {0, total_size};
  11248. using read_callback_t =
  11249. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11250. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11251. void *userdata) -> size_t {
  11252. read_data *d = (read_data *)userdata;
  11253. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11254. std::fill_n(ptr, size * nmemb, 'A');
  11255. d->read_size += size * nmemb;
  11256. return size * nmemb;
  11257. };
  11258. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11259. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11260. std::vector<char> buffer;
  11261. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11262. using write_callback_t =
  11263. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11264. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11265. void *userdata) -> size_t {
  11266. std::vector<char> *buf = (std::vector<char> *)userdata;
  11267. buf->reserve(buf->size() + size * nmemb + 1);
  11268. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11269. return size * nmemb;
  11270. };
  11271. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11272. {
  11273. const auto res = curl_easy_perform(curl.get());
  11274. ASSERT_EQ(res, CURLE_OK);
  11275. }
  11276. {
  11277. auto response_code = long{};
  11278. const auto res =
  11279. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11280. ASSERT_EQ(res, CURLE_OK);
  11281. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11282. }
  11283. {
  11284. auto dl = curl_off_t{};
  11285. const auto res =
  11286. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11287. ASSERT_EQ(res, CURLE_OK);
  11288. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11289. }
  11290. {
  11291. buffer.push_back('\0');
  11292. ASSERT_STRCASEEQ(buffer.data(), reject);
  11293. }
  11294. }
  11295. }
  11296. #endif
  11297. template <typename S, typename C>
  11298. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11299. svr.Get("/stream", [&](const Request &, Response &res) {
  11300. auto data = new std::string("01234567890123456789");
  11301. res.set_content_provider(
  11302. data->size(), "text/plain",
  11303. [&, data](size_t offset, size_t length, DataSink &sink) {
  11304. const size_t DATA_CHUNK_SIZE = 4;
  11305. const auto &d = *data;
  11306. std::this_thread::sleep_for(std::chrono::seconds(1));
  11307. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11308. return true;
  11309. },
  11310. [data](bool success) {
  11311. EXPECT_FALSE(success);
  11312. delete data;
  11313. });
  11314. });
  11315. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11316. auto i = new size_t(0);
  11317. res.set_content_provider(
  11318. "text/plain",
  11319. [i](size_t, DataSink &sink) {
  11320. if (*i < 5) {
  11321. std::this_thread::sleep_for(std::chrono::seconds(1));
  11322. sink.write("abcd", 4);
  11323. (*i)++;
  11324. } else {
  11325. sink.done();
  11326. }
  11327. return true;
  11328. },
  11329. [i](bool success) {
  11330. EXPECT_FALSE(success);
  11331. delete i;
  11332. });
  11333. });
  11334. svr.Get("/chunked", [&](const Request &, Response &res) {
  11335. auto i = new size_t(0);
  11336. res.set_chunked_content_provider(
  11337. "text/plain",
  11338. [i](size_t, DataSink &sink) {
  11339. if (*i < 5) {
  11340. std::this_thread::sleep_for(std::chrono::seconds(1));
  11341. sink.os << "abcd";
  11342. (*i)++;
  11343. } else {
  11344. sink.done();
  11345. }
  11346. return true;
  11347. },
  11348. [i](bool success) {
  11349. EXPECT_FALSE(success);
  11350. delete i;
  11351. });
  11352. });
  11353. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11354. auto se = detail::scope_exit([&] {
  11355. svr.stop();
  11356. listen_thread.join();
  11357. ASSERT_FALSE(svr.is_running());
  11358. });
  11359. svr.wait_until_ready();
  11360. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11361. {
  11362. auto start = std::chrono::steady_clock::now();
  11363. auto res = cli.Get("/stream");
  11364. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11365. std::chrono::steady_clock::now() - start)
  11366. .count();
  11367. ASSERT_FALSE(res);
  11368. EXPECT_EQ(Error::Read, res.error());
  11369. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11370. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11371. }
  11372. {
  11373. auto start = std::chrono::steady_clock::now();
  11374. auto res = cli.Get("/stream_without_length");
  11375. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11376. std::chrono::steady_clock::now() - start)
  11377. .count();
  11378. ASSERT_FALSE(res);
  11379. EXPECT_EQ(Error::Read, res.error());
  11380. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11381. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11382. }
  11383. {
  11384. auto start = std::chrono::steady_clock::now();
  11385. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11386. EXPECT_EQ("abcd", string(data, data_length));
  11387. return true;
  11388. });
  11389. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11390. std::chrono::steady_clock::now() - start)
  11391. .count();
  11392. ASSERT_FALSE(res);
  11393. EXPECT_EQ(Error::Read, res.error());
  11394. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11395. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11396. }
  11397. }
  11398. TEST(MaxTimeoutTest, ContentStream) {
  11399. time_t timeout = 2000;
  11400. time_t threshold = 200;
  11401. Server svr;
  11402. Client cli("localhost", PORT);
  11403. max_timeout_test(svr, cli, timeout, threshold);
  11404. }
  11405. #ifdef CPPHTTPLIB_SSL_ENABLED
  11406. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11407. time_t timeout = 2000;
  11408. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11410. SSLClient cli("localhost", PORT);
  11411. cli.enable_server_certificate_verification(false);
  11412. max_timeout_test(svr, cli, timeout, threshold);
  11413. }
  11414. #endif
  11415. class EventDispatcher {
  11416. public:
  11417. EventDispatcher() {}
  11418. bool wait_event(DataSink *sink) {
  11419. unique_lock<mutex> lk(m_);
  11420. int id = id_;
  11421. // Wait with timeout to prevent hanging if client disconnects
  11422. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11423. [&] { return cid_ == id; })) {
  11424. return false; // Timeout occurred
  11425. }
  11426. sink->write(message_.data(), message_.size());
  11427. return true;
  11428. }
  11429. void send_event(const string &message) {
  11430. lock_guard<mutex> lk(m_);
  11431. cid_ = id_++;
  11432. message_ = message;
  11433. cv_.notify_all();
  11434. }
  11435. private:
  11436. mutex m_;
  11437. condition_variable cv_;
  11438. atomic_int id_{0};
  11439. atomic_int cid_{-1};
  11440. string message_;
  11441. };
  11442. TEST(ClientInThreadTest, Issue2068) {
  11443. EventDispatcher ed;
  11444. Server svr;
  11445. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11446. res.set_chunked_content_provider("text/event-stream",
  11447. [&](size_t /*offset*/, DataSink &sink) {
  11448. return ed.wait_event(&sink);
  11449. });
  11450. });
  11451. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11452. svr.wait_until_ready();
  11453. thread event_thread([&] {
  11454. int id = 0;
  11455. while (svr.is_running()) {
  11456. this_thread::sleep_for(chrono::milliseconds(500));
  11457. std::stringstream ss;
  11458. ss << "data: " << id << "\n\n";
  11459. ed.send_event(ss.str());
  11460. id++;
  11461. }
  11462. });
  11463. auto se = detail::scope_exit([&] {
  11464. svr.stop();
  11465. listen_thread.join();
  11466. event_thread.join();
  11467. ASSERT_FALSE(svr.is_running());
  11468. });
  11469. {
  11470. auto client = detail::make_unique<Client>(HOST, PORT);
  11471. client->set_read_timeout(std::chrono::minutes(10));
  11472. std::atomic<bool> stop{false};
  11473. std::thread t([&] {
  11474. client->Get("/event1",
  11475. [&](const char *, size_t) -> bool { return !stop; });
  11476. });
  11477. std::this_thread::sleep_for(std::chrono::seconds(2));
  11478. stop = true;
  11479. client->stop();
  11480. t.join();
  11481. // Reset client after thread has finished
  11482. client.reset();
  11483. }
  11484. }
  11485. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11486. auto handled = false;
  11487. Server svr;
  11488. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11489. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11490. auto se = detail::scope_exit([&] {
  11491. svr.stop();
  11492. t.join();
  11493. ASSERT_FALSE(svr.is_running());
  11494. ASSERT_FALSE(handled);
  11495. });
  11496. svr.wait_until_ready();
  11497. // Two Content-Length headers with different values — must be rejected
  11498. auto req = "POST /test HTTP/1.1\r\n"
  11499. "Content-Length: 5\r\n"
  11500. "Content-Length: 10\r\n"
  11501. "\r\n"
  11502. "hello";
  11503. std::string response;
  11504. ASSERT_TRUE(send_request(1, req, &response));
  11505. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11506. response.substr(0, response.find("\r\n")));
  11507. }
  11508. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11509. auto handled = false;
  11510. Server svr;
  11511. svr.Post("/test", [&](const Request &, Response &res) {
  11512. handled = true;
  11513. res.set_content("ok", "text/plain");
  11514. });
  11515. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11516. auto se = detail::scope_exit([&] {
  11517. svr.stop();
  11518. t.join();
  11519. ASSERT_FALSE(svr.is_running());
  11520. ASSERT_TRUE(handled);
  11521. });
  11522. svr.wait_until_ready();
  11523. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11524. auto req = "POST /test HTTP/1.1\r\n"
  11525. "Content-Length: 5\r\n"
  11526. "Content-Length: 5\r\n"
  11527. "\r\n"
  11528. "hello";
  11529. std::string response;
  11530. ASSERT_TRUE(send_request(1, req, &response));
  11531. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11532. }
  11533. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11534. Server svr;
  11535. svr.Get("/", [](const Request &req, Response &res) {
  11536. EXPECT_EQ(2U, req.trailers.size());
  11537. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11538. // Denied
  11539. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11540. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11541. // Accepted
  11542. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11543. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11544. EXPECT_TRUE(req.has_trailer("X-World"));
  11545. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11546. res.set_content("ok", "text/plain");
  11547. });
  11548. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11549. auto se = detail::scope_exit([&] {
  11550. svr.stop();
  11551. t.join();
  11552. ASSERT_FALSE(svr.is_running());
  11553. });
  11554. svr.wait_until_ready();
  11555. const std::string req = "GET / HTTP/1.1\r\n"
  11556. "Transfer-Encoding: chunked\r\n"
  11557. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11558. "\r\n"
  11559. "0\r\n"
  11560. "Content-Length: 10\r\n"
  11561. "Host: internal.local\r\n"
  11562. "Content-Type: malicious/content\r\n"
  11563. "Cookie: any\r\n"
  11564. "Set-Cookie: any\r\n"
  11565. "X-Forwarded-For: attacker.com\r\n"
  11566. "X-Real-Ip: 1.1.1.1\r\n"
  11567. "X-Hello: hello\r\n"
  11568. "X-World: world\r\n"
  11569. "\r\n";
  11570. std::string res;
  11571. ASSERT_TRUE(send_request(1, req, &res));
  11572. }
  11573. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11574. Server svr;
  11575. std::string observed_remote_addr;
  11576. std::string observed_xff;
  11577. svr.Get("/ip", [&](const Request &req, Response &res) {
  11578. observed_remote_addr = req.remote_addr;
  11579. observed_xff = req.get_header_value("X-Forwarded-For");
  11580. res.set_content("ok", "text/plain");
  11581. });
  11582. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11583. auto se = detail::scope_exit([&] {
  11584. svr.stop();
  11585. t.join();
  11586. ASSERT_FALSE(svr.is_running());
  11587. });
  11588. svr.wait_until_ready();
  11589. Client cli(HOST, PORT);
  11590. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11591. ASSERT_TRUE(res);
  11592. EXPECT_EQ(StatusCode::OK_200, res->status);
  11593. EXPECT_EQ(observed_xff, "203.0.113.66");
  11594. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11595. observed_remote_addr == "127.0.0.1");
  11596. }
  11597. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11598. Server svr;
  11599. svr.set_trusted_proxies({"203.0.113.66"});
  11600. std::string observed_remote_addr;
  11601. std::string observed_xff;
  11602. svr.Get("/ip", [&](const Request &req, Response &res) {
  11603. observed_remote_addr = req.remote_addr;
  11604. observed_xff = req.get_header_value("X-Forwarded-For");
  11605. res.set_content("ok", "text/plain");
  11606. });
  11607. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11608. auto se = detail::scope_exit([&] {
  11609. svr.stop();
  11610. t.join();
  11611. ASSERT_FALSE(svr.is_running());
  11612. });
  11613. svr.wait_until_ready();
  11614. Client cli(HOST, PORT);
  11615. auto res = cli.Get("/ip");
  11616. ASSERT_TRUE(res);
  11617. EXPECT_EQ(StatusCode::OK_200, res->status);
  11618. EXPECT_EQ(observed_xff, "");
  11619. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11620. observed_remote_addr == "127.0.0.1");
  11621. }
  11622. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11623. Server svr;
  11624. svr.set_trusted_proxies({"203.0.113.66"});
  11625. std::string observed_remote_addr;
  11626. std::string observed_xff;
  11627. svr.Get("/ip", [&](const Request &req, Response &res) {
  11628. observed_remote_addr = req.remote_addr;
  11629. observed_xff = req.get_header_value("X-Forwarded-For");
  11630. res.set_content("ok", "text/plain");
  11631. });
  11632. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11633. auto se = detail::scope_exit([&] {
  11634. svr.stop();
  11635. t.join();
  11636. ASSERT_FALSE(svr.is_running());
  11637. });
  11638. svr.wait_until_ready();
  11639. Client cli(HOST, PORT);
  11640. auto res =
  11641. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11642. ASSERT_TRUE(res);
  11643. EXPECT_EQ(StatusCode::OK_200, res->status);
  11644. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11645. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11646. }
  11647. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11648. Server svr;
  11649. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11650. std::string observed_remote_addr;
  11651. std::string observed_xff;
  11652. svr.Get("/ip", [&](const Request &req, Response &res) {
  11653. observed_remote_addr = req.remote_addr;
  11654. observed_xff = req.get_header_value("X-Forwarded-For");
  11655. res.set_content("ok", "text/plain");
  11656. });
  11657. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11658. auto se = detail::scope_exit([&] {
  11659. svr.stop();
  11660. t.join();
  11661. ASSERT_FALSE(svr.is_running());
  11662. });
  11663. svr.wait_until_ready();
  11664. Client cli(HOST, PORT);
  11665. auto res = cli.Get(
  11666. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11667. ASSERT_TRUE(res);
  11668. EXPECT_EQ(StatusCode::OK_200, res->status);
  11669. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11670. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11671. }
  11672. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11673. Server svr;
  11674. svr.set_trusted_proxies({"192.0.2.45"});
  11675. std::string observed_remote_addr;
  11676. std::string observed_xff;
  11677. svr.Get("/ip", [&](const Request &req, Response &res) {
  11678. observed_remote_addr = req.remote_addr;
  11679. observed_xff = req.get_header_value("X-Forwarded-For");
  11680. res.set_content("ok", "text/plain");
  11681. });
  11682. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11683. auto se = detail::scope_exit([&] {
  11684. svr.stop();
  11685. t.join();
  11686. ASSERT_FALSE(svr.is_running());
  11687. });
  11688. svr.wait_until_ready();
  11689. Client cli(HOST, PORT);
  11690. auto res =
  11691. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11692. ASSERT_TRUE(res);
  11693. EXPECT_EQ(StatusCode::OK_200, res->status);
  11694. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11695. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11696. }
  11697. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11698. Server svr;
  11699. svr.set_trusted_proxies({"192.0.2.45"});
  11700. std::string observed_remote_addr;
  11701. std::string observed_xff;
  11702. svr.Get("/ip", [&](const Request &req, Response &res) {
  11703. observed_remote_addr = req.remote_addr;
  11704. observed_xff = req.get_header_value("X-Forwarded-For");
  11705. res.set_content("ok", "text/plain");
  11706. });
  11707. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11708. auto se = detail::scope_exit([&] {
  11709. svr.stop();
  11710. t.join();
  11711. ASSERT_FALSE(svr.is_running());
  11712. });
  11713. svr.wait_until_ready();
  11714. Client cli(HOST, PORT);
  11715. auto res = cli.Get(
  11716. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11717. ASSERT_TRUE(res);
  11718. EXPECT_EQ(StatusCode::OK_200, res->status);
  11719. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11720. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11721. }
  11722. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11723. Server svr;
  11724. svr.set_trusted_proxies({"192.0.2.45"});
  11725. std::string observed_remote_addr;
  11726. std::string observed_xff;
  11727. svr.Get("/ip", [&](const Request &req, Response &res) {
  11728. observed_remote_addr = req.remote_addr;
  11729. observed_xff = req.get_header_value("X-Forwarded-For");
  11730. res.set_content("ok", "text/plain");
  11731. });
  11732. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11733. auto se = detail::scope_exit([&] {
  11734. svr.stop();
  11735. t.join();
  11736. ASSERT_FALSE(svr.is_running());
  11737. });
  11738. svr.wait_until_ready();
  11739. std::string raw_req =
  11740. "GET /ip HTTP/1.1\r\n"
  11741. "Host: localhost\r\n"
  11742. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11743. "Connection: close\r\n"
  11744. "\r\n";
  11745. std::string out;
  11746. ASSERT_TRUE(send_request(5, raw_req, &out));
  11747. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11748. // Header parser trims surrounding whitespace of the header value
  11749. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11750. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11751. }
  11752. #ifndef _WIN32
  11753. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11754. Server svr;
  11755. svr.Post("/post", [&](const Request &req, Response &res) {
  11756. res.set_content(req.body, "text/plain");
  11757. });
  11758. svr.Put("/put", [&](const Request &req, Response &res) {
  11759. res.set_content(req.body, "text/plain");
  11760. });
  11761. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11762. res.set_content(req.body, "text/plain");
  11763. });
  11764. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11765. res.set_content(req.body, "text/plain");
  11766. });
  11767. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11768. auto se = detail::scope_exit([&] {
  11769. svr.stop();
  11770. t.join();
  11771. ASSERT_FALSE(svr.is_running());
  11772. });
  11773. svr.wait_until_ready();
  11774. std::string resp;
  11775. // POST without Content-Length
  11776. ASSERT_TRUE(send_request(5,
  11777. "POST /post HTTP/1.1\r\n"
  11778. "Host: localhost\r\n"
  11779. "Connection: close\r\n"
  11780. "\r\n",
  11781. &resp));
  11782. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11783. // PUT without Content-Length
  11784. resp.clear();
  11785. ASSERT_TRUE(send_request(5,
  11786. "PUT /put HTTP/1.1\r\n"
  11787. "Host: localhost\r\n"
  11788. "Connection: close\r\n"
  11789. "\r\n",
  11790. &resp));
  11791. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11792. // PATCH without Content-Length
  11793. resp.clear();
  11794. ASSERT_TRUE(send_request(5,
  11795. "PATCH /patch HTTP/1.1\r\n"
  11796. "Host: localhost\r\n"
  11797. "Connection: close\r\n"
  11798. "\r\n",
  11799. &resp));
  11800. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11801. // DELETE without Content-Length
  11802. resp.clear();
  11803. ASSERT_TRUE(send_request(5,
  11804. "DELETE /delete HTTP/1.1\r\n"
  11805. "Host: localhost\r\n"
  11806. "Connection: close\r\n"
  11807. "\r\n",
  11808. &resp));
  11809. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11810. }
  11811. #endif
  11812. //==============================================================================
  11813. // open_stream() Tests
  11814. //==============================================================================
  11815. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11816. std::string result;
  11817. char buf[8192];
  11818. ssize_t n;
  11819. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11820. result.append(buf, static_cast<size_t>(n));
  11821. }
  11822. return result;
  11823. }
  11824. // Mock stream for unit tests
  11825. class MockStream : public Stream {
  11826. public:
  11827. std::string data;
  11828. size_t pos = 0;
  11829. ssize_t error_after = -1; // -1 = no error
  11830. explicit MockStream(const std::string &d, ssize_t err = -1)
  11831. : data(d), error_after(err) {}
  11832. bool is_readable() const override { return true; }
  11833. bool wait_readable() const override { return true; }
  11834. bool wait_writable() const override { return true; }
  11835. ssize_t read(char *ptr, size_t size) override {
  11836. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11837. if (pos >= data.size()) return 0;
  11838. size_t limit =
  11839. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11840. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11841. std::memcpy(ptr, data.data() + pos, to_read);
  11842. pos += to_read;
  11843. return static_cast<ssize_t>(to_read);
  11844. }
  11845. ssize_t write(const char *, size_t) override { return -1; }
  11846. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11847. ip = "127.0.0.1";
  11848. port = 0;
  11849. }
  11850. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11851. ip = "127.0.0.1";
  11852. port = 0;
  11853. }
  11854. socket_t socket() const override { return INVALID_SOCKET; }
  11855. time_t duration() const override { return 0; }
  11856. };
  11857. TEST(StreamHandleTest, Basic) {
  11858. ClientImpl::StreamHandle handle;
  11859. EXPECT_FALSE(handle.is_valid());
  11860. handle.response = detail::make_unique<Response>();
  11861. handle.error = Error::Connection;
  11862. EXPECT_FALSE(handle.is_valid());
  11863. handle.error = Error::Success;
  11864. EXPECT_TRUE(handle.is_valid());
  11865. }
  11866. TEST(BodyReaderTest, Basic) {
  11867. MockStream stream("Hello, World!");
  11868. detail::BodyReader reader;
  11869. reader.stream = &stream;
  11870. reader.content_length = 13;
  11871. char buf[32];
  11872. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11873. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11874. EXPECT_TRUE(reader.eof);
  11875. }
  11876. TEST(BodyReaderTest, NoStream) {
  11877. detail::BodyReader reader;
  11878. char buf[32];
  11879. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11880. EXPECT_EQ(Error::Connection, reader.last_error);
  11881. }
  11882. TEST(BodyReaderTest, Error) {
  11883. MockStream stream("Hello, World!", 5);
  11884. detail::BodyReader reader;
  11885. reader.stream = &stream;
  11886. reader.content_length = 13;
  11887. char buf[32];
  11888. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11889. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11890. EXPECT_EQ(Error::Read, reader.last_error);
  11891. }
  11892. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11893. // Mock-based StreamHandle tests relying on private internals are removed.
  11894. class OpenStreamTest : public ::testing::Test {
  11895. protected:
  11896. void SetUp() override {
  11897. svr_.Get("/hello", [](const Request &, Response &res) {
  11898. res.set_content("Hello World!", "text/plain");
  11899. });
  11900. svr_.Get("/large", [](const Request &, Response &res) {
  11901. res.set_content(std::string(10000, 'X'), "text/plain");
  11902. });
  11903. svr_.Get("/chunked", [](const Request &, Response &res) {
  11904. res.set_chunked_content_provider("text/plain",
  11905. [](size_t offset, DataSink &sink) {
  11906. if (offset < 15) {
  11907. sink.write("chunk", 5);
  11908. return true;
  11909. }
  11910. sink.done();
  11911. return true;
  11912. });
  11913. });
  11914. svr_.Get("/compressible", [](const Request &, Response &res) {
  11915. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11916. DataSink &sink) {
  11917. if (offset < 100 * 1024) {
  11918. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11919. sink.write(chunk.data(), chunk.size());
  11920. return true;
  11921. }
  11922. sink.done();
  11923. return true;
  11924. });
  11925. });
  11926. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11927. [](const Request & /*req*/, Response &res) {
  11928. auto i = new int(0);
  11929. res.set_header("Trailer", "Content-Length, X-Allowed");
  11930. res.set_chunked_content_provider(
  11931. "text/plain",
  11932. [i](size_t /*offset*/, DataSink &sink) {
  11933. switch (*i) {
  11934. case 0: sink.os << "123"; break;
  11935. case 1: sink.os << "456"; break;
  11936. case 2: sink.os << "789"; break;
  11937. case 3: {
  11938. sink.done_with_trailer(
  11939. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11940. } break;
  11941. }
  11942. (*i)++;
  11943. return true;
  11944. },
  11945. [i](bool success) {
  11946. EXPECT_TRUE(success);
  11947. delete i;
  11948. });
  11949. });
  11950. // Echo headers endpoint for header-related tests
  11951. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11952. std::string body;
  11953. for (const auto &h : req.headers) {
  11954. body.append(h.first);
  11955. body.push_back(':');
  11956. body.append(h.second);
  11957. body.push_back('\n');
  11958. }
  11959. res.set_content(body, "text/plain");
  11960. });
  11961. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11962. std::string body;
  11963. for (const auto &h : req.headers) {
  11964. body.append(h.first);
  11965. body.push_back(':');
  11966. body.append(h.second);
  11967. body.push_back('\n');
  11968. }
  11969. res.set_content(body, "text/plain");
  11970. });
  11971. port_ = svr_.bind_to_any_port("127.0.0.1");
  11972. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11973. svr_.wait_until_ready();
  11974. }
  11975. void TearDown() override {
  11976. svr_.stop();
  11977. if (thread_.joinable()) thread_.join();
  11978. }
  11979. Server svr_;
  11980. std::thread thread_;
  11981. int port_ = 0;
  11982. };
  11983. TEST_F(OpenStreamTest, Basic) {
  11984. Client cli("127.0.0.1", port_);
  11985. auto handle = cli.open_stream("GET", "/hello");
  11986. EXPECT_TRUE(handle.is_valid());
  11987. EXPECT_EQ("Hello World!", read_all(handle));
  11988. }
  11989. TEST_F(OpenStreamTest, SmallBuffer) {
  11990. Client cli("127.0.0.1", port_);
  11991. auto handle = cli.open_stream("GET", "/hello");
  11992. std::string result;
  11993. char buf[4];
  11994. ssize_t n;
  11995. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11996. result.append(buf, static_cast<size_t>(n));
  11997. EXPECT_EQ("Hello World!", result);
  11998. }
  11999. TEST_F(OpenStreamTest, DefaultHeaders) {
  12000. Client cli("127.0.0.1", port_);
  12001. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12002. {
  12003. auto handle = cli.open_stream("GET", "/echo-headers");
  12004. ASSERT_TRUE(handle.is_valid());
  12005. auto body = read_all(handle);
  12006. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12007. std::string::npos);
  12008. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12009. std::string::npos);
  12010. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12011. }
  12012. // open_stream POST with body and no explicit content_type should NOT add
  12013. // text/plain Content-Type (behavior differs from non-streaming path), but
  12014. // should include Content-Length
  12015. {
  12016. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12017. ASSERT_TRUE(handle.is_valid());
  12018. auto body = read_all(handle);
  12019. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12020. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12021. }
  12022. // open_stream POST with explicit Content-Type should preserve it
  12023. {
  12024. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12025. {{"Content-Type", "application/custom"}},
  12026. "{}", "application/custom");
  12027. ASSERT_TRUE(handle.is_valid());
  12028. auto body = read_all(handle);
  12029. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12030. }
  12031. // User-specified User-Agent must not be overwritten for stream API
  12032. {
  12033. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12034. {{"User-Agent", "MyAgent/1.2"}});
  12035. ASSERT_TRUE(handle.is_valid());
  12036. auto body = read_all(handle);
  12037. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12038. }
  12039. }
  12040. TEST_F(OpenStreamTest, Large) {
  12041. Client cli("127.0.0.1", port_);
  12042. auto handle = cli.open_stream("GET", "/large");
  12043. EXPECT_EQ(10000u, read_all(handle).size());
  12044. }
  12045. TEST_F(OpenStreamTest, ConnectionError) {
  12046. Client cli("127.0.0.1", 9999);
  12047. auto handle = cli.open_stream("GET", "/hello");
  12048. EXPECT_FALSE(handle.is_valid());
  12049. }
  12050. TEST_F(OpenStreamTest, Chunked) {
  12051. Client cli("127.0.0.1", port_);
  12052. auto handle = cli.open_stream("GET", "/chunked");
  12053. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12054. "Transfer-Encoding") == "chunked");
  12055. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12056. }
  12057. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12058. Client cli("127.0.0.1", port_);
  12059. auto handle =
  12060. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12061. ASSERT_TRUE(handle.is_valid());
  12062. // Consume body to allow trailers to be received/parsed
  12063. auto body = read_all(handle);
  12064. // Explicitly parse trailers (ensure trailers are available for assertion)
  12065. handle.parse_trailers_if_needed();
  12066. EXPECT_EQ(std::string("123456789"), body);
  12067. // The response should include a Trailer header declaring both names
  12068. ASSERT_TRUE(handle.response);
  12069. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12070. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12071. handle.response->get_header_value("Trailer"));
  12072. // Prohibited trailer must not be present
  12073. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12074. // Allowed trailer should be present
  12075. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12076. EXPECT_EQ(std::string("yes"),
  12077. handle.response->get_trailer_value("X-Allowed"));
  12078. // Verify trailers are NOT present as regular headers
  12079. EXPECT_EQ(std::string(""),
  12080. handle.response->get_header_value("Content-Length"));
  12081. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12082. }
  12083. static std::thread serve_single_response(std::promise<int> &port_promise,
  12084. const std::string &response) {
  12085. return std::thread([&port_promise, response] {
  12086. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12087. default_socket_options(srv);
  12088. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12089. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12090. sockaddr_in addr{};
  12091. addr.sin_family = AF_INET;
  12092. addr.sin_port = htons(0); // Let OS assign a free port
  12093. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12094. int opt = 1;
  12095. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12096. #ifdef _WIN32
  12097. reinterpret_cast<const char *>(&opt),
  12098. #else
  12099. &opt,
  12100. #endif
  12101. sizeof(opt));
  12102. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12103. ::listen(srv, 1) != 0) {
  12104. port_promise.set_value(-1);
  12105. detail::close_socket(srv);
  12106. return;
  12107. }
  12108. socklen_t addr_len = sizeof(addr);
  12109. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12110. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12111. sockaddr_in cli_addr{};
  12112. socklen_t cli_len = sizeof(cli_addr);
  12113. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12114. if (cli != INVALID_SOCKET) {
  12115. // Read the complete HTTP request (until the blank line that terminates
  12116. // headers) before sending the response. If the server closes the socket
  12117. // while the client's request data is still unread in the kernel receive
  12118. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12119. // connection on both sides: it discards the client's receive buffer
  12120. // (which already holds our response) and causes any in-progress write on
  12121. // the client to fail with ECONNRESET. Reading all request data first
  12122. // ensures close() emits a graceful FIN.
  12123. {
  12124. char rbuf[256];
  12125. std::string req;
  12126. while (req.find("\r\n\r\n") == std::string::npos) {
  12127. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12128. if (n <= 0) { break; }
  12129. req.append(rbuf, static_cast<size_t>(n));
  12130. }
  12131. }
  12132. ::send(cli,
  12133. #ifdef _WIN32
  12134. static_cast<const char *>(response.c_str()),
  12135. static_cast<int>(response.size()),
  12136. #else
  12137. response.c_str(), response.size(),
  12138. #endif
  12139. 0);
  12140. detail::close_socket(cli);
  12141. }
  12142. detail::close_socket(srv);
  12143. });
  12144. }
  12145. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12146. #ifndef _WIN32
  12147. signal(SIGPIPE, SIG_IGN);
  12148. #endif
  12149. std::promise<int> port_promise;
  12150. auto port_future = port_promise.get_future();
  12151. auto server_thread =
  12152. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12153. "Content-Type: text/plain\r\n"
  12154. "Content-Length: not-a-number\r\n"
  12155. "Connection: close\r\n"
  12156. "\r\n"
  12157. "hello");
  12158. auto port = port_future.get();
  12159. ASSERT_GT(port, 0);
  12160. Client cli("127.0.0.1", port);
  12161. auto handle = cli.open_stream("GET", "/");
  12162. EXPECT_FALSE(handle.is_valid());
  12163. server_thread.join();
  12164. }
  12165. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12166. #ifndef _WIN32
  12167. signal(SIGPIPE, SIG_IGN);
  12168. #endif
  12169. std::promise<int> port_promise;
  12170. auto port_future = port_promise.get_future();
  12171. auto server_thread = serve_single_response(
  12172. port_promise, "HTTP/1.1 200 OK\r\n"
  12173. "Content-Type: text/plain\r\n"
  12174. "Content-Length: 99999999999999999999999999\r\n"
  12175. "Connection: close\r\n"
  12176. "\r\n"
  12177. "hello");
  12178. auto port = port_future.get();
  12179. ASSERT_GT(port, 0);
  12180. // Before the fix, std::stoull would throw std::out_of_range here and
  12181. // crash the process. After the fix, strtoull silently clamps to
  12182. // ULLONG_MAX so the stream opens without crashing. The important thing
  12183. // is that the process does NOT terminate.
  12184. Client cli("127.0.0.1", port);
  12185. auto handle = cli.open_stream("GET", "/");
  12186. EXPECT_TRUE(handle.is_valid());
  12187. server_thread.join();
  12188. }
  12189. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12190. TEST_F(OpenStreamTest, Gzip) {
  12191. Client cli("127.0.0.1", port_);
  12192. auto handle = cli.open_stream("GET", "/compressible", {},
  12193. {{"Accept-Encoding", "gzip"}});
  12194. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12195. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12196. }
  12197. #endif
  12198. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12199. TEST_F(OpenStreamTest, Brotli) {
  12200. Client cli("127.0.0.1", port_);
  12201. auto handle =
  12202. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12203. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12204. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12205. }
  12206. #endif
  12207. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12208. TEST_F(OpenStreamTest, Zstd) {
  12209. Client cli("127.0.0.1", port_);
  12210. auto handle = cli.open_stream("GET", "/compressible", {},
  12211. {{"Accept-Encoding", "zstd"}});
  12212. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12213. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12214. }
  12215. #endif
  12216. #ifdef CPPHTTPLIB_SSL_ENABLED
  12217. class SSLOpenStreamTest : public ::testing::Test {
  12218. protected:
  12219. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12220. void SetUp() override {
  12221. svr_.Get("/hello", [](const Request &, Response &res) {
  12222. res.set_content("Hello SSL World!", "text/plain");
  12223. });
  12224. svr_.Get("/chunked", [](const Request &, Response &res) {
  12225. res.set_chunked_content_provider("text/plain",
  12226. [](size_t offset, DataSink &sink) {
  12227. if (offset < 15) {
  12228. sink.write("chunk", 5);
  12229. return true;
  12230. }
  12231. sink.done();
  12232. return true;
  12233. });
  12234. });
  12235. svr_.Post("/echo", [](const Request &req, Response &res) {
  12236. res.set_content(req.body, req.get_header_value("Content-Type"));
  12237. });
  12238. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12239. std::string body = req.body;
  12240. res.set_chunked_content_provider(
  12241. "text/plain", [body](size_t offset, DataSink &sink) {
  12242. if (offset < body.size()) {
  12243. sink.write(body.data() + offset, body.size() - offset);
  12244. }
  12245. sink.done();
  12246. return true;
  12247. });
  12248. });
  12249. port_ = svr_.bind_to_any_port("127.0.0.1");
  12250. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12251. svr_.wait_until_ready();
  12252. }
  12253. void TearDown() override {
  12254. svr_.stop();
  12255. if (thread_.joinable()) thread_.join();
  12256. }
  12257. SSLServer svr_;
  12258. std::thread thread_;
  12259. int port_ = 0;
  12260. };
  12261. TEST_F(SSLOpenStreamTest, Basic) {
  12262. SSLClient cli("127.0.0.1", port_);
  12263. cli.enable_server_certificate_verification(false);
  12264. auto handle = cli.open_stream("GET", "/hello");
  12265. ASSERT_TRUE(handle.is_valid());
  12266. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12267. }
  12268. TEST_F(SSLOpenStreamTest, Chunked) {
  12269. SSLClient cli("127.0.0.1", port_);
  12270. cli.enable_server_certificate_verification(false);
  12271. auto handle = cli.open_stream("GET", "/chunked");
  12272. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12273. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12274. "Transfer-Encoding") == "chunked");
  12275. auto body = read_all(handle);
  12276. EXPECT_EQ("chunkchunkchunk", body);
  12277. }
  12278. TEST_F(SSLOpenStreamTest, Post) {
  12279. SSLClient cli("127.0.0.1", port_);
  12280. cli.enable_server_certificate_verification(false);
  12281. auto handle =
  12282. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12283. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12284. EXPECT_EQ(200, handle.response->status);
  12285. auto body = read_all(handle);
  12286. EXPECT_EQ("Hello SSL POST", body);
  12287. }
  12288. TEST_F(SSLOpenStreamTest, PostChunked) {
  12289. SSLClient cli("127.0.0.1", port_);
  12290. cli.enable_server_certificate_verification(false);
  12291. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12292. "Chunked SSL Data", "text/plain");
  12293. ASSERT_TRUE(handle.is_valid());
  12294. EXPECT_EQ(200, handle.response->status);
  12295. auto body = read_all(handle);
  12296. EXPECT_EQ("Chunked SSL Data", body);
  12297. }
  12298. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12299. // Content-Length is terminated by the server closing the connection. When the
  12300. // SSL peer sends a close_notify after the body, the client must treat it as a
  12301. // clean EOF and return a successful response rather than an error.
  12302. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12304. ASSERT_TRUE(svr.is_valid());
  12305. svr.set_keep_alive_max_count(1);
  12306. const std::string expected_body = "Hello from connection-close response!";
  12307. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12308. res.set_content_provider("text/plain",
  12309. [&](size_t offset, DataSink &sink) -> bool {
  12310. if (offset < expected_body.size()) {
  12311. sink.write(expected_body.data() + offset,
  12312. expected_body.size() - offset);
  12313. }
  12314. sink.done();
  12315. return true;
  12316. });
  12317. });
  12318. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12319. auto se = detail::scope_exit([&] {
  12320. svr.stop();
  12321. listen_thread.join();
  12322. ASSERT_FALSE(svr.is_running());
  12323. });
  12324. svr.wait_until_ready();
  12325. SSLClient cli(HOST, PORT);
  12326. cli.enable_server_certificate_verification(false);
  12327. auto res = cli.Get("/no-content-length");
  12328. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12329. EXPECT_EQ(StatusCode::OK_200, res->status);
  12330. EXPECT_EQ(expected_body, res->body);
  12331. }
  12332. #endif // CPPHTTPLIB_SSL_ENABLED
  12333. //==============================================================================
  12334. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12335. // results for various scenarios.
  12336. //==============================================================================
  12337. TEST(ParityTest, GetVsOpenStream) {
  12338. Server svr;
  12339. const std::string path = "/parity";
  12340. const std::string content = "Parity test content: hello world";
  12341. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12342. res.set_content(content, "text/plain");
  12343. });
  12344. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12345. auto se = detail::scope_exit([&] {
  12346. svr.stop();
  12347. t.join();
  12348. ASSERT_FALSE(svr.is_running());
  12349. });
  12350. svr.wait_until_ready();
  12351. Client cli(HOST, PORT);
  12352. // Non-stream path
  12353. auto r1 = cli.Get(path);
  12354. ASSERT_TRUE(r1);
  12355. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12356. // Stream path
  12357. auto h = cli.open_stream("GET", path);
  12358. ASSERT_TRUE(h.is_valid());
  12359. EXPECT_EQ(r1->body, read_all(h));
  12360. }
  12361. // Helper to compress data with provided compressor type T
  12362. template <typename Compressor>
  12363. static std::string compress_payload_for_parity(const std::string &in) {
  12364. std::string out;
  12365. Compressor compressor;
  12366. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12367. [&](const char *data, size_t n) {
  12368. out.append(data, n);
  12369. return true;
  12370. });
  12371. EXPECT_TRUE(ok);
  12372. return out;
  12373. }
  12374. // Helper function for compression parity tests
  12375. template <typename Compressor>
  12376. static void test_compression_parity(const std::string &original,
  12377. const std::string &path,
  12378. const std::string &encoding) {
  12379. const std::string compressed =
  12380. compress_payload_for_parity<Compressor>(original);
  12381. Server svr;
  12382. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12383. res.set_content(compressed, "application/octet-stream");
  12384. res.set_header("Content-Encoding", encoding);
  12385. });
  12386. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12387. auto se = detail::scope_exit([&] {
  12388. svr.stop();
  12389. t.join();
  12390. ASSERT_FALSE(svr.is_running());
  12391. });
  12392. svr.wait_until_ready();
  12393. Client cli(HOST, PORT);
  12394. // Non-streaming
  12395. {
  12396. auto res = cli.Get(path);
  12397. ASSERT_TRUE(res);
  12398. EXPECT_EQ(StatusCode::OK_200, res->status);
  12399. EXPECT_EQ(original, res->body);
  12400. }
  12401. // Streaming
  12402. {
  12403. auto h = cli.open_stream("GET", path);
  12404. ASSERT_TRUE(h.is_valid());
  12405. EXPECT_EQ(original, read_all(h));
  12406. }
  12407. }
  12408. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12409. TEST(ParityTest, Gzip) {
  12410. test_compression_parity<detail::gzip_compressor>(
  12411. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12412. }
  12413. #endif
  12414. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12415. TEST(ParityTest, Brotli) {
  12416. test_compression_parity<detail::brotli_compressor>(
  12417. "Hello, brotli parity test payload", "/parity-br", "br");
  12418. }
  12419. #endif
  12420. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12421. TEST(ParityTest, Zstd) {
  12422. test_compression_parity<detail::zstd_compressor>(
  12423. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12424. }
  12425. #endif
  12426. //==============================================================================
  12427. // New Stream API Tests
  12428. //==============================================================================
  12429. inline std::string read_body(httplib::stream::Result &result) {
  12430. std::string body;
  12431. while (result.next()) {
  12432. body.append(result.data(), result.size());
  12433. }
  12434. return body;
  12435. }
  12436. TEST(ClientConnectionTest, Basic) {
  12437. httplib::ClientConnection conn;
  12438. EXPECT_FALSE(conn.is_open());
  12439. conn.sock = 1;
  12440. EXPECT_TRUE(conn.is_open());
  12441. httplib::ClientConnection conn2(std::move(conn));
  12442. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12443. conn2.sock = INVALID_SOCKET;
  12444. }
  12445. // Unified test server for all stream::* tests
  12446. class StreamApiTest : public ::testing::Test {
  12447. protected:
  12448. void SetUp() override {
  12449. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12450. res.set_content("Hello World!", "text/plain");
  12451. });
  12452. svr_.Get("/echo-params",
  12453. [](const httplib::Request &req, httplib::Response &res) {
  12454. std::string r;
  12455. for (const auto &p : req.params) {
  12456. if (!r.empty()) r += "&";
  12457. r += p.first + "=" + p.second;
  12458. }
  12459. res.set_content(r, "text/plain");
  12460. });
  12461. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12462. res.set_content(req.body, req.get_header_value("Content-Type"));
  12463. });
  12464. svr_.Post("/echo-headers",
  12465. [](const httplib::Request &req, httplib::Response &res) {
  12466. std::string r;
  12467. for (const auto &h : req.headers)
  12468. r += h.first + ": " + h.second + "\n";
  12469. res.set_content(r, "text/plain");
  12470. });
  12471. svr_.Post("/echo-params",
  12472. [](const httplib::Request &req, httplib::Response &res) {
  12473. std::string r = "params:";
  12474. for (const auto &p : req.params)
  12475. r += p.first + "=" + p.second + ";";
  12476. res.set_content(r + " body:" + req.body, "text/plain");
  12477. });
  12478. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12479. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12480. });
  12481. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12482. res.set_content("PUT:" + req.body, "text/plain");
  12483. });
  12484. svr_.Patch("/echo",
  12485. [](const httplib::Request &req, httplib::Response &res) {
  12486. res.set_content("PATCH:" + req.body, "text/plain");
  12487. });
  12488. svr_.Delete(
  12489. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12490. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12491. "text/plain");
  12492. });
  12493. svr_.Get("/head-test",
  12494. [](const httplib::Request &, httplib::Response &res) {
  12495. res.set_content("body for HEAD", "text/plain");
  12496. });
  12497. svr_.Options("/options",
  12498. [](const httplib::Request &, httplib::Response &res) {
  12499. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12500. });
  12501. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12502. svr_.wait_until_ready();
  12503. }
  12504. void TearDown() override {
  12505. svr_.stop();
  12506. if (thread_.joinable()) thread_.join();
  12507. }
  12508. httplib::Server svr_;
  12509. std::thread thread_;
  12510. };
  12511. // stream::Get tests
  12512. TEST_F(StreamApiTest, GetBasic) {
  12513. httplib::Client cli(HOST, PORT);
  12514. auto result = httplib::stream::Get(cli, "/hello");
  12515. ASSERT_TRUE(result.is_valid());
  12516. EXPECT_EQ(200, result.status());
  12517. EXPECT_EQ("Hello World!", read_body(result));
  12518. }
  12519. TEST_F(StreamApiTest, GetWithParams) {
  12520. httplib::Client cli(HOST, PORT);
  12521. httplib::Params params{{"foo", "bar"}};
  12522. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12523. ASSERT_TRUE(result.is_valid());
  12524. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12525. }
  12526. TEST_F(StreamApiTest, GetConnectionError) {
  12527. httplib::Client cli(HOST, 9999);
  12528. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12529. }
  12530. TEST_F(StreamApiTest, Get404) {
  12531. httplib::Client cli(HOST, PORT);
  12532. auto result = httplib::stream::Get(cli, "/nonexistent");
  12533. EXPECT_TRUE(result.is_valid());
  12534. EXPECT_EQ(404, result.status());
  12535. }
  12536. // stream::Post tests
  12537. TEST_F(StreamApiTest, PostBasic) {
  12538. httplib::Client cli(HOST, PORT);
  12539. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12540. "application/json");
  12541. ASSERT_TRUE(result.is_valid());
  12542. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12543. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12544. }
  12545. TEST_F(StreamApiTest, PostWithHeaders) {
  12546. httplib::Client cli(HOST, PORT);
  12547. httplib::Headers headers{{"X-Custom", "value"}};
  12548. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12549. "text/plain");
  12550. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12551. }
  12552. TEST_F(StreamApiTest, PostWithParams) {
  12553. httplib::Client cli(HOST, PORT);
  12554. httplib::Params params{{"k", "v"}};
  12555. auto result =
  12556. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12557. auto body = read_body(result);
  12558. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12559. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12560. }
  12561. TEST_F(StreamApiTest, PostLarge) {
  12562. httplib::Client cli(HOST, PORT);
  12563. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12564. size_t total = 0;
  12565. while (result.next()) {
  12566. total += result.size();
  12567. }
  12568. EXPECT_EQ(100u * 1024u, total);
  12569. }
  12570. // stream::Put/Patch tests
  12571. TEST_F(StreamApiTest, PutAndPatch) {
  12572. httplib::Client cli(HOST, PORT);
  12573. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12574. EXPECT_EQ("PUT:test", read_body(put));
  12575. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12576. EXPECT_EQ("PATCH:test", read_body(patch));
  12577. }
  12578. // stream::Delete tests
  12579. TEST_F(StreamApiTest, Delete) {
  12580. httplib::Client cli(HOST, PORT);
  12581. auto del1 = httplib::stream::Delete(cli, "/resource");
  12582. EXPECT_EQ("Deleted", read_body(del1));
  12583. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12584. EXPECT_EQ("Deleted:data", read_body(del2));
  12585. }
  12586. // stream::Head/Options tests
  12587. TEST_F(StreamApiTest, HeadAndOptions) {
  12588. httplib::Client cli(HOST, PORT);
  12589. auto head = httplib::stream::Head(cli, "/head-test");
  12590. EXPECT_TRUE(head.is_valid());
  12591. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12592. auto opts = httplib::stream::Options(cli, "/options");
  12593. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12594. }
  12595. // SSL stream::* tests
  12596. #ifdef CPPHTTPLIB_SSL_ENABLED
  12597. class SSLStreamApiTest : public ::testing::Test {
  12598. protected:
  12599. void SetUp() override {
  12600. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12601. res.set_content("Hello SSL!", "text/plain");
  12602. });
  12603. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12604. res.set_content(req.body, "text/plain");
  12605. });
  12606. port_ = svr_.bind_to_any_port("127.0.0.1");
  12607. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12608. svr_.wait_until_ready();
  12609. }
  12610. void TearDown() override {
  12611. svr_.stop();
  12612. if (thread_.joinable()) thread_.join();
  12613. }
  12614. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12615. std::thread thread_;
  12616. int port_ = 0;
  12617. };
  12618. TEST_F(SSLStreamApiTest, GetAndPost) {
  12619. httplib::SSLClient cli("127.0.0.1", port_);
  12620. cli.enable_server_certificate_verification(false);
  12621. auto get = httplib::stream::Get(cli, "/hello");
  12622. EXPECT_EQ("Hello SSL!", read_body(get));
  12623. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12624. EXPECT_EQ("test", read_body(post));
  12625. }
  12626. #endif
  12627. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12628. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12629. // BodyReader
  12630. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12631. // Test that read timeout during streaming is detected
  12632. // Use a large content-length response where server delays mid-stream
  12633. Server svr;
  12634. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12635. // Send a large response with delay in the middle
  12636. res.set_content_provider(
  12637. 1000, // content_length
  12638. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12639. if (offset < 100) {
  12640. // Send first 100 bytes immediately
  12641. std::string data(100, 'A');
  12642. sink.write(data.c_str(), data.size());
  12643. return true;
  12644. }
  12645. // Then delay longer than client timeout
  12646. std::this_thread::sleep_for(std::chrono::seconds(3));
  12647. std::string data(900, 'B');
  12648. sink.write(data.c_str(), data.size());
  12649. return true;
  12650. });
  12651. });
  12652. auto port = 8091;
  12653. std::thread t([&]() { svr.listen("localhost", port); });
  12654. svr.wait_until_ready();
  12655. Client cli("localhost", port);
  12656. cli.set_read_timeout(1, 0); // 1 second timeout
  12657. auto handle = cli.open_stream("GET", "/slow-stream");
  12658. ASSERT_TRUE(handle.is_valid());
  12659. char buf[256];
  12660. ssize_t total = 0;
  12661. ssize_t n;
  12662. bool got_error = false;
  12663. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12664. total += n;
  12665. }
  12666. if (n < 0) {
  12667. got_error = true;
  12668. // Should be timeout or read error
  12669. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12670. handle.get_read_error() == Error::Read)
  12671. << "Actual error: " << to_string(handle.get_read_error());
  12672. }
  12673. // Either we got an error, or we got less data than expected
  12674. EXPECT_TRUE(got_error || total < 1000)
  12675. << "Expected timeout but got all " << total << " bytes";
  12676. svr.stop();
  12677. t.join();
  12678. }
  12679. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12680. // Test connection closed detection via BodyReader
  12681. Server svr;
  12682. std::atomic<bool> close_now{false};
  12683. svr.Get("/will-close", [&](const Request &, Response &res) {
  12684. res.set_content_provider(
  12685. 10000, // Large content_length that we won't fully send
  12686. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12687. if (offset < 100) {
  12688. std::string data(100, 'X');
  12689. sink.write(data.c_str(), data.size());
  12690. return true;
  12691. }
  12692. // Wait for signal then abort
  12693. while (!close_now) {
  12694. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12695. }
  12696. return false; // Abort - server will close connection
  12697. });
  12698. });
  12699. auto port = 8092;
  12700. std::thread t([&]() { svr.listen("localhost", port); });
  12701. svr.wait_until_ready();
  12702. Client cli("localhost", port);
  12703. auto handle = cli.open_stream("GET", "/will-close");
  12704. ASSERT_TRUE(handle.is_valid());
  12705. char buf[256];
  12706. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12707. EXPECT_GT(n, 0) << "First read should succeed";
  12708. // Signal server to close
  12709. close_now = true;
  12710. // Keep reading until error or EOF
  12711. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12712. // Keep reading
  12713. }
  12714. // Should get an error since content_length wasn't satisfied
  12715. if (n < 0) {
  12716. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12717. handle.get_read_error() == Error::Read)
  12718. << "Actual error: " << to_string(handle.get_read_error());
  12719. }
  12720. svr.stop();
  12721. t.join();
  12722. }
  12723. #ifdef CPPHTTPLIB_SSL_ENABLED
  12724. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12725. // Test that read timeout during SSL streaming is detected
  12726. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12727. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12728. res.set_content_provider(
  12729. 1000, "text/plain",
  12730. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12731. if (offset < 100) {
  12732. std::string data(100, 'A');
  12733. sink.write(data.c_str(), data.size());
  12734. return true;
  12735. }
  12736. std::this_thread::sleep_for(std::chrono::seconds(3));
  12737. std::string data(900, 'B');
  12738. sink.write(data.c_str(), data.size());
  12739. return true;
  12740. });
  12741. });
  12742. auto port = 8093;
  12743. std::thread t([&]() { svr.listen("localhost", port); });
  12744. svr.wait_until_ready();
  12745. SSLClient cli("localhost", port);
  12746. cli.enable_server_certificate_verification(false);
  12747. cli.set_read_timeout(1, 0); // 1 second timeout
  12748. auto handle = cli.open_stream("GET", "/slow-stream");
  12749. ASSERT_TRUE(handle.is_valid());
  12750. char buf[256];
  12751. ssize_t total = 0;
  12752. ssize_t n;
  12753. bool got_error = false;
  12754. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12755. total += n;
  12756. }
  12757. if (n < 0) {
  12758. got_error = true;
  12759. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12760. handle.get_read_error() == Error::Read)
  12761. << "Actual error: " << to_string(handle.get_read_error());
  12762. }
  12763. EXPECT_TRUE(got_error || total < 1000)
  12764. << "Expected timeout but got all " << total << " bytes";
  12765. svr.stop();
  12766. t.join();
  12767. }
  12768. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12769. // Test SSL connection closed detection
  12770. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12771. std::atomic<bool> close_now{false};
  12772. svr.Get("/will-close", [&](const Request &, Response &res) {
  12773. res.set_content_provider(
  12774. 10000, "text/plain",
  12775. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12776. if (offset < 100) {
  12777. std::string data(100, 'X');
  12778. sink.write(data.c_str(), data.size());
  12779. return true;
  12780. }
  12781. while (!close_now) {
  12782. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12783. }
  12784. return false;
  12785. });
  12786. });
  12787. auto port = 8094;
  12788. std::thread t([&]() { svr.listen("localhost", port); });
  12789. svr.wait_until_ready();
  12790. SSLClient cli("localhost", port);
  12791. cli.enable_server_certificate_verification(false);
  12792. auto handle = cli.open_stream("GET", "/will-close");
  12793. ASSERT_TRUE(handle.is_valid());
  12794. char buf[256];
  12795. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12796. EXPECT_GT(n, 0);
  12797. // Signal server to close
  12798. close_now = true;
  12799. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12800. // Keep reading
  12801. }
  12802. if (n < 0) {
  12803. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12804. handle.get_read_error() == Error::Read)
  12805. << "Actual error: " << to_string(handle.get_read_error());
  12806. }
  12807. svr.stop();
  12808. t.join();
  12809. }
  12810. #endif
  12811. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12812. using namespace httplib;
  12813. // Create a test file
  12814. const char *fname = "etag_testfile.txt";
  12815. const char *content = "etag-content";
  12816. {
  12817. std::ofstream ofs(fname);
  12818. ofs << content;
  12819. ASSERT_TRUE(ofs.good());
  12820. }
  12821. Server svr;
  12822. svr.set_mount_point("/static", ".");
  12823. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12824. svr.wait_until_ready();
  12825. Client cli(HOST, PORT);
  12826. // First request: should get 200 with ETag header
  12827. auto res1 = cli.Get("/static/etag_testfile.txt");
  12828. ASSERT_TRUE(res1);
  12829. ASSERT_EQ(200, res1->status);
  12830. ASSERT_TRUE(res1->has_header("ETag"));
  12831. std::string etag = res1->get_header_value("ETag");
  12832. EXPECT_FALSE(etag.empty());
  12833. // Verify ETag format: W/"hex-hex"
  12834. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12835. EXPECT_EQ('W', etag[0]);
  12836. EXPECT_EQ('/', etag[1]);
  12837. EXPECT_EQ('"', etag[2]);
  12838. EXPECT_EQ('"', etag.back());
  12839. // Exact match: expect 304 Not Modified
  12840. Headers h2 = {{"If-None-Match", etag}};
  12841. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12842. ASSERT_TRUE(res2);
  12843. EXPECT_EQ(304, res2->status);
  12844. // Wildcard match: expect 304 Not Modified
  12845. Headers h3 = {{"If-None-Match", "*"}};
  12846. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12847. ASSERT_TRUE(res3);
  12848. EXPECT_EQ(304, res3->status);
  12849. // Non-matching ETag: expect 200
  12850. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12851. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12852. ASSERT_TRUE(res4);
  12853. EXPECT_EQ(200, res4->status);
  12854. // Multiple ETags with one matching: expect 304
  12855. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12856. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12857. ASSERT_TRUE(res5);
  12858. EXPECT_EQ(304, res5->status);
  12859. svr.stop();
  12860. t.join();
  12861. std::remove(fname);
  12862. }
  12863. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12864. using namespace httplib;
  12865. Server svr;
  12866. svr.set_mount_point("/static", ".");
  12867. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12868. svr.wait_until_ready();
  12869. Client cli(HOST, PORT);
  12870. // Send If-None-Match: * to a non-existent file
  12871. Headers h = {{"If-None-Match", "*"}};
  12872. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12873. ASSERT_TRUE(res);
  12874. EXPECT_EQ(404, res->status);
  12875. svr.stop();
  12876. t.join();
  12877. }
  12878. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12879. using namespace httplib;
  12880. // Create a test file
  12881. const char *fname = "etag_boundary_testfile.txt";
  12882. const char *content = "boundary-test";
  12883. {
  12884. std::ofstream ofs(fname);
  12885. ofs << content;
  12886. ASSERT_TRUE(ofs.good());
  12887. }
  12888. Server svr;
  12889. svr.set_mount_point("/static", ".");
  12890. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12891. svr.wait_until_ready();
  12892. Client cli(HOST, PORT);
  12893. // Get the actual ETag
  12894. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12895. ASSERT_TRUE(res1);
  12896. ASSERT_EQ(200, res1->status);
  12897. ASSERT_TRUE(res1->has_header("ETag"));
  12898. std::string etag = res1->get_header_value("ETag");
  12899. // Test 1: Very long ETag value (longer than actual ETag)
  12900. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12901. Headers h1 = {{"If-None-Match", "W/"
  12902. "\"very-long-etag-value-that-is-much-longer-"
  12903. "than-the-actual-etag-value\""}};
  12904. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12905. ASSERT_TRUE(res2);
  12906. EXPECT_EQ(200, res2->status); // Should not match
  12907. // Test 2: Long string followed by wildcard
  12908. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12909. // string)
  12910. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12911. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12912. ASSERT_TRUE(res3);
  12913. EXPECT_EQ(304, res3->status); // Should match on "*"
  12914. // Test 3: Wildcard followed by long string
  12915. // Should match on "*" immediately and return 304
  12916. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12917. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12918. ASSERT_TRUE(res4);
  12919. EXPECT_EQ(304, res4->status); // Should match on "*"
  12920. // Test 4: Multiple long non-matching values
  12921. // Should NOT match and return 200 (test that all comparisons are safe)
  12922. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12923. "W/\"second-long-non-matching-value\", "
  12924. "W/\"third-long-non-matching-value\""}};
  12925. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12926. ASSERT_TRUE(res5);
  12927. EXPECT_EQ(200, res5->status); // Should not match
  12928. // Test 5: Single character that is not "*" (edge case)
  12929. Headers h5 = {{"If-None-Match", "X"}};
  12930. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12931. ASSERT_TRUE(res6);
  12932. EXPECT_EQ(200, res6->status); // Should not match
  12933. svr.stop();
  12934. t.join();
  12935. std::remove(fname);
  12936. }
  12937. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12938. using namespace httplib;
  12939. // Create a test file
  12940. const char *fname = "ims_testfile.txt";
  12941. const char *content = "if-modified-since-test";
  12942. {
  12943. std::ofstream ofs(fname);
  12944. ofs << content;
  12945. ASSERT_TRUE(ofs.good());
  12946. }
  12947. Server svr;
  12948. svr.set_mount_point("/static", ".");
  12949. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12950. svr.wait_until_ready();
  12951. Client cli(HOST, PORT);
  12952. // First request: should get 200 with Last-Modified header
  12953. auto res1 = cli.Get("/static/ims_testfile.txt");
  12954. ASSERT_TRUE(res1);
  12955. ASSERT_EQ(200, res1->status);
  12956. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12957. std::string last_modified = res1->get_header_value("Last-Modified");
  12958. EXPECT_FALSE(last_modified.empty());
  12959. // If-Modified-Since with same time: expect 304
  12960. Headers h2 = {{"If-Modified-Since", last_modified}};
  12961. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12962. ASSERT_TRUE(res2);
  12963. EXPECT_EQ(304, res2->status);
  12964. // If-Modified-Since with future time: expect 304
  12965. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12966. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12967. ASSERT_TRUE(res3);
  12968. EXPECT_EQ(304, res3->status);
  12969. // If-Modified-Since with past time: expect 200
  12970. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12971. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12972. ASSERT_TRUE(res4);
  12973. EXPECT_EQ(200, res4->status);
  12974. // If-None-Match takes precedence over If-Modified-Since
  12975. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12976. ASSERT_TRUE(res1->has_header("ETag"));
  12977. std::string etag = res1->get_header_value("ETag");
  12978. Headers h5 = {{"If-None-Match", etag},
  12979. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12980. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12981. ASSERT_TRUE(res5);
  12982. EXPECT_EQ(304, res5->status);
  12983. svr.stop();
  12984. t.join();
  12985. std::remove(fname);
  12986. }
  12987. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12988. using namespace httplib;
  12989. Server svr;
  12990. // Endpoint that returns compressible content
  12991. svr.Get("/compressible", [](const Request &, Response &res) {
  12992. // Return a large enough body to trigger compression
  12993. std::string body(1000, 'a');
  12994. res.set_content(body, "text/plain");
  12995. });
  12996. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12997. svr.wait_until_ready();
  12998. Client cli(HOST, PORT);
  12999. // Request with gzip support: should get Vary header when compressed
  13000. cli.set_compress(true);
  13001. auto res1 = cli.Get("/compressible");
  13002. ASSERT_TRUE(res1);
  13003. EXPECT_EQ(200, res1->status);
  13004. // If Content-Encoding is set, Vary should also be set
  13005. if (res1->has_header("Content-Encoding")) {
  13006. EXPECT_TRUE(res1->has_header("Vary"));
  13007. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13008. }
  13009. // Request without Accept-Encoding header: should not have compression
  13010. Headers h_no_compress;
  13011. auto res2 = cli.Get("/compressible", h_no_compress);
  13012. ASSERT_TRUE(res2);
  13013. EXPECT_EQ(200, res2->status);
  13014. // Verify Vary header is present when compression is applied
  13015. // (the exact behavior depends on server configuration)
  13016. svr.stop();
  13017. t.join();
  13018. }
  13019. TEST(ETagTest, IfRangeWithETag) {
  13020. using namespace httplib;
  13021. // Create a test file with known content
  13022. const char *fname = "if_range_testfile.txt";
  13023. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13024. {
  13025. std::ofstream ofs(fname);
  13026. ofs << content;
  13027. ASSERT_TRUE(ofs.good());
  13028. }
  13029. Server svr;
  13030. svr.set_mount_point("/static", ".");
  13031. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13032. svr.wait_until_ready();
  13033. Client cli(HOST, PORT);
  13034. // First request: get ETag
  13035. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13036. ASSERT_TRUE(res1);
  13037. ASSERT_EQ(200, res1->status);
  13038. ASSERT_TRUE(res1->has_header("ETag"));
  13039. std::string etag = res1->get_header_value("ETag");
  13040. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13041. // Since our server generates weak ETags (W/"..."), If-Range with our
  13042. // ETag should NOT result in partial content - it should return full content.
  13043. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13044. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13045. ASSERT_TRUE(res2);
  13046. // Weak ETag in If-Range -> full content (200), not partial (206)
  13047. EXPECT_EQ(200, res2->status);
  13048. EXPECT_EQ(content, res2->body);
  13049. EXPECT_FALSE(res2->has_header("Content-Range"));
  13050. // Range request with non-matching If-Range (ETag): should get 200 (full
  13051. // content)
  13052. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13053. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13054. ASSERT_TRUE(res3);
  13055. EXPECT_EQ(200, res3->status);
  13056. EXPECT_EQ(content, res3->body);
  13057. EXPECT_FALSE(res3->has_header("Content-Range"));
  13058. // Range request with strong ETag (hypothetical - our server doesn't generate
  13059. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13060. // should return full content)
  13061. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13062. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13063. ASSERT_TRUE(res4);
  13064. EXPECT_EQ(200, res4->status);
  13065. EXPECT_EQ(content, res4->body);
  13066. EXPECT_FALSE(res4->has_header("Content-Range"));
  13067. svr.stop();
  13068. t.join();
  13069. std::remove(fname);
  13070. }
  13071. TEST(ETagTest, IfRangeWithDate) {
  13072. using namespace httplib;
  13073. // Create a test file
  13074. const char *fname = "if_range_date_testfile.txt";
  13075. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13076. {
  13077. std::ofstream ofs(fname);
  13078. ofs << content;
  13079. ASSERT_TRUE(ofs.good());
  13080. }
  13081. Server svr;
  13082. svr.set_mount_point("/static", ".");
  13083. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13084. svr.wait_until_ready();
  13085. Client cli(HOST, PORT);
  13086. // First request: get Last-Modified
  13087. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13088. ASSERT_TRUE(res1);
  13089. ASSERT_EQ(200, res1->status);
  13090. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13091. std::string last_modified = res1->get_header_value("Last-Modified");
  13092. // Range request with matching If-Range (date): should get 206
  13093. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13094. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13095. ASSERT_TRUE(res2);
  13096. EXPECT_EQ(206, res2->status);
  13097. EXPECT_EQ("FGHIJ", res2->body);
  13098. // Range request with old If-Range date: should get 200 (full content)
  13099. Headers h3 = {{"Range", "bytes=5-9"},
  13100. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13101. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13102. ASSERT_TRUE(res3);
  13103. EXPECT_EQ(200, res3->status);
  13104. EXPECT_EQ(content, res3->body);
  13105. // Range request with future If-Range date: should get 206
  13106. Headers h4 = {{"Range", "bytes=0-4"},
  13107. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13108. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13109. ASSERT_TRUE(res4);
  13110. EXPECT_EQ(206, res4->status);
  13111. EXPECT_EQ("ABCDE", res4->body);
  13112. svr.stop();
  13113. t.join();
  13114. std::remove(fname);
  13115. }
  13116. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13117. using namespace httplib;
  13118. const char *fname = "etag_malformed.txt";
  13119. const char *content = "malformed-etag";
  13120. {
  13121. std::ofstream ofs(fname);
  13122. ofs << content;
  13123. ASSERT_TRUE(ofs.good());
  13124. }
  13125. Server svr;
  13126. svr.set_mount_point("/static", ".");
  13127. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13128. svr.wait_until_ready();
  13129. Client cli(HOST, PORT);
  13130. // baseline: should get 200 and an ETag
  13131. auto res1 = cli.Get("/static/etag_malformed.txt");
  13132. ASSERT_TRUE(res1);
  13133. ASSERT_EQ(200, res1->status);
  13134. ASSERT_TRUE(res1->has_header("ETag"));
  13135. // Malformed ETag value (missing quotes) should be treated as non-matching
  13136. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13137. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13138. ASSERT_TRUE(res_bad);
  13139. EXPECT_EQ(200, res_bad->status);
  13140. // Whitespace-only header value should be considered invalid / non-matching
  13141. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13142. "Host: localhost\r\n"
  13143. "If-None-Match: \r\n"
  13144. "Connection: close\r\n"
  13145. "\r\n";
  13146. std::string out;
  13147. ASSERT_TRUE(send_request(5, raw_req, &out));
  13148. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13149. svr.stop();
  13150. t.join();
  13151. std::remove(fname);
  13152. }
  13153. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13154. using namespace httplib;
  13155. const char *fname = "ims_invalid_format.txt";
  13156. const char *content = "ims-bad-format";
  13157. {
  13158. std::ofstream ofs(fname);
  13159. ofs << content;
  13160. ASSERT_TRUE(ofs.good());
  13161. }
  13162. Server svr;
  13163. svr.set_mount_point("/static", ".");
  13164. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13165. svr.wait_until_ready();
  13166. Client cli(HOST, PORT);
  13167. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13168. ASSERT_TRUE(res1);
  13169. ASSERT_EQ(200, res1->status);
  13170. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13171. // If-Modified-Since with invalid format should not result in 304
  13172. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13173. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13174. ASSERT_TRUE(res_bad);
  13175. EXPECT_EQ(200, res_bad->status);
  13176. // If-Range with invalid date format should be treated as mismatch -> full
  13177. // content (200)
  13178. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13179. {"If-Range", "invalid-date"}};
  13180. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13181. ASSERT_TRUE(res_ifrange);
  13182. EXPECT_EQ(200, res_ifrange->status);
  13183. svr.stop();
  13184. t.join();
  13185. std::remove(fname);
  13186. }
  13187. TEST(ETagTest, IfRangeWithMalformedETag) {
  13188. using namespace httplib;
  13189. const char *fname = "ifrange_malformed.txt";
  13190. const std::string content = "0123456789";
  13191. {
  13192. std::ofstream ofs(fname);
  13193. ofs << content;
  13194. ASSERT_TRUE(ofs.good());
  13195. }
  13196. Server svr;
  13197. svr.set_mount_point("/static", ".");
  13198. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13199. svr.wait_until_ready();
  13200. Client cli(HOST, PORT);
  13201. // First request: get ETag
  13202. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13203. ASSERT_TRUE(res1);
  13204. ASSERT_EQ(200, res1->status);
  13205. ASSERT_TRUE(res1->has_header("ETag"));
  13206. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13207. // full content (200)
  13208. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13209. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13210. ASSERT_TRUE(res2);
  13211. EXPECT_EQ(200, res2->status);
  13212. EXPECT_EQ(content, res2->body);
  13213. svr.stop();
  13214. t.join();
  13215. std::remove(fname);
  13216. }
  13217. TEST(ETagTest, ExtremeLargeDateValues) {
  13218. using namespace httplib;
  13219. const char *fname = "ims_extreme_date.txt";
  13220. const char *content = "ims-extreme-date";
  13221. {
  13222. std::ofstream ofs(fname);
  13223. ofs << content;
  13224. ASSERT_TRUE(ofs.good());
  13225. }
  13226. Server svr;
  13227. svr.set_mount_point("/static", ".");
  13228. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13229. svr.wait_until_ready();
  13230. Client cli(HOST, PORT);
  13231. auto res1 = cli.Get(std::string("/static/") + fname);
  13232. ASSERT_TRUE(res1);
  13233. ASSERT_EQ(200, res1->status);
  13234. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13235. // Extremely large year that may overflow date parsing routines.
  13236. Headers h_large_date = {
  13237. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13238. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13239. ASSERT_TRUE(res_bad);
  13240. // Expect server to treat this as invalid/mismatch and return full content
  13241. EXPECT_EQ(200, res_bad->status);
  13242. // If-Range with extremely large date should be treated as mismatch -> full
  13243. // content (200)
  13244. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13245. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13246. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13247. ASSERT_TRUE(res_ifrange);
  13248. EXPECT_EQ(200, res_ifrange->status);
  13249. svr.stop();
  13250. t.join();
  13251. std::remove(fname);
  13252. }
  13253. TEST(ETagTest, NegativeFileModificationTime) {
  13254. using namespace httplib;
  13255. const char *fname = "ims_negative_mtime.txt";
  13256. const std::string content = "negative-mtime";
  13257. {
  13258. std::ofstream ofs(fname);
  13259. ofs << content;
  13260. ASSERT_TRUE(ofs.good());
  13261. }
  13262. // Try to set file mtime to a negative value. This may fail on some
  13263. // platforms/filesystems; if it fails, the test will still verify server
  13264. // behaves safely by performing a regular conditional request.
  13265. #if defined(__APPLE__) || defined(__linux__)
  13266. bool set_negative = false;
  13267. do {
  13268. struct timeval times[2];
  13269. // access time: now
  13270. times[0].tv_sec = time(nullptr);
  13271. times[0].tv_usec = 0;
  13272. // modification time: negative (e.g., -1)
  13273. times[1].tv_sec = -1;
  13274. times[1].tv_usec = 0;
  13275. if (utimes(fname, times) == 0) { set_negative = true; }
  13276. } while (0);
  13277. #else
  13278. bool set_negative = false;
  13279. #endif
  13280. Server svr;
  13281. svr.set_mount_point("/static", ".");
  13282. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13283. svr.wait_until_ready();
  13284. Client cli(HOST, PORT);
  13285. auto res1 = cli.Get(std::string("/static/") + fname);
  13286. ASSERT_TRUE(res1);
  13287. ASSERT_EQ(200, res1->status);
  13288. bool has_last_modified = res1->has_header("Last-Modified");
  13289. std::string last_modified;
  13290. if (has_last_modified) {
  13291. last_modified = res1->get_header_value("Last-Modified");
  13292. }
  13293. if (set_negative) {
  13294. // If we successfully set a negative mtime, ensure server returns a
  13295. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13296. // with an old date and ensure server handles it without crash.
  13297. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13298. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13299. ASSERT_TRUE(res2);
  13300. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13301. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13302. } else {
  13303. // Could not set negative mtime on this platform; fall back to verifying
  13304. // that normal invalid/malformed dates are treated safely (non-304).
  13305. Headers h_bad_date = {
  13306. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13307. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13308. ASSERT_TRUE(res_bad);
  13309. EXPECT_EQ(200, res_bad->status);
  13310. }
  13311. svr.stop();
  13312. t.join();
  13313. std::remove(fname);
  13314. }
  13315. //==============================================================================
  13316. // SSE Parsing Tests
  13317. //==============================================================================
  13318. class SSEParsingTest : public ::testing::Test {
  13319. protected:
  13320. // Test helper that mimics SSE parsing behavior
  13321. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13322. int &retry_ms) {
  13323. // Blank line signals end of event
  13324. if (line.empty() || line == "\r") { return true; }
  13325. // Lines starting with ':' are comments (ignored)
  13326. if (!line.empty() && line[0] == ':') { return false; }
  13327. // Find the colon separator
  13328. auto colon_pos = line.find(':');
  13329. if (colon_pos == std::string::npos) {
  13330. // Line with no colon is treated as field name with empty value
  13331. return false;
  13332. }
  13333. std::string field = line.substr(0, colon_pos);
  13334. std::string value;
  13335. // Value starts after colon, skip optional single space
  13336. if (colon_pos + 1 < line.size()) {
  13337. size_t value_start = colon_pos + 1;
  13338. if (line[value_start] == ' ') { value_start++; }
  13339. value = line.substr(value_start);
  13340. // Remove trailing \r if present
  13341. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13342. }
  13343. // Handle known fields
  13344. if (field == "event") {
  13345. msg.event = value;
  13346. } else if (field == "data") {
  13347. // Multiple data lines are concatenated with newlines
  13348. if (!msg.data.empty()) { msg.data += "\n"; }
  13349. msg.data += value;
  13350. } else if (field == "id") {
  13351. // Empty id is valid (clears the last event ID)
  13352. msg.id = value;
  13353. } else if (field == "retry") {
  13354. // Parse retry interval in milliseconds
  13355. {
  13356. int v = 0;
  13357. auto res =
  13358. detail::from_chars(value.data(), value.data() + value.size(), v);
  13359. if (res.ec == std::errc{}) { retry_ms = v; }
  13360. }
  13361. }
  13362. // Unknown fields are ignored per SSE spec
  13363. return false;
  13364. }
  13365. };
  13366. // Test: Single-line data
  13367. TEST_F(SSEParsingTest, SingleLineData) {
  13368. sse::SSEMessage msg;
  13369. int retry_ms = 3000;
  13370. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13371. EXPECT_EQ(msg.data, "hello");
  13372. EXPECT_EQ(msg.event, "message");
  13373. // Blank line ends event
  13374. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13375. }
  13376. // Test: Multi-line data
  13377. TEST_F(SSEParsingTest, MultiLineData) {
  13378. sse::SSEMessage msg;
  13379. int retry_ms = 3000;
  13380. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13381. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13382. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13383. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13384. }
  13385. // Test: Custom event types
  13386. TEST_F(SSEParsingTest, CustomEventType) {
  13387. sse::SSEMessage msg;
  13388. int retry_ms = 3000;
  13389. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13390. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13391. EXPECT_EQ(msg.event, "update");
  13392. EXPECT_EQ(msg.data, "payload");
  13393. }
  13394. // Test: Event ID handling
  13395. TEST_F(SSEParsingTest, EventIdHandling) {
  13396. sse::SSEMessage msg;
  13397. int retry_ms = 3000;
  13398. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13399. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13400. EXPECT_EQ(msg.id, "12345");
  13401. }
  13402. // Test: Empty event ID (clears last event ID)
  13403. TEST_F(SSEParsingTest, EmptyEventId) {
  13404. sse::SSEMessage msg;
  13405. msg.id = "previous";
  13406. int retry_ms = 3000;
  13407. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13408. EXPECT_EQ(msg.id, "");
  13409. }
  13410. // Test: Retry field parsing
  13411. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13412. sse::SSEMessage msg;
  13413. int retry_ms = 3000;
  13414. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13415. EXPECT_EQ(retry_ms, 5000);
  13416. }
  13417. // Test: Invalid retry value
  13418. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13419. sse::SSEMessage msg;
  13420. int retry_ms = 3000;
  13421. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13422. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13423. }
  13424. // Test: Comments (lines starting with :)
  13425. TEST_F(SSEParsingTest, CommentsIgnored) {
  13426. sse::SSEMessage msg;
  13427. int retry_ms = 3000;
  13428. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13429. EXPECT_EQ(msg.data, "");
  13430. EXPECT_EQ(msg.event, "message");
  13431. }
  13432. // Test: Colon in value
  13433. TEST_F(SSEParsingTest, ColonInValue) {
  13434. sse::SSEMessage msg;
  13435. int retry_ms = 3000;
  13436. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13437. EXPECT_EQ(msg.data, "hello:world:test");
  13438. }
  13439. // Test: Line with no colon (field name only)
  13440. TEST_F(SSEParsingTest, FieldNameOnly) {
  13441. sse::SSEMessage msg;
  13442. int retry_ms = 3000;
  13443. // According to SSE spec, this is treated as field name with empty value
  13444. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13445. // Since we don't recognize "data" without colon, data should be empty
  13446. EXPECT_EQ(msg.data, "");
  13447. }
  13448. // Test: Trailing \r handling
  13449. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13450. sse::SSEMessage msg;
  13451. int retry_ms = 3000;
  13452. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13453. EXPECT_EQ(msg.data, "hello");
  13454. }
  13455. // Test: Unknown fields ignored
  13456. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13457. sse::SSEMessage msg;
  13458. int retry_ms = 3000;
  13459. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13460. EXPECT_EQ(msg.data, "");
  13461. EXPECT_EQ(msg.event, "message");
  13462. }
  13463. // Test: Space after colon is optional
  13464. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13465. sse::SSEMessage msg1, msg2;
  13466. int retry_ms = 3000;
  13467. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13468. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13469. EXPECT_EQ(msg1.data, "hello");
  13470. EXPECT_EQ(msg2.data, "hello");
  13471. }
  13472. // Test: SSEMessage clear
  13473. TEST_F(SSEParsingTest, MessageClear) {
  13474. sse::SSEMessage msg;
  13475. msg.event = "custom";
  13476. msg.data = "some data";
  13477. msg.id = "123";
  13478. msg.clear();
  13479. EXPECT_EQ(msg.event, "message");
  13480. EXPECT_EQ(msg.data, "");
  13481. EXPECT_EQ(msg.id, "");
  13482. }
  13483. // Test: Complete event parsing
  13484. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13485. sse::SSEMessage msg;
  13486. int retry_ms = 3000;
  13487. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13488. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13489. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13490. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13491. // Blank line ends event
  13492. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13493. EXPECT_EQ(msg.event, "notification");
  13494. EXPECT_EQ(msg.id, "evt-42");
  13495. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13496. EXPECT_EQ(retry_ms, 1000);
  13497. }
  13498. //==============================================================================
  13499. // Integration Tests with Server
  13500. //==============================================================================
  13501. class SSEIntegrationTest : public ::testing::Test {
  13502. protected:
  13503. void SetUp() override {
  13504. stop_server_.store(false);
  13505. events_.clear();
  13506. server_ = httplib::detail::make_unique<Server>();
  13507. setup_server();
  13508. start_server();
  13509. }
  13510. void TearDown() override {
  13511. stop_server_.store(true);
  13512. event_cv_.notify_all();
  13513. server_->stop();
  13514. if (server_thread_.joinable()) { server_thread_.join(); }
  13515. }
  13516. void setup_server() {
  13517. // Simple SSE endpoint
  13518. server_->Get("/events", [this](const Request &req, Response &res) {
  13519. auto last_id = req.get_header_value("Last-Event-ID");
  13520. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13521. res.set_chunked_content_provider(
  13522. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13523. std::unique_lock<std::mutex> lock(event_mutex_);
  13524. if (event_cv_.wait_for(
  13525. lock, std::chrono::milliseconds(200), [this] {
  13526. return !events_.empty() || stop_server_.load();
  13527. })) {
  13528. if (stop_server_.load()) { return false; }
  13529. if (!events_.empty()) {
  13530. std::string event = events_.front();
  13531. events_.erase(events_.begin());
  13532. sink.write(event.data(), event.size());
  13533. return true;
  13534. }
  13535. }
  13536. return !stop_server_.load();
  13537. });
  13538. });
  13539. // Endpoint that returns error
  13540. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13541. res.status = 500;
  13542. res.set_content("Internal Server Error", "text/plain");
  13543. });
  13544. // Endpoint for custom event types
  13545. server_->Get("/custom-events", [](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 = "event: update\ndata: updated\n\n"
  13550. "event: delete\ndata: deleted\n\n";
  13551. sink.write(event.data(), event.size());
  13552. }
  13553. return false; // End stream after sending
  13554. });
  13555. });
  13556. }
  13557. void start_server() {
  13558. port_ = server_->bind_to_any_port(HOST);
  13559. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13560. // Wait for server to start
  13561. while (!server_->is_running()) {
  13562. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13563. }
  13564. }
  13565. int get_port() const { return port_; }
  13566. void send_event(const std::string &event) {
  13567. std::lock_guard<std::mutex> lock(event_mutex_);
  13568. events_.push_back(event);
  13569. event_cv_.notify_all();
  13570. }
  13571. std::unique_ptr<Server> server_;
  13572. std::thread server_thread_;
  13573. std::mutex event_mutex_;
  13574. std::condition_variable event_cv_;
  13575. std::vector<std::string> events_;
  13576. std::atomic<bool> stop_server_{false};
  13577. std::string last_received_event_id_;
  13578. int port_ = 0;
  13579. };
  13580. // Test: Successful connection and on_open callback
  13581. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13582. // Add a simple endpoint that sends one event and closes
  13583. server_->Get("/simple-event", [](const Request &, Response &res) {
  13584. res.set_chunked_content_provider(
  13585. "text/event-stream", [](size_t offset, DataSink &sink) {
  13586. if (offset == 0) {
  13587. std::string event = "data: hello\n\n";
  13588. sink.write(event.data(), event.size());
  13589. }
  13590. return false; // Close stream after sending
  13591. });
  13592. });
  13593. Client client("localhost", get_port());
  13594. sse::SSEClient sse(client, "/simple-event");
  13595. std::atomic<bool> open_called{false};
  13596. std::atomic<bool> message_received{false};
  13597. sse.on_open([&open_called]() { open_called.store(true); });
  13598. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13599. if (msg.data == "hello") { message_received.store(true); }
  13600. });
  13601. sse.set_reconnect_interval(100);
  13602. sse.set_max_reconnect_attempts(1);
  13603. // Start async
  13604. sse.start_async();
  13605. // Wait for message to be processed
  13606. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13607. sse.stop();
  13608. EXPECT_TRUE(open_called.load());
  13609. EXPECT_TRUE(message_received.load());
  13610. }
  13611. // Test: on_message callback
  13612. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13613. // Endpoint that sends multiple events then closes
  13614. server_->Get("/multi-event", [](const Request &, Response &res) {
  13615. res.set_chunked_content_provider(
  13616. "text/event-stream", [](size_t offset, DataSink &sink) {
  13617. if (offset == 0) {
  13618. std::string events = "data: message1\n\ndata: message2\n\n";
  13619. sink.write(events.data(), events.size());
  13620. }
  13621. return false;
  13622. });
  13623. });
  13624. Client client("localhost", get_port());
  13625. sse::SSEClient sse(client, "/multi-event");
  13626. std::vector<std::string> received_messages;
  13627. std::mutex messages_mutex;
  13628. sse.on_message([&](const sse::SSEMessage &msg) {
  13629. std::lock_guard<std::mutex> lock(messages_mutex);
  13630. received_messages.push_back(msg.data);
  13631. });
  13632. sse.set_reconnect_interval(100);
  13633. sse.set_max_reconnect_attempts(1);
  13634. sse.start_async();
  13635. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13636. sse.stop();
  13637. std::lock_guard<std::mutex> lock(messages_mutex);
  13638. EXPECT_GE(received_messages.size(), 2u);
  13639. if (received_messages.size() >= 2) {
  13640. EXPECT_EQ(received_messages[0], "message1");
  13641. EXPECT_EQ(received_messages[1], "message2");
  13642. }
  13643. }
  13644. // Test: on_event for specific types
  13645. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13646. Client client("localhost", get_port());
  13647. sse::SSEClient sse(client, "/custom-events");
  13648. std::atomic<bool> update_received{false};
  13649. std::atomic<bool> delete_received{false};
  13650. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13651. if (msg.data == "updated") { update_received.store(true); }
  13652. });
  13653. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13654. if (msg.data == "deleted") { delete_received.store(true); }
  13655. });
  13656. sse.set_max_reconnect_attempts(1);
  13657. sse.start_async();
  13658. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13659. sse.stop();
  13660. EXPECT_TRUE(update_received.load());
  13661. EXPECT_TRUE(delete_received.load());
  13662. }
  13663. // Test: on_error callback on connection failure
  13664. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13665. // Connect to a non-existent port
  13666. Client client("localhost", 59999);
  13667. sse::SSEClient sse(client, "/events");
  13668. std::atomic<bool> error_called{false};
  13669. Error received_error = Error::Success;
  13670. sse.on_error([&](Error err) {
  13671. error_called.store(true);
  13672. received_error = err;
  13673. });
  13674. sse.set_reconnect_interval(50);
  13675. sse.set_max_reconnect_attempts(1);
  13676. sse.start_async();
  13677. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13678. sse.stop();
  13679. EXPECT_TRUE(error_called.load());
  13680. EXPECT_NE(received_error, Error::Success);
  13681. }
  13682. // Test: Last-Event-ID header sent on reconnect
  13683. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13684. // Endpoint that sends event with ID
  13685. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13686. res.set_chunked_content_provider(
  13687. "text/event-stream", [](size_t offset, DataSink &sink) {
  13688. if (offset == 0) {
  13689. std::string event = "id: evt-123\ndata: test\n\n";
  13690. sink.write(event.data(), event.size());
  13691. }
  13692. return false;
  13693. });
  13694. });
  13695. Client client("localhost", get_port());
  13696. sse::SSEClient sse(client, "/event-with-id");
  13697. std::atomic<bool> id_received{false};
  13698. sse.on_message([&](const sse::SSEMessage &msg) {
  13699. if (!msg.id.empty()) { id_received.store(true); }
  13700. });
  13701. sse.set_reconnect_interval(100);
  13702. sse.set_max_reconnect_attempts(1);
  13703. sse.start_async();
  13704. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13705. sse.stop();
  13706. EXPECT_TRUE(id_received.load());
  13707. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13708. }
  13709. // Test: Manual stop
  13710. TEST_F(SSEIntegrationTest, ManualStop) {
  13711. // Endpoint that sends one event and stays open briefly
  13712. std::atomic<bool> handler_running{true};
  13713. server_->Get("/stay-open", [&handler_running](const Request &,
  13714. Response &res) {
  13715. res.set_chunked_content_provider(
  13716. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13717. if (offset == 0) {
  13718. std::string event = "data: connected\n\n";
  13719. sink.write(event.data(), event.size());
  13720. }
  13721. // Keep connection open while handler_running is true
  13722. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13723. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13724. }
  13725. return false;
  13726. });
  13727. });
  13728. Client client("localhost", get_port());
  13729. sse::SSEClient sse(client, "/stay-open");
  13730. std::atomic<bool> connected{false};
  13731. sse.on_open([&connected]() { connected.store(true); });
  13732. sse.set_reconnect_interval(100);
  13733. sse.set_max_reconnect_attempts(1);
  13734. sse.start_async();
  13735. // Wait for connection to establish
  13736. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13737. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13738. }
  13739. EXPECT_TRUE(connected.load());
  13740. EXPECT_TRUE(sse.is_connected());
  13741. // Signal handler to stop
  13742. handler_running.store(false);
  13743. // Stop SSE client
  13744. sse.stop();
  13745. EXPECT_FALSE(sse.is_connected());
  13746. }
  13747. // Test: SSEClient with custom headers
  13748. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13749. // Setup a server endpoint that checks for custom header
  13750. std::atomic<bool> header_received{false};
  13751. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13752. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13753. header_received.store(true);
  13754. }
  13755. res.set_chunked_content_provider("text/event-stream",
  13756. [](size_t, DataSink &) { return false; });
  13757. });
  13758. Client client("localhost", get_port());
  13759. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13760. sse::SSEClient sse(client, "/header-check", headers);
  13761. sse.set_max_reconnect_attempts(1);
  13762. sse.start_async();
  13763. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13764. sse.stop();
  13765. EXPECT_TRUE(header_received.load());
  13766. }
  13767. // Test: Reconnect interval configuration
  13768. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13769. Client client("localhost", get_port());
  13770. sse::SSEClient sse(client, "/events");
  13771. auto &result = sse.set_reconnect_interval(500);
  13772. // Builder pattern should return reference to self
  13773. EXPECT_EQ(&result, &sse);
  13774. }
  13775. // Test: Max reconnect attempts
  13776. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13777. // Connect to non-existent port to force reconnects
  13778. Client client("localhost", 59998);
  13779. sse::SSEClient sse(client, "/events");
  13780. std::atomic<int> error_count{0};
  13781. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13782. sse.set_reconnect_interval(50);
  13783. sse.set_max_reconnect_attempts(2);
  13784. auto start = std::chrono::steady_clock::now();
  13785. sse.start(); // Blocking call
  13786. auto end = std::chrono::steady_clock::now();
  13787. // Should have stopped after 2 failed attempts
  13788. EXPECT_GE(error_count.load(), 2);
  13789. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13790. auto duration =
  13791. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13792. #ifdef _WIN32
  13793. // Windows is much slower for socket connection failures
  13794. EXPECT_LT(duration.count(), 7000);
  13795. #else
  13796. EXPECT_LT(duration.count(), 1000);
  13797. #endif
  13798. }
  13799. // Test: Multi-line data in integration
  13800. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13801. // Endpoint with multi-line data
  13802. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13803. res.set_chunked_content_provider(
  13804. "text/event-stream", [](size_t offset, DataSink &sink) {
  13805. if (offset == 0) {
  13806. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13807. sink.write(event.data(), event.size());
  13808. }
  13809. return false;
  13810. });
  13811. });
  13812. Client client("localhost", get_port());
  13813. sse::SSEClient sse(client, "/multiline-data");
  13814. std::string received_data;
  13815. std::mutex data_mutex;
  13816. sse.on_message([&](const sse::SSEMessage &msg) {
  13817. std::lock_guard<std::mutex> lock(data_mutex);
  13818. received_data = msg.data;
  13819. });
  13820. sse.set_reconnect_interval(100);
  13821. sse.set_max_reconnect_attempts(1);
  13822. sse.start_async();
  13823. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13824. sse.stop();
  13825. std::lock_guard<std::mutex> lock(data_mutex);
  13826. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13827. }
  13828. // Test: Auto-reconnect after server disconnection
  13829. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13830. std::atomic<int> connection_count{0};
  13831. std::atomic<int> message_count{0};
  13832. // Endpoint that sends one event and closes, forcing reconnect
  13833. server_->Get("/reconnect-test",
  13834. [&connection_count](const Request &, Response &res) {
  13835. connection_count.fetch_add(1);
  13836. res.set_chunked_content_provider(
  13837. "text/event-stream", [](size_t offset, DataSink &sink) {
  13838. if (offset == 0) {
  13839. std::string event = "data: hello\n\n";
  13840. sink.write(event.data(), event.size());
  13841. }
  13842. return false; // Close connection after sending
  13843. });
  13844. });
  13845. Client client("localhost", get_port());
  13846. sse::SSEClient sse(client, "/reconnect-test");
  13847. sse.on_message([&message_count](const sse::SSEMessage &) {
  13848. message_count.fetch_add(1);
  13849. });
  13850. sse.set_reconnect_interval(100);
  13851. sse.set_max_reconnect_attempts(3);
  13852. sse.start_async();
  13853. // Wait long enough for multiple reconnects
  13854. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13855. sse.stop();
  13856. // Should have connected multiple times (initial + reconnects)
  13857. EXPECT_GE(connection_count.load(), 2);
  13858. // Should have received messages from multiple connections
  13859. EXPECT_GE(message_count.load(), 2);
  13860. }
  13861. // Test: Last-Event-ID sent on reconnect
  13862. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13863. std::atomic<int> connection_count{0};
  13864. std::vector<std::string> received_last_event_ids;
  13865. std::mutex id_mutex;
  13866. // Endpoint that checks Last-Event-ID header and sends event with ID
  13867. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13868. int conn = connection_count.fetch_add(1);
  13869. // Capture the Last-Event-ID header from each connection
  13870. {
  13871. std::lock_guard<std::mutex> lock(id_mutex);
  13872. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13873. }
  13874. res.set_chunked_content_provider(
  13875. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13876. if (offset == 0) {
  13877. std::string event =
  13878. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13879. sink.write(event.data(), event.size());
  13880. }
  13881. return false;
  13882. });
  13883. });
  13884. Client client("localhost", get_port());
  13885. sse::SSEClient sse(client, "/reconnect-with-id");
  13886. sse.set_reconnect_interval(100);
  13887. sse.set_max_reconnect_attempts(3);
  13888. sse.start_async();
  13889. // Wait for at least 2 connections
  13890. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13891. sse.stop();
  13892. // Verify behavior
  13893. std::lock_guard<std::mutex> lock(id_mutex);
  13894. EXPECT_GE(received_last_event_ids.size(), 2u);
  13895. // First connection should have no Last-Event-ID
  13896. if (!received_last_event_ids.empty()) {
  13897. EXPECT_EQ(received_last_event_ids[0], "");
  13898. }
  13899. // Second connection should have Last-Event-ID from first connection
  13900. if (received_last_event_ids.size() >= 2) {
  13901. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13902. }
  13903. }
  13904. // Test: set_headers updates headers used on reconnect
  13905. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13906. std::vector<std::string> received_tokens;
  13907. std::mutex token_mutex;
  13908. // Endpoint that captures Authorization header
  13909. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13910. {
  13911. std::lock_guard<std::mutex> lock(token_mutex);
  13912. received_tokens.push_back(req.get_header_value("Authorization"));
  13913. }
  13914. res.set_chunked_content_provider(
  13915. "text/event-stream", [](size_t offset, DataSink &sink) {
  13916. if (offset == 0) {
  13917. std::string event = "data: hello\n\n";
  13918. sink.write(event.data(), event.size());
  13919. }
  13920. return false; // Close connection to trigger reconnect
  13921. });
  13922. });
  13923. Client client("localhost", get_port());
  13924. Headers headers = {{"Authorization", "Bearer old-token"}};
  13925. sse::SSEClient sse(client, "/auth-check", headers);
  13926. // Update headers on each successful connection
  13927. sse.on_open(
  13928. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13929. sse.set_reconnect_interval(100);
  13930. sse.set_max_reconnect_attempts(3);
  13931. sse.start_async();
  13932. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13933. sse.stop();
  13934. std::lock_guard<std::mutex> lock(token_mutex);
  13935. ASSERT_GE(received_tokens.size(), 2u);
  13936. // First connection uses original header
  13937. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13938. // Second connection uses updated header from set_headers
  13939. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13940. }
  13941. // Test: 401 allows reconnection (so on_error can refresh headers)
  13942. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13943. std::atomic<int> connection_count{0};
  13944. // Endpoint: returns 401 on first attempt, 200 on second
  13945. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13946. int conn = connection_count.fetch_add(1);
  13947. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13948. res.status = StatusCode::Unauthorized_401;
  13949. res.set_content("Unauthorized", "text/plain");
  13950. return;
  13951. }
  13952. res.set_chunked_content_provider(
  13953. "text/event-stream", [](size_t offset, DataSink &sink) {
  13954. if (offset == 0) {
  13955. std::string event = "data: authenticated\n\n";
  13956. sink.write(event.data(), event.size());
  13957. }
  13958. return false;
  13959. });
  13960. });
  13961. Client client("localhost", get_port());
  13962. Headers headers = {{"Authorization", "Bearer expired"}};
  13963. sse::SSEClient sse(client, "/auth-retry", headers);
  13964. std::atomic<bool> message_received{false};
  13965. // Refresh token on error
  13966. sse.on_error(
  13967. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13968. sse.on_message([&](const sse::SSEMessage &msg) {
  13969. if (msg.data == "authenticated") { message_received.store(true); }
  13970. });
  13971. sse.set_reconnect_interval(100);
  13972. sse.set_max_reconnect_attempts(3);
  13973. sse.start_async();
  13974. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13975. sse.stop();
  13976. // Should have reconnected after 401 and succeeded with new token
  13977. EXPECT_GE(connection_count.load(), 2);
  13978. EXPECT_TRUE(message_received.load());
  13979. }
  13980. TEST(Issue2318Test, EmptyHostString) {
  13981. {
  13982. httplib::Client cli_empty("", PORT);
  13983. auto res = cli_empty.Get("/");
  13984. ASSERT_FALSE(res);
  13985. EXPECT_EQ(httplib::Error::Connection, res.error());
  13986. }
  13987. {
  13988. httplib::Client cli(" ", PORT);
  13989. auto res = cli.Get("/");
  13990. ASSERT_FALSE(res);
  13991. EXPECT_EQ(httplib::Error::Connection, res.error());
  13992. }
  13993. }
  13994. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13995. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13996. Server svr;
  13997. // Set a small payload limit (1KB)
  13998. svr.set_payload_max_length(1024);
  13999. svr.Post("/test", [&](const Request &req, Response &res) {
  14000. res.set_content("Body size: " + std::to_string(req.body.size()),
  14001. "text/plain");
  14002. });
  14003. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14004. auto se = detail::scope_exit([&] {
  14005. svr.stop();
  14006. listen_thread.join();
  14007. });
  14008. svr.wait_until_ready();
  14009. // Create data that compresses well but exceeds limit when decompressed
  14010. // 8KB of repeated null bytes compresses to a very small size
  14011. std::string original_data(8 * 1024, '\0');
  14012. // Compress the data using gzip
  14013. std::string compressed_data;
  14014. detail::gzip_compressor compressor;
  14015. compressor.compress(original_data.data(), original_data.size(), true,
  14016. [&](const char *data, size_t size) {
  14017. compressed_data.append(data, size);
  14018. return true;
  14019. });
  14020. // Verify compression worked (compressed should be much smaller)
  14021. ASSERT_LT(compressed_data.size(), original_data.size());
  14022. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14023. // Send compressed data with Content-Encoding: gzip
  14024. Client cli(HOST, PORT);
  14025. Headers headers = {{"Content-Encoding", "gzip"}};
  14026. auto res =
  14027. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14028. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14029. ASSERT_TRUE(res);
  14030. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14031. }
  14032. #endif
  14033. // ============================================================================
  14034. // OpenSSL-Specific Tests
  14035. // ============================================================================
  14036. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14037. X509 *readCertificate(const std::string &strFileName) {
  14038. std::ifstream inStream(strFileName);
  14039. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14040. std::istreambuf_iterator<char>());
  14041. if (strCertPEM.empty()) return (nullptr);
  14042. BIO *pbCert = BIO_new(BIO_s_mem());
  14043. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14044. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14045. BIO_free(pbCert);
  14046. return (pCert);
  14047. }
  14048. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14049. std::ifstream inStream(strFileName);
  14050. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14051. std::istreambuf_iterator<char>());
  14052. if (strPrivateKeyPEM.empty()) return (nullptr);
  14053. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14054. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14055. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14056. BIO_free(pbPrivKey);
  14057. return (pPrivateKey);
  14058. }
  14059. TEST(BindServerTest, UpdateCerts) {
  14060. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14061. int port = svr.bind_to_any_port("0.0.0.0");
  14062. ASSERT_TRUE(svr.is_valid());
  14063. ASSERT_TRUE(port > 0);
  14064. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14065. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14066. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14067. ASSERT_TRUE(cert != nullptr);
  14068. ASSERT_TRUE(ca_cert != nullptr);
  14069. ASSERT_TRUE(key != nullptr);
  14070. X509_STORE *cert_store = X509_STORE_new();
  14071. X509_STORE_add_cert(cert_store, ca_cert);
  14072. // svr.update_certs(cert, key, cert_store); // deprecated
  14073. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14074. CLIENT_CA_CERT_FILE);
  14075. ASSERT_TRUE(svr.is_valid());
  14076. svr.stop();
  14077. X509_STORE_free(cert_store);
  14078. X509_free(cert);
  14079. X509_free(ca_cert);
  14080. EVP_PKEY_free(key);
  14081. }
  14082. // Test that update_certs() updates client CA list correctly
  14083. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14084. // Start with file-based constructor
  14085. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14086. ASSERT_TRUE(svr.is_valid());
  14087. // Initially no client CA list should be set
  14088. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14089. ASSERT_TRUE(ssl_ctx != nullptr);
  14090. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14091. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14092. EXPECT_EQ(0, count_before);
  14093. // Now update with client CA (PEM string)
  14094. std::string cert_pem, key_pem, ca_pem;
  14095. read_file(SERVER_CERT_FILE, cert_pem);
  14096. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14097. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14098. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14099. ASSERT_TRUE(svr.is_valid());
  14100. // Now client CA list should be set
  14101. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14102. ASSERT_TRUE(ca_list_after != nullptr);
  14103. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14104. }
  14105. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14106. // Test that the file-path SSLServer constructor properly sets the client CA
  14107. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14108. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14109. ASSERT_TRUE(svr.is_valid());
  14110. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14111. ASSERT_TRUE(ssl_ctx != nullptr);
  14112. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14113. ASSERT_TRUE(ca_list != nullptr);
  14114. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14115. }
  14116. #endif
  14117. // ============================================================================
  14118. // MbedTLS-Specific Tests
  14119. // ============================================================================
  14120. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14121. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14122. using namespace httplib::tls;
  14123. // Track if callback was invoked
  14124. bool callback_invoked = false;
  14125. // The callback receives void* ctx which is actually MbedTlsContext*
  14126. // We can access the mbedtls_ssl_config via the context
  14127. auto setup_callback = [&callback_invoked](void *ctx) {
  14128. callback_invoked = true;
  14129. // Cast to MbedTlsContext* to access the ssl config
  14130. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14131. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14132. // Use static variables to hold certificate data (simplified for test)
  14133. static mbedtls_x509_crt own_cert;
  14134. static mbedtls_pk_context own_key;
  14135. static mbedtls_x509_crt ca_chain;
  14136. static bool initialized = false;
  14137. if (!initialized) {
  14138. mbedtls_x509_crt_init(&own_cert);
  14139. mbedtls_pk_init(&own_key);
  14140. mbedtls_x509_crt_init(&ca_chain);
  14141. // Load server certificate
  14142. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14143. return false;
  14144. }
  14145. // Load server private key
  14146. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14147. #if MBEDTLS_VERSION_MAJOR >= 3
  14148. ,
  14149. mbedtls_ctr_drbg_random, nullptr
  14150. #endif
  14151. ) != 0) {
  14152. return false;
  14153. }
  14154. // Load CA chain for client verification
  14155. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14156. return false;
  14157. }
  14158. initialized = true;
  14159. }
  14160. // Configure the SSL config
  14161. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14162. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14163. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14164. // Set minimum TLS version using mbedTLS native API
  14165. #if MBEDTLS_VERSION_MAJOR >= 3
  14166. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14167. #else
  14168. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14169. MBEDTLS_SSL_MINOR_VERSION_3);
  14170. #endif
  14171. return true;
  14172. };
  14173. SSLServer svr(setup_callback);
  14174. ASSERT_TRUE(svr.is_valid());
  14175. ASSERT_TRUE(callback_invoked);
  14176. svr.Get("/test", [&](const Request &req, Response &res) {
  14177. res.set_content("test", "text/plain");
  14178. auto cert = req.peer_cert();
  14179. ASSERT_TRUE(static_cast<bool>(cert));
  14180. auto common_name = cert.subject_cn();
  14181. EXPECT_EQ("Common Name", common_name);
  14182. });
  14183. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14184. auto se = detail::scope_exit([&] {
  14185. svr.stop();
  14186. t.join();
  14187. ASSERT_FALSE(svr.is_running());
  14188. });
  14189. svr.wait_until_ready();
  14190. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14191. cli.enable_server_certificate_verification(false);
  14192. cli.set_connection_timeout(30);
  14193. auto res = cli.Get("/test");
  14194. ASSERT_TRUE(res);
  14195. ASSERT_EQ(StatusCode::OK_200, res->status);
  14196. }
  14197. #endif
  14198. // WebSocket Tests
  14199. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14200. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14201. // defining the meaning of these bits has been negotiated.
  14202. auto make_frame = [](uint8_t first_byte) {
  14203. std::string frame;
  14204. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14205. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14206. frame += "Hello";
  14207. return frame;
  14208. };
  14209. // RSV1 set (0x40)
  14210. {
  14211. detail::BufferStream strm;
  14212. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14213. ws::Opcode opcode;
  14214. std::string payload;
  14215. bool fin;
  14216. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14217. false, 1024));
  14218. }
  14219. // RSV2 set (0x20)
  14220. {
  14221. detail::BufferStream strm;
  14222. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14223. ws::Opcode opcode;
  14224. std::string payload;
  14225. bool fin;
  14226. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14227. false, 1024));
  14228. }
  14229. // RSV3 set (0x10)
  14230. {
  14231. detail::BufferStream strm;
  14232. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14233. ws::Opcode opcode;
  14234. std::string payload;
  14235. bool fin;
  14236. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14237. false, 1024));
  14238. }
  14239. // No RSV bits set - should succeed
  14240. {
  14241. detail::BufferStream strm;
  14242. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14243. ws::Opcode opcode;
  14244. std::string payload;
  14245. bool fin;
  14246. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14247. false, 1024));
  14248. EXPECT_EQ(ws::Opcode::Text, opcode);
  14249. EXPECT_EQ("Hello", payload);
  14250. EXPECT_TRUE(fin);
  14251. }
  14252. }
  14253. TEST(WebSocketTest, ControlFrameValidation) {
  14254. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14255. // payload length <= 125.
  14256. // Ping with FIN=0 - must be rejected
  14257. {
  14258. detail::BufferStream strm;
  14259. std::string frame;
  14260. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14261. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14262. strm.write(frame.data(), frame.size());
  14263. ws::Opcode opcode;
  14264. std::string payload;
  14265. bool fin;
  14266. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14267. false, 1024));
  14268. }
  14269. // Close with FIN=0 - must be rejected
  14270. {
  14271. detail::BufferStream strm;
  14272. std::string frame;
  14273. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14274. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14275. strm.write(frame.data(), frame.size());
  14276. ws::Opcode opcode;
  14277. std::string payload;
  14278. bool fin;
  14279. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14280. false, 1024));
  14281. }
  14282. // Ping with payload_len=126 (extended length) - must be rejected
  14283. {
  14284. detail::BufferStream strm;
  14285. std::string frame;
  14286. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14287. frame += static_cast<char>(126); // payload_len=126 (>125)
  14288. frame += static_cast<char>(0x00); // extended length high byte
  14289. frame += static_cast<char>(126); // extended length low byte
  14290. frame += std::string(126, 'x');
  14291. strm.write(frame.data(), frame.size());
  14292. ws::Opcode opcode;
  14293. std::string payload;
  14294. bool fin;
  14295. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14296. false, 1024));
  14297. }
  14298. // Ping with FIN=1 and payload_len=125 - should succeed
  14299. {
  14300. detail::BufferStream strm;
  14301. std::string frame;
  14302. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14303. frame += static_cast<char>(125); // payload_len=125
  14304. frame += std::string(125, 'x');
  14305. strm.write(frame.data(), frame.size());
  14306. ws::Opcode opcode;
  14307. std::string payload;
  14308. bool fin;
  14309. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14310. false, 1024));
  14311. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14312. EXPECT_EQ(125u, payload.size());
  14313. EXPECT_TRUE(fin);
  14314. }
  14315. }
  14316. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14317. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14318. // length MUST be 0.
  14319. // MSB set - must be rejected
  14320. {
  14321. detail::BufferStream strm;
  14322. std::string frame;
  14323. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14324. frame += static_cast<char>(127); // 64-bit extended length
  14325. frame += static_cast<char>(0x80); // MSB set (invalid)
  14326. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14327. strm.write(frame.data(), frame.size());
  14328. ws::Opcode opcode;
  14329. std::string payload;
  14330. bool fin;
  14331. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14332. false, 1024));
  14333. }
  14334. // MSB clear - should pass length parsing (will be rejected by max_len,
  14335. // but that's a different check; use a small length to verify)
  14336. {
  14337. detail::BufferStream strm;
  14338. std::string frame;
  14339. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14340. frame += static_cast<char>(127); // 64-bit extended length
  14341. frame += std::string(7, '\0'); // high bytes = 0
  14342. frame += static_cast<char>(0x03); // length = 3
  14343. frame += "abc";
  14344. strm.write(frame.data(), frame.size());
  14345. ws::Opcode opcode;
  14346. std::string payload;
  14347. bool fin;
  14348. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14349. false, 1024));
  14350. EXPECT_EQ(ws::Opcode::Text, opcode);
  14351. EXPECT_EQ("abc", payload);
  14352. }
  14353. }
  14354. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14355. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14356. // Valid UTF-8
  14357. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14358. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14359. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14360. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14361. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14362. // Invalid UTF-8
  14363. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14364. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14365. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14366. EXPECT_FALSE(
  14367. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14368. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14369. }
  14370. TEST(WebSocketTest, ConnectAndDisconnect) {
  14371. Server svr;
  14372. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14373. std::string msg;
  14374. while (ws.read(msg)) {}
  14375. });
  14376. auto port = svr.bind_to_any_port(HOST);
  14377. std::thread t([&]() { svr.listen_after_bind(); });
  14378. svr.wait_until_ready();
  14379. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14380. ASSERT_TRUE(client.connect());
  14381. EXPECT_TRUE(client.is_open());
  14382. client.close();
  14383. EXPECT_FALSE(client.is_open());
  14384. svr.stop();
  14385. t.join();
  14386. }
  14387. TEST(WebSocketTest, ValidURL) {
  14388. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14389. EXPECT_TRUE(ws1.is_valid());
  14390. ws::WebSocketClient ws2("ws://example.com/path");
  14391. EXPECT_TRUE(ws2.is_valid());
  14392. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14393. EXPECT_TRUE(ws3.is_valid());
  14394. #ifdef CPPHTTPLIB_SSL_ENABLED
  14395. ws::WebSocketClient wss1("wss://example.com/path");
  14396. EXPECT_TRUE(wss1.is_valid());
  14397. ws::WebSocketClient wss2("wss://example.com:443/path");
  14398. EXPECT_TRUE(wss2.is_valid());
  14399. #endif
  14400. }
  14401. TEST(WebSocketTest, InvalidURL) {
  14402. // No scheme
  14403. ws::WebSocketClient ws1("localhost:8080/path");
  14404. EXPECT_FALSE(ws1.is_valid());
  14405. // No path
  14406. ws::WebSocketClient ws2("ws://localhost:8080");
  14407. EXPECT_FALSE(ws2.is_valid());
  14408. // Empty string
  14409. ws::WebSocketClient ws3("");
  14410. EXPECT_FALSE(ws3.is_valid());
  14411. // Missing host
  14412. ws::WebSocketClient ws4("ws://:8080/path");
  14413. EXPECT_FALSE(ws4.is_valid());
  14414. // Port number overflow — should not crash
  14415. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14416. EXPECT_FALSE(ws5.is_valid());
  14417. // Port out of range
  14418. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14419. EXPECT_FALSE(ws6.is_valid());
  14420. }
  14421. TEST(WebSocketTest, UnsupportedScheme) {
  14422. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14423. ws::WebSocketClient ws1("http://localhost:8080/path");
  14424. EXPECT_FALSE(ws1.is_valid());
  14425. ws::WebSocketClient ws2("https://localhost:8080/path");
  14426. EXPECT_FALSE(ws2.is_valid());
  14427. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14428. EXPECT_FALSE(ws3.is_valid());
  14429. #else
  14430. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14431. std::invalid_argument);
  14432. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14433. std::invalid_argument);
  14434. #endif
  14435. }
  14436. TEST(WebSocketTest, ConnectWhenInvalid) {
  14437. ws::WebSocketClient ws("not a valid url");
  14438. EXPECT_FALSE(ws.is_valid());
  14439. EXPECT_FALSE(ws.connect());
  14440. }
  14441. TEST(WebSocketTest, DefaultPort) {
  14442. ws::WebSocketClient ws1("ws://example.com/path");
  14443. EXPECT_TRUE(ws1.is_valid());
  14444. // ws:// defaults to port 80 (verified by successful parse)
  14445. #ifdef CPPHTTPLIB_SSL_ENABLED
  14446. ws::WebSocketClient ws2("wss://example.com/path");
  14447. EXPECT_TRUE(ws2.is_valid());
  14448. // wss:// defaults to port 443 (verified by successful parse)
  14449. #endif
  14450. }
  14451. TEST(WebSocketTest, IPv6LiteralAddress) {
  14452. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14453. EXPECT_TRUE(ws1.is_valid());
  14454. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14455. EXPECT_TRUE(ws2.is_valid());
  14456. }
  14457. TEST(WebSocketTest, ComplexPath) {
  14458. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14459. EXPECT_TRUE(ws1.is_valid());
  14460. ws::WebSocketClient ws2("ws://localhost:8080/");
  14461. EXPECT_TRUE(ws2.is_valid());
  14462. }
  14463. class WebSocketIntegrationTest : public ::testing::Test {
  14464. protected:
  14465. void SetUp() override {
  14466. server_ = httplib::detail::make_unique<Server>();
  14467. setup_server();
  14468. start_server();
  14469. }
  14470. void TearDown() override {
  14471. server_->stop();
  14472. if (server_thread_.joinable()) { server_thread_.join(); }
  14473. }
  14474. void setup_server() {
  14475. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14476. std::string msg;
  14477. ws::ReadResult ret;
  14478. while ((ret = ws.read(msg))) {
  14479. if (ret == ws::Binary) {
  14480. ws.send(msg.data(), msg.size());
  14481. } else {
  14482. ws.send(msg);
  14483. }
  14484. }
  14485. });
  14486. server_->WebSocket("/ws-echo-string",
  14487. [](const Request &, ws::WebSocket &ws) {
  14488. std::string msg;
  14489. while (ws.read(msg)) {
  14490. ws.send("echo: " + msg);
  14491. }
  14492. });
  14493. server_->WebSocket(
  14494. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14495. // Echo back request metadata
  14496. ws.send("path:" + req.path);
  14497. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14498. std::string msg;
  14499. while (ws.read(msg)) {}
  14500. });
  14501. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14502. std::string msg;
  14503. ws.read(msg); // wait for a message
  14504. ws.close();
  14505. });
  14506. server_->WebSocket("/ws-close-status",
  14507. [](const Request &, ws::WebSocket &ws) {
  14508. std::string msg;
  14509. ws.read(msg); // wait for a message
  14510. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14511. });
  14512. server_->WebSocket(
  14513. "/ws-subprotocol",
  14514. [](const Request &, ws::WebSocket &ws) {
  14515. std::string msg;
  14516. while (ws.read(msg)) {
  14517. ws.send(msg);
  14518. }
  14519. },
  14520. [](const std::vector<std::string> &protocols) -> std::string {
  14521. for (const auto &p : protocols) {
  14522. if (p == "graphql-ws") { return p; }
  14523. }
  14524. return "";
  14525. });
  14526. }
  14527. void start_server() {
  14528. port_ = server_->bind_to_any_port(HOST);
  14529. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14530. server_->wait_until_ready();
  14531. }
  14532. std::unique_ptr<Server> server_;
  14533. std::thread server_thread_;
  14534. int port_ = 0;
  14535. };
  14536. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14537. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14538. "/ws-echo");
  14539. ASSERT_TRUE(client.connect());
  14540. ASSERT_TRUE(client.is_open());
  14541. ASSERT_TRUE(client.send("Hello WebSocket"));
  14542. std::string msg;
  14543. EXPECT_EQ(ws::Text, client.read(msg));
  14544. EXPECT_EQ("Hello WebSocket", msg);
  14545. client.close();
  14546. }
  14547. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14548. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14549. "/ws-echo");
  14550. ASSERT_TRUE(client.connect());
  14551. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14552. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14553. std::string msg;
  14554. EXPECT_EQ(ws::Binary, client.read(msg));
  14555. EXPECT_EQ(binary_data, msg);
  14556. client.close();
  14557. }
  14558. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14559. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14560. "/ws-echo");
  14561. ASSERT_TRUE(client.connect());
  14562. for (int i = 0; i < 10; i++) {
  14563. auto text = "message " + std::to_string(i);
  14564. ASSERT_TRUE(client.send(text));
  14565. std::string msg;
  14566. ASSERT_TRUE(client.read(msg));
  14567. EXPECT_EQ(text, msg);
  14568. }
  14569. client.close();
  14570. }
  14571. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14572. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14573. "/ws-close");
  14574. ASSERT_TRUE(client.connect());
  14575. // Send a message to trigger the server to close
  14576. ASSERT_TRUE(client.send("trigger close"));
  14577. // The server will close, so read should return false
  14578. std::string msg;
  14579. EXPECT_FALSE(client.read(msg));
  14580. EXPECT_FALSE(client.is_open());
  14581. }
  14582. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14583. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14584. "/ws-echo");
  14585. ASSERT_TRUE(client.connect());
  14586. // 128KB message
  14587. std::string large_data(128 * 1024, 'X');
  14588. ASSERT_TRUE(client.send(large_data));
  14589. std::string msg;
  14590. ASSERT_TRUE(client.read(msg));
  14591. EXPECT_EQ(large_data, msg);
  14592. client.close();
  14593. }
  14594. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14595. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14596. "/ws-echo");
  14597. ASSERT_TRUE(client.connect());
  14598. const int num_threads = 4;
  14599. std::vector<std::thread> threads;
  14600. std::atomic<int> send_count{0};
  14601. for (int t = 0; t < num_threads; t++) {
  14602. threads.emplace_back([&client, &send_count, t]() {
  14603. for (int i = 0; i < 5; i++) {
  14604. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14605. if (client.send(text)) { send_count++; }
  14606. }
  14607. });
  14608. }
  14609. for (auto &th : threads) {
  14610. th.join();
  14611. }
  14612. int received = 0;
  14613. std::string msg;
  14614. while (received < send_count.load()) {
  14615. if (!client.read(msg)) { break; }
  14616. received++;
  14617. }
  14618. EXPECT_EQ(send_count.load(), received);
  14619. client.close();
  14620. }
  14621. TEST_F(WebSocketIntegrationTest, ReadString) {
  14622. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14623. "/ws-echo-string");
  14624. ASSERT_TRUE(client.connect());
  14625. ASSERT_TRUE(client.send("hello"));
  14626. std::string msg;
  14627. ASSERT_TRUE(client.read(msg));
  14628. EXPECT_EQ("echo: hello", msg);
  14629. ASSERT_TRUE(client.send("world"));
  14630. ASSERT_TRUE(client.read(msg));
  14631. EXPECT_EQ("echo: world", msg);
  14632. client.close();
  14633. }
  14634. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14635. Headers headers = {{"X-Test-Header", "test-value"}};
  14636. ws::WebSocketClient client(
  14637. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14638. ASSERT_TRUE(client.connect());
  14639. std::string msg;
  14640. ASSERT_TRUE(client.read(msg));
  14641. EXPECT_EQ("path:/ws-request-info", msg);
  14642. ASSERT_TRUE(client.read(msg));
  14643. EXPECT_EQ("header:test-value", msg);
  14644. client.close();
  14645. }
  14646. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14647. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14648. "/ws-echo");
  14649. client.set_read_timeout(1, 0); // 1 second
  14650. ASSERT_TRUE(client.connect());
  14651. // Don't send anything — server echo handler waits for a message,
  14652. // so read() should time out and return false.
  14653. std::string msg;
  14654. EXPECT_FALSE(client.read(msg));
  14655. }
  14656. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14657. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14658. "/ws-echo");
  14659. client.set_read_timeout(5, 0);
  14660. ASSERT_TRUE(client.connect());
  14661. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14662. // The server should reject it and close the connection.
  14663. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14664. client.send(oversized);
  14665. // The server's read() should have failed due to payload limit,
  14666. // so our read() should return false (connection closed).
  14667. std::string msg;
  14668. EXPECT_FALSE(client.read(msg));
  14669. }
  14670. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14671. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14672. "/ws-echo");
  14673. client.set_read_timeout(10, 0);
  14674. ASSERT_TRUE(client.connect());
  14675. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14676. // This should succeed.
  14677. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14678. ASSERT_TRUE(client.send(at_limit));
  14679. std::string msg;
  14680. ASSERT_TRUE(client.read(msg));
  14681. EXPECT_EQ(at_limit.size(), msg.size());
  14682. client.close();
  14683. }
  14684. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14685. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14686. "/nonexistent");
  14687. EXPECT_FALSE(client.connect());
  14688. EXPECT_FALSE(client.is_open());
  14689. }
  14690. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14691. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14692. "/ws-echo");
  14693. ASSERT_TRUE(client.connect());
  14694. ASSERT_TRUE(client.send(""));
  14695. std::string msg;
  14696. EXPECT_EQ(ws::Text, client.read(msg));
  14697. EXPECT_EQ("", msg);
  14698. client.close();
  14699. }
  14700. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14701. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14702. "/ws-echo");
  14703. // First connection
  14704. ASSERT_TRUE(client.connect());
  14705. ASSERT_TRUE(client.send("first"));
  14706. std::string msg;
  14707. ASSERT_TRUE(client.read(msg));
  14708. EXPECT_EQ("first", msg);
  14709. client.close();
  14710. EXPECT_FALSE(client.is_open());
  14711. // Reconnect using the same client object
  14712. ASSERT_TRUE(client.connect());
  14713. ASSERT_TRUE(client.is_open());
  14714. ASSERT_TRUE(client.send("second"));
  14715. ASSERT_TRUE(client.read(msg));
  14716. EXPECT_EQ("second", msg);
  14717. client.close();
  14718. }
  14719. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14720. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14721. "/ws-close-status");
  14722. ASSERT_TRUE(client.connect());
  14723. // Trigger the server to close with GoingAway status
  14724. ASSERT_TRUE(client.send("trigger"));
  14725. // read() should return false after receiving the close frame
  14726. std::string msg;
  14727. EXPECT_FALSE(client.read(msg));
  14728. EXPECT_FALSE(client.is_open());
  14729. }
  14730. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14731. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14732. "/ws-echo");
  14733. ASSERT_TRUE(client.connect());
  14734. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14735. EXPECT_FALSE(client.is_open());
  14736. }
  14737. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14738. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14739. ws::WebSocketClient client(
  14740. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14741. ASSERT_TRUE(client.connect());
  14742. // Server should have selected graphql-ws
  14743. EXPECT_EQ("graphql-ws", client.subprotocol());
  14744. client.close();
  14745. }
  14746. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14747. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14748. ws::WebSocketClient client(
  14749. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14750. ASSERT_TRUE(client.connect());
  14751. // Server should not have selected any subprotocol
  14752. EXPECT_TRUE(client.subprotocol().empty());
  14753. client.close();
  14754. }
  14755. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14756. // Connect without requesting any subprotocol
  14757. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14758. "/ws-subprotocol");
  14759. ASSERT_TRUE(client.connect());
  14760. EXPECT_TRUE(client.subprotocol().empty());
  14761. client.close();
  14762. }
  14763. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14764. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14765. "/ws-echo");
  14766. client.set_tcp_nodelay(true);
  14767. client.set_connection_timeout(3, 0);
  14768. bool socket_options_called = false;
  14769. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14770. ASSERT_TRUE(client.connect());
  14771. ASSERT_TRUE(client.is_open());
  14772. EXPECT_TRUE(socket_options_called);
  14773. ASSERT_TRUE(client.send("hello"));
  14774. std::string msg;
  14775. auto result = client.read(msg);
  14776. EXPECT_EQ(result, ws::ReadResult::Text);
  14777. EXPECT_EQ(msg, "hello");
  14778. client.close();
  14779. }
  14780. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14781. Server svr;
  14782. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14783. if (!req.has_header("Authorization")) {
  14784. res.status = StatusCode::Unauthorized_401;
  14785. res.set_content("Unauthorized", "text/plain");
  14786. return Server::HandlerResponse::Handled;
  14787. }
  14788. return Server::HandlerResponse::Unhandled;
  14789. });
  14790. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14791. std::string msg;
  14792. while (ws.read(msg)) {
  14793. ws.send(msg);
  14794. }
  14795. });
  14796. auto port = svr.bind_to_any_port("localhost");
  14797. std::thread t([&]() { svr.listen_after_bind(); });
  14798. svr.wait_until_ready();
  14799. // Without Authorization header - should be rejected before upgrade
  14800. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14801. EXPECT_FALSE(client1.connect());
  14802. // With Authorization header - should succeed
  14803. Headers headers = {{"Authorization", "Bearer token123"}};
  14804. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14805. headers);
  14806. ASSERT_TRUE(client2.connect());
  14807. ASSERT_TRUE(client2.send("hello"));
  14808. std::string msg;
  14809. ASSERT_TRUE(client2.read(msg));
  14810. EXPECT_EQ("hello", msg);
  14811. client2.close();
  14812. svr.stop();
  14813. t.join();
  14814. }
  14815. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14816. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14817. protected:
  14818. void SetUp() override {
  14819. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14820. SERVER_PRIVATE_KEY_FILE);
  14821. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14822. std::string msg;
  14823. ws::ReadResult ret;
  14824. while ((ret = ws.read(msg))) {
  14825. if (ret == ws::Binary) {
  14826. ws.send(msg.data(), msg.size());
  14827. } else {
  14828. ws.send(msg);
  14829. }
  14830. }
  14831. });
  14832. port_ = server_->bind_to_any_port(HOST);
  14833. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14834. server_->wait_until_ready();
  14835. }
  14836. void TearDown() override {
  14837. server_->stop();
  14838. if (server_thread_.joinable()) { server_thread_.join(); }
  14839. }
  14840. std::unique_ptr<SSLServer> server_;
  14841. std::thread server_thread_;
  14842. int port_ = 0;
  14843. };
  14844. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14845. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14846. "/ws-echo");
  14847. client.enable_server_certificate_verification(false);
  14848. ASSERT_TRUE(client.connect());
  14849. ASSERT_TRUE(client.is_open());
  14850. ASSERT_TRUE(client.send("Hello WSS"));
  14851. std::string msg;
  14852. EXPECT_EQ(ws::Text, client.read(msg));
  14853. EXPECT_EQ("Hello WSS", msg);
  14854. client.close();
  14855. }
  14856. #endif
  14857. #if !defined(_WIN32)
  14858. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14859. auto secret_dir = std::string("./symlink_test_secret");
  14860. auto served_dir = std::string("./symlink_test_served");
  14861. auto secret_file = secret_dir + "/secret.txt";
  14862. auto symlink_path = served_dir + "/escape";
  14863. // Setup: create directories and files
  14864. mkdir(secret_dir.c_str(), 0755);
  14865. mkdir(served_dir.c_str(), 0755);
  14866. {
  14867. std::ofstream ofs(secret_file);
  14868. ofs << "SECRET_DATA";
  14869. }
  14870. // Create symlink using absolute path so it resolves correctly
  14871. #ifdef PATH_MAX
  14872. char abs_secret[PATH_MAX];
  14873. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14874. #else
  14875. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  14876. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  14877. ASSERT_NE(nullptr, abs_secret);
  14878. #endif
  14879. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14880. auto se = detail::scope_exit([&] {
  14881. unlink(symlink_path.c_str());
  14882. unlink(secret_file.c_str());
  14883. rmdir(served_dir.c_str());
  14884. rmdir(secret_dir.c_str());
  14885. });
  14886. Server svr;
  14887. svr.set_mount_point("/", served_dir);
  14888. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14889. auto se2 = detail::scope_exit([&] {
  14890. svr.stop();
  14891. listen_thread.join();
  14892. });
  14893. svr.wait_until_ready();
  14894. Client cli("localhost", PORT);
  14895. // Symlink pointing outside base dir should be blocked
  14896. auto res = cli.Get("/escape/secret.txt");
  14897. ASSERT_TRUE(res);
  14898. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14899. }
  14900. #endif
  14901. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  14902. // A GET request with Content-Length to a static file handler must have its
  14903. // body drained before the keep-alive connection is reused. Otherwise the
  14904. // unread body bytes are interpreted as the next HTTP request.
  14905. //
  14906. // The body is sent AFTER receiving the first response (as in the original
  14907. // PoC) so that the stream_line_reader cannot buffer it together with the
  14908. // headers of the first request.
  14909. Server svr;
  14910. svr.set_mount_point("/", "./www");
  14911. std::atomic<int> smuggled_count(0);
  14912. svr.Get("/smuggled", [&](const Request &, Response &res) {
  14913. smuggled_count++;
  14914. res.set_content("oops", "text/plain");
  14915. });
  14916. auto port = svr.bind_to_any_port("localhost");
  14917. thread t = thread([&] { svr.listen_after_bind(); });
  14918. auto se = detail::scope_exit([&] {
  14919. svr.stop();
  14920. t.join();
  14921. });
  14922. svr.wait_until_ready();
  14923. auto error = Error::Success;
  14924. auto sock = detail::create_client_socket(
  14925. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  14926. /*connection_timeout_sec=*/2, 0,
  14927. /*read_timeout_sec=*/2, 0,
  14928. /*write_timeout_sec=*/2, 0, std::string(), error);
  14929. ASSERT_NE(INVALID_SOCKET, sock);
  14930. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  14931. // The "smuggled" request will be sent as the body of the outer GET
  14932. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  14933. "Host: localhost\r\n"
  14934. "Connection: close\r\n"
  14935. "\r\n";
  14936. // Step 1: Send only the outer request headers (no body yet)
  14937. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  14938. "Host: localhost\r\n"
  14939. "Content-Length: " +
  14940. std::to_string(smuggled.size()) +
  14941. "\r\n"
  14942. "\r\n";
  14943. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  14944. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  14945. // Step 2: Read the first response (server serves file without reading body)
  14946. std::string first_response;
  14947. char buf[4096];
  14948. for (;;) {
  14949. auto n = recv(sock, buf, sizeof(buf), 0);
  14950. if (n <= 0) break;
  14951. first_response.append(buf, static_cast<size_t>(n));
  14952. // Stop once we have a complete response (headers + body)
  14953. auto hdr_end = first_response.find("\r\n\r\n");
  14954. if (hdr_end != std::string::npos) {
  14955. // Check for Content-Length to know when the body is complete
  14956. auto cl_pos = first_response.find("Content-Length:");
  14957. if (cl_pos != std::string::npos) {
  14958. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  14959. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  14960. auto cl = std::stoul(
  14961. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  14962. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  14963. } else {
  14964. break; // No Content-Length, assume headers-only response
  14965. }
  14966. }
  14967. }
  14968. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  14969. // Step 3: Now send the body, which looks like a new HTTP request.
  14970. // On a vulnerable server the keep-alive loop reads this as a second request.
  14971. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  14972. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  14973. // Step 4: Try to read a second response (should NOT exist after fix)
  14974. std::string second_response;
  14975. for (;;) {
  14976. auto n = recv(sock, buf, sizeof(buf), 0);
  14977. if (n <= 0) break;
  14978. second_response.append(buf, static_cast<size_t>(n));
  14979. }
  14980. // The smuggled request must NOT have been processed
  14981. EXPECT_EQ(0, smuggled_count.load());
  14982. }
  14983. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  14984. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  14985. // must be rejected with 400 Bad Request.
  14986. Server svr;
  14987. svr.Post("/test", [&](const Request &, Response &res) {
  14988. res.set_content("ok", "text/plain");
  14989. });
  14990. thread t = thread([&] { svr.listen(HOST, PORT); });
  14991. auto se = detail::scope_exit([&] {
  14992. svr.stop();
  14993. t.join();
  14994. ASSERT_FALSE(svr.is_running());
  14995. });
  14996. svr.wait_until_ready();
  14997. // Exact "chunked"
  14998. {
  14999. auto req = "POST /test HTTP/1.1\r\n"
  15000. "Host: localhost\r\n"
  15001. "Content-Length: 5\r\n"
  15002. "Transfer-Encoding: chunked\r\n"
  15003. "Connection: close\r\n"
  15004. "\r\n"
  15005. "hello";
  15006. std::string response;
  15007. ASSERT_TRUE(send_request(1, req, &response));
  15008. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15009. response.substr(0, response.find("\r\n")));
  15010. }
  15011. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15012. {
  15013. auto req = "POST /test HTTP/1.1\r\n"
  15014. "Host: localhost\r\n"
  15015. "Content-Length: 5\r\n"
  15016. "Transfer-Encoding: gzip, chunked\r\n"
  15017. "Connection: close\r\n"
  15018. "\r\n"
  15019. "hello";
  15020. std::string response;
  15021. ASSERT_TRUE(send_request(1, req, &response));
  15022. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15023. response.substr(0, response.find("\r\n")));
  15024. }
  15025. }