test.cc 522 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082
  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. const int PORT = get_base_port();
  57. const string LONG_QUERY_VALUE = string(25000, '@');
  58. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  59. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  60. const string TOO_LONG_QUERY_URL =
  61. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  62. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  63. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  64. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  65. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  66. return file.name == key;
  67. });
  68. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  69. return *it;
  70. #else
  71. if (it != items.end()) { return *it; }
  72. throw std::runtime_error("invalid multipart form data name error");
  73. #endif
  74. }
  75. static void read_file(const std::string &path, std::string &out) {
  76. std::ifstream fs(path, std::ios_base::binary);
  77. if (!fs) {
  78. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  79. return;
  80. #else
  81. throw std::runtime_error("File not found: " + path);
  82. #endif
  83. }
  84. fs.seekg(0, std::ios_base::end);
  85. auto size = fs.tellg();
  86. fs.seekg(0);
  87. out.resize(static_cast<size_t>(size));
  88. fs.read(&out[0], static_cast<std::streamsize>(size));
  89. }
  90. class UnixSocketTest : public ::testing::Test {
  91. protected:
  92. void TearDown() override { std::remove(pathname_.c_str()); }
  93. void client_GET(const std::string &addr) {
  94. httplib::Client cli{addr};
  95. cli.set_address_family(AF_UNIX);
  96. ASSERT_TRUE(cli.is_valid());
  97. const auto &result = cli.Get(pattern_);
  98. ASSERT_TRUE(result) << "error: " << result.error();
  99. const auto &resp = result.value();
  100. EXPECT_EQ(resp.status, StatusCode::OK_200);
  101. EXPECT_EQ(resp.body, content_);
  102. }
  103. static std::string make_sock_path() {
  104. const char *shard = getenv("GTEST_SHARD_INDEX");
  105. return shard ? std::string("./httplib-server-") + shard + ".sock"
  106. : "./httplib-server.sock";
  107. }
  108. const std::string pathname_{make_sock_path()};
  109. const std::string pattern_{"/hi"};
  110. const std::string content_{"Hello World!"};
  111. };
  112. TEST_F(UnixSocketTest, pathname) {
  113. httplib::Server svr;
  114. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  115. res.set_content(content_, "text/plain");
  116. });
  117. std::thread t{[&] {
  118. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  119. }};
  120. auto se = detail::scope_exit([&] {
  121. svr.stop();
  122. t.join();
  123. ASSERT_FALSE(svr.is_running());
  124. });
  125. svr.wait_until_ready();
  126. ASSERT_TRUE(svr.is_running());
  127. client_GET(pathname_);
  128. }
  129. #if defined(__linux__) || \
  130. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  131. TEST_F(UnixSocketTest, PeerPid) {
  132. httplib::Server svr;
  133. std::string remote_port_val;
  134. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  135. res.set_content(content_, "text/plain");
  136. remote_port_val = std::to_string(req.remote_port);
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  150. }
  151. #endif
  152. #ifdef __linux__
  153. TEST_F(UnixSocketTest, abstract) {
  154. constexpr char svr_path[]{"\x00httplib-server.sock"};
  155. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  156. httplib::Server svr;
  157. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(abstract_addr);
  171. }
  172. #endif
  173. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  174. httplib::Server svr;
  175. std::string received_host_header;
  176. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  177. // Capture the Host header sent by the client
  178. auto host_iter = req.headers.find("Host");
  179. if (host_iter != req.headers.end()) {
  180. received_host_header = host_iter->second;
  181. }
  182. res.set_content(content_, "text/plain");
  183. });
  184. std::thread t{[&] {
  185. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  186. }};
  187. auto se = detail::scope_exit([&] {
  188. svr.stop();
  189. t.join();
  190. ASSERT_FALSE(svr.is_running());
  191. });
  192. svr.wait_until_ready();
  193. ASSERT_TRUE(svr.is_running());
  194. // Test that Host header is automatically set to "localhost" for Unix socket
  195. // connections
  196. httplib::Client cli{pathname_};
  197. cli.set_address_family(AF_UNIX);
  198. ASSERT_TRUE(cli.is_valid());
  199. const auto &result = cli.Get(pattern_);
  200. ASSERT_TRUE(result) << "error: " << result.error();
  201. const auto &resp = result.value();
  202. EXPECT_EQ(resp.status, StatusCode::OK_200);
  203. EXPECT_EQ(resp.body, content_);
  204. // Verify that Host header was automatically set to "localhost"
  205. EXPECT_EQ(received_host_header, "localhost");
  206. }
  207. #ifndef _WIN32
  208. TEST(SocketStream, wait_writable_UNIX) {
  209. int fds[2];
  210. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  211. const auto asSocketStream = [&](socket_t fd,
  212. std::function<bool(Stream &)> func) {
  213. return detail::process_client_socket(
  214. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  215. };
  216. asSocketStream(fds[0], [&](Stream &s0) {
  217. EXPECT_EQ(s0.socket(), fds[0]);
  218. EXPECT_TRUE(s0.wait_writable());
  219. EXPECT_TRUE(s0.is_peer_alive());
  220. EXPECT_EQ(0, close(fds[1]));
  221. EXPECT_FALSE(s0.is_peer_alive());
  222. return true;
  223. });
  224. EXPECT_EQ(0, close(fds[0]));
  225. }
  226. TEST(SocketStream, wait_writable_INET) {
  227. sockaddr_in addr;
  228. memset(&addr, 0, sizeof(addr));
  229. addr.sin_family = AF_INET;
  230. addr.sin_port = htons(PORT + 1);
  231. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  232. int disconnected_svr_sock = -1;
  233. std::thread svr{[&] {
  234. const int s = socket(AF_INET, SOCK_STREAM, 0);
  235. ASSERT_LE(0, s);
  236. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  237. ASSERT_EQ(0, listen(s, 1));
  238. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  239. ASSERT_EQ(0, close(s));
  240. }};
  241. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  242. std::thread cli{[&] {
  243. const int s = socket(AF_INET, SOCK_STREAM, 0);
  244. ASSERT_LE(0, s);
  245. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  246. ASSERT_EQ(0, close(s));
  247. }};
  248. cli.join();
  249. svr.join();
  250. ASSERT_NE(disconnected_svr_sock, -1);
  251. const auto asSocketStream = [&](socket_t fd,
  252. std::function<bool(Stream &)> func) {
  253. return detail::process_client_socket(
  254. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  255. };
  256. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  257. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  258. // wait_writable() returns true because select_write() only checks if the
  259. // send buffer has space. Peer disconnection is detected later by send().
  260. EXPECT_TRUE(ss.wait_writable());
  261. return true;
  262. });
  263. ASSERT_EQ(0, close(disconnected_svr_sock));
  264. }
  265. #endif // #ifndef _WIN32
  266. TEST(ClientTest, MoveConstructible) {
  267. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  268. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  269. }
  270. TEST(ClientTest, MoveAssignable) {
  271. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  272. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  273. }
  274. #ifdef _WIN32
  275. TEST(StartupTest, WSAStartup) {
  276. WSADATA wsaData;
  277. int ret = WSAStartup(0x0002, &wsaData);
  278. ASSERT_EQ(0, ret);
  279. }
  280. #endif
  281. TEST(DecodePathTest, PercentCharacter) {
  282. EXPECT_EQ(
  283. decode_path_component(
  284. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  285. U8("descrip=Gastos áéíóúñÑ 6"));
  286. }
  287. TEST(DecodePathTest, PercentCharacterNUL) {
  288. string expected;
  289. expected.push_back('x');
  290. expected.push_back('\0');
  291. expected.push_back('x');
  292. EXPECT_EQ(decode_path_component("x%00x"), expected);
  293. }
  294. TEST(DecodePathTest, UnicodeEncoding) {
  295. // %u0041 = 'A' (1-byte UTF-8)
  296. EXPECT_EQ("A", decode_path_component("%u0041"));
  297. // %u00E9 = 'é' (2-byte UTF-8)
  298. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  299. // %u3042 = 'あ' (3-byte UTF-8)
  300. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  301. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  302. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  303. // %uD800 = surrogate (invalid, silently dropped)
  304. EXPECT_EQ("", decode_path_component("%uD800"));
  305. }
  306. TEST(SanitizeFilenameTest, VariousPatterns) {
  307. // Path traversal
  308. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  309. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  310. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  311. // Normal and edge cases
  312. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  313. EXPECT_EQ("filename.txt",
  314. httplib::sanitize_filename("/path/to/filename.txt"));
  315. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  316. EXPECT_EQ("", httplib::sanitize_filename(".."));
  317. EXPECT_EQ("", httplib::sanitize_filename(""));
  318. // Null bytes stripped
  319. EXPECT_EQ("safe.txt",
  320. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  321. // Whitespace-only rejected
  322. EXPECT_EQ("", httplib::sanitize_filename(" "));
  323. }
  324. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  325. string unescapedCharacters = "-_.!~*'()";
  326. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  327. }
  328. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  329. string reservedCharacters = ";,/?:@&=+$";
  330. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  331. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  332. }
  333. TEST(ClientQueryOrder, PreserveOrder) {
  334. // This test reproduces Issue #2259: client may reorder query parameters
  335. // when sending a GET request. The expected behavior is that the client
  336. // preserves the original query string order when the caller supplied it
  337. // as part of the path.
  338. Server svr;
  339. svr.Get("/", [&](const Request &req, Response &res) {
  340. // Echo back the raw target so the test can assert ordering
  341. res.set_content(req.target, "text/plain");
  342. });
  343. std::thread t{[&] { svr.listen(HOST, PORT); }};
  344. auto se = detail::scope_exit([&] {
  345. svr.stop();
  346. t.join();
  347. ASSERT_FALSE(svr.is_running());
  348. });
  349. svr.wait_until_ready();
  350. Client cli(HOST, PORT);
  351. ASSERT_TRUE(cli.is_valid());
  352. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  353. auto res = cli.Get(original);
  354. ASSERT_TRUE(res);
  355. // Expect the echoed target to exactly match the original path (order
  356. // preserved)
  357. EXPECT_EQ(res->body, original);
  358. }
  359. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  360. string chineseCharacters = U8("中国語");
  361. string russianCharacters = U8("дом");
  362. string brazilianCharacters = U8("óculos");
  363. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  364. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  365. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  366. "%D0%B4%D0%BE%D0%BC");
  367. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  368. }
  369. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  370. string unescapedCharacters = "-_.!~*'()";
  371. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  372. }
  373. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  374. string reservedCharacters = ";,/?:@&=+$";
  375. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  376. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  377. }
  378. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  379. string chineseCharacters = U8("中国語");
  380. string russianCharacters = U8("дом");
  381. string brazilianCharacters = U8("óculos");
  382. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  383. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  384. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  385. "%D0%B4%D0%BE%D0%BC");
  386. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  387. }
  388. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  389. // Issue #2082 use case: encoding path component with ampersand
  390. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  391. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  392. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  393. }
  394. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  395. string unescapedCharacters = "-_.!~*'()";
  396. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  397. }
  398. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  399. string reservedCharacters = ";,/?:@&=+$#";
  400. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  401. }
  402. TEST(EncodeUriTest, TestUTF8Characters) {
  403. string chineseCharacters = U8("中国語");
  404. string russianCharacters = U8("дом");
  405. string brazilianCharacters = U8("óculos");
  406. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  407. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  408. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  409. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  410. }
  411. TEST(EncodeUriTest, TestCompleteUri) {
  412. string uri =
  413. "https://example.com/path/to/resource?query=value&param=test#fragment";
  414. EXPECT_EQ(
  415. httplib::encode_uri(uri),
  416. "https://example.com/path/to/resource?query=value&param=test#fragment");
  417. }
  418. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  419. string uri =
  420. "https://example.com/path with spaces/file name.html?q=hello world";
  421. EXPECT_EQ(httplib::encode_uri(uri),
  422. "https://example.com/path%20with%20spaces/"
  423. "file%20name.html?q=hello%20world");
  424. }
  425. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  426. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  427. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  428. }
  429. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  430. string unescapedCharacters = "-_.!~*'()";
  431. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  432. }
  433. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  434. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  435. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  436. string encodedBrazilian = "%C3%B3culos";
  437. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  438. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  439. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  440. }
  441. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  442. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  443. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  444. "Piri Tommy Villiers - on & on");
  445. }
  446. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  447. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  448. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  449. }
  450. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  451. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  452. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  453. }
  454. TEST(DecodeUriTest, TestUTF8Characters) {
  455. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  456. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  457. string encodedBrazilian = "%C3%B3culos";
  458. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  459. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  460. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  461. }
  462. TEST(DecodeUriTest, TestCompleteUri) {
  463. string encodedUri = "https://example.com/path%20with%20spaces/"
  464. "file%20name.html?q=hello%20world";
  465. EXPECT_EQ(
  466. httplib::decode_uri(encodedUri),
  467. "https://example.com/path with spaces/file name.html?q=hello world");
  468. }
  469. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  470. string original =
  471. "https://example.com/path with spaces/file name.html?q=hello world";
  472. string encoded = httplib::encode_uri(original);
  473. string decoded = httplib::decode_uri(encoded);
  474. EXPECT_EQ(decoded, original);
  475. }
  476. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  477. string original = "Piri Tommy Villiers - on & on";
  478. string encoded = httplib::encode_uri_component(original);
  479. string decoded = httplib::decode_uri_component(encoded);
  480. EXPECT_EQ(decoded, original);
  481. }
  482. TEST(TrimTests, TrimStringTests) {
  483. EXPECT_EQ("abc", detail::trim_copy("abc"));
  484. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  485. EXPECT_TRUE(detail::trim_copy("").empty());
  486. }
  487. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  488. // Simple case without quality values
  489. std::vector<std::string> result1;
  490. EXPECT_TRUE(detail::parse_accept_header(
  491. "text/html,application/json,text/plain", result1));
  492. EXPECT_EQ(result1.size(), 3U);
  493. EXPECT_EQ(result1[0], "text/html");
  494. EXPECT_EQ(result1[1], "application/json");
  495. EXPECT_EQ(result1[2], "text/plain");
  496. // With quality values
  497. std::vector<std::string> result2;
  498. EXPECT_TRUE(detail::parse_accept_header(
  499. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  500. EXPECT_EQ(result2.size(), 3U);
  501. EXPECT_EQ(result2[0], "application/json"); // highest q value
  502. EXPECT_EQ(result2[1], "text/html");
  503. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  504. }
  505. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  506. // Mixed with and without quality values
  507. std::vector<std::string> result;
  508. EXPECT_TRUE(detail::parse_accept_header(
  509. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  510. EXPECT_EQ(result.size(), 3U);
  511. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  512. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  513. EXPECT_EQ(result[2], "application/json"); // q=0.5
  514. }
  515. TEST(ParseAcceptHeaderTest, EdgeCases) {
  516. // Empty header
  517. std::vector<std::string> empty_result;
  518. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  519. EXPECT_TRUE(empty_result.empty());
  520. // Single type
  521. std::vector<std::string> single_result;
  522. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  523. EXPECT_EQ(single_result.size(), 1U);
  524. EXPECT_EQ(single_result[0], "application/json");
  525. // Wildcard types
  526. std::vector<std::string> wildcard_result;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  529. EXPECT_EQ(wildcard_result.size(), 3U);
  530. EXPECT_EQ(wildcard_result[0], "application/json");
  531. EXPECT_EQ(wildcard_result[1], "text/*");
  532. EXPECT_EQ(wildcard_result[2], "*/*");
  533. }
  534. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  535. // Common browser Accept header
  536. std::vector<std::string> browser_result;
  537. EXPECT_TRUE(
  538. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  539. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  540. browser_result));
  541. EXPECT_EQ(browser_result.size(), 6U);
  542. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  543. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  544. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  547. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  548. // API client header
  549. std::vector<std::string> api_result;
  550. EXPECT_TRUE(detail::parse_accept_header(
  551. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  552. api_result));
  553. EXPECT_EQ(api_result.size(), 3U);
  554. EXPECT_EQ(api_result[0], "application/json");
  555. EXPECT_EQ(api_result[1], "application/xml");
  556. EXPECT_EQ(api_result[2], "text/plain");
  557. }
  558. TEST(ParseAcceptHeaderTest, SpecialCases) {
  559. // Quality value with 3 decimal places
  560. std::vector<std::string> decimal_result;
  561. EXPECT_TRUE(detail::parse_accept_header(
  562. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  563. EXPECT_EQ(decimal_result.size(), 2U);
  564. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  565. EXPECT_EQ(decimal_result[1], "text/html");
  566. // Zero quality (should still be included but with lowest priority)
  567. std::vector<std::string> zero_q_result;
  568. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  569. zero_q_result));
  570. EXPECT_EQ(zero_q_result.size(), 2U);
  571. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  572. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  573. // No spaces around commas
  574. std::vector<std::string> no_space_result;
  575. EXPECT_TRUE(detail::parse_accept_header(
  576. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  577. no_space_result));
  578. EXPECT_EQ(no_space_result.size(), 3U);
  579. EXPECT_EQ(no_space_result[0], "text/html");
  580. EXPECT_EQ(no_space_result[1], "application/json");
  581. EXPECT_EQ(no_space_result[2], "text/plain");
  582. }
  583. TEST(ParseAcceptHeaderTest, InvalidCases) {
  584. std::vector<std::string> result;
  585. // Invalid quality value (> 1.0)
  586. EXPECT_FALSE(
  587. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  588. // Invalid quality value (< 0.0)
  589. EXPECT_FALSE(
  590. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  591. // Invalid quality value (not a number)
  592. EXPECT_FALSE(detail::parse_accept_header(
  593. "text/html;q=invalid,application/json", result));
  594. // Empty quality value
  595. EXPECT_FALSE(
  596. detail::parse_accept_header("text/html;q=,application/json", result));
  597. // Invalid media type format (no slash and not wildcard)
  598. EXPECT_FALSE(
  599. detail::parse_accept_header("invalidtype,application/json", result));
  600. // Empty media type
  601. result.clear();
  602. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  603. // Only commas
  604. result.clear();
  605. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  606. // Valid cases should still work
  607. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  608. EXPECT_EQ(result.size(), 1U);
  609. EXPECT_EQ(result[0], "*/*");
  610. EXPECT_TRUE(detail::parse_accept_header("*", result));
  611. EXPECT_EQ(result.size(), 1U);
  612. EXPECT_EQ(result[0], "*");
  613. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  614. EXPECT_EQ(result.size(), 1U);
  615. EXPECT_EQ(result[0], "text/*");
  616. }
  617. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  618. Server svr;
  619. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  620. EXPECT_EQ(req.accept_content_types.size(), 3U);
  621. EXPECT_EQ(req.accept_content_types[0], "application/json");
  622. EXPECT_EQ(req.accept_content_types[1], "text/html");
  623. EXPECT_EQ(req.accept_content_types[2], "*/*");
  624. res.set_content("ok", "text/plain");
  625. });
  626. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  627. EXPECT_TRUE(false);
  628. res.set_content("bad request", "text/plain");
  629. });
  630. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  631. auto se = detail::scope_exit([&] {
  632. svr.stop();
  633. listen_thread.join();
  634. ASSERT_FALSE(svr.is_running());
  635. });
  636. svr.wait_until_ready();
  637. Client cli("localhost", PORT);
  638. {
  639. auto res =
  640. cli.Get("/accept_ok",
  641. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  642. ASSERT_TRUE(res);
  643. EXPECT_EQ(StatusCode::OK_200, res->status);
  644. }
  645. {
  646. auto res = cli.Get("/accept_bad_request",
  647. {{"Accept", "text/html;q=abc,application/json"}});
  648. ASSERT_TRUE(res);
  649. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  650. }
  651. }
  652. TEST(DivideTest, DivideStringTests) {
  653. auto divide = [](const std::string &str, char d) {
  654. std::string lhs;
  655. std::string rhs;
  656. detail::divide(str, d,
  657. [&](const char *lhs_data, std::size_t lhs_size,
  658. const char *rhs_data, std::size_t rhs_size) {
  659. lhs.assign(lhs_data, lhs_size);
  660. rhs.assign(rhs_data, rhs_size);
  661. });
  662. return std::make_pair(std::move(lhs), std::move(rhs));
  663. };
  664. {
  665. const auto res = divide("", '=');
  666. EXPECT_EQ(res.first, "");
  667. EXPECT_EQ(res.second, "");
  668. }
  669. {
  670. const auto res = divide("=", '=');
  671. EXPECT_EQ(res.first, "");
  672. EXPECT_EQ(res.second, "");
  673. }
  674. {
  675. const auto res = divide(" ", '=');
  676. EXPECT_EQ(res.first, " ");
  677. EXPECT_EQ(res.second, "");
  678. }
  679. {
  680. const auto res = divide("a", '=');
  681. EXPECT_EQ(res.first, "a");
  682. EXPECT_EQ(res.second, "");
  683. }
  684. {
  685. const auto res = divide("a=", '=');
  686. EXPECT_EQ(res.first, "a");
  687. EXPECT_EQ(res.second, "");
  688. }
  689. {
  690. const auto res = divide("=b", '=');
  691. EXPECT_EQ(res.first, "");
  692. EXPECT_EQ(res.second, "b");
  693. }
  694. {
  695. const auto res = divide("a=b", '=');
  696. EXPECT_EQ(res.first, "a");
  697. EXPECT_EQ(res.second, "b");
  698. }
  699. {
  700. const auto res = divide("a=b=", '=');
  701. EXPECT_EQ(res.first, "a");
  702. EXPECT_EQ(res.second, "b=");
  703. }
  704. {
  705. const auto res = divide("a=b=c", '=');
  706. EXPECT_EQ(res.first, "a");
  707. EXPECT_EQ(res.second, "b=c");
  708. }
  709. }
  710. TEST(SplitTest, ParseQueryString) {
  711. string s = "key1=val1&key2=val2&key3=val3";
  712. Params dic;
  713. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  714. [&](const char *b, const char *e) {
  715. string key, val;
  716. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  717. if (key.empty()) {
  718. key.assign(b2, e2);
  719. } else {
  720. val.assign(b2, e2);
  721. }
  722. });
  723. dic.emplace(key, val);
  724. });
  725. EXPECT_EQ("val1", dic.find("key1")->second);
  726. EXPECT_EQ("val2", dic.find("key2")->second);
  727. EXPECT_EQ("val3", dic.find("key3")->second);
  728. }
  729. TEST(SplitTest, ParseInvalidQueryTests) {
  730. {
  731. string s = " ";
  732. Params dict;
  733. detail::parse_query_text(s, dict);
  734. EXPECT_TRUE(dict.empty());
  735. }
  736. {
  737. string s = " = =";
  738. Params dict;
  739. detail::parse_query_text(s, dict);
  740. EXPECT_TRUE(dict.empty());
  741. }
  742. }
  743. TEST(ParseQueryTest, ParseQueryString) {
  744. {
  745. std::string s = "key1=val1&key2=val2&key3=val3";
  746. Params dic;
  747. detail::parse_query_text(s, dic);
  748. EXPECT_EQ("val1", dic.find("key1")->second);
  749. EXPECT_EQ("val2", dic.find("key2")->second);
  750. EXPECT_EQ("val3", dic.find("key3")->second);
  751. }
  752. {
  753. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  754. Params dic;
  755. detail::parse_query_text(s, dic);
  756. EXPECT_EQ("", dic.find("key1")->second);
  757. EXPECT_EQ("val1", dic.find("key2")->second);
  758. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  759. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  760. }
  761. }
  762. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  763. Params dic;
  764. EXPECT_EQ(detail::params_to_query_str(dic), "");
  765. dic.emplace("key1", "val1");
  766. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  767. dic.emplace("key2", "val2");
  768. dic.emplace("key3", "val3");
  769. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  770. }
  771. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  772. string content_type = "multipart/form-data; boundary=something";
  773. string boundary;
  774. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  775. EXPECT_TRUE(ret);
  776. EXPECT_EQ(boundary, "something");
  777. }
  778. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  779. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  780. string boundary;
  781. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  782. EXPECT_TRUE(ret);
  783. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  784. }
  785. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  786. string content_type =
  787. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  788. string boundary;
  789. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  790. EXPECT_TRUE(ret);
  791. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  792. }
  793. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  794. string content_type =
  795. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  796. string boundary;
  797. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  798. EXPECT_TRUE(ret);
  799. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  800. }
  801. TEST(GetHeaderValueTest, DefaultValue) {
  802. Headers headers = {{"Dummy", "Dummy"}};
  803. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  804. EXPECT_STREQ("text/plain", val);
  805. }
  806. TEST(GetHeaderValueTest, DefaultValueInt) {
  807. Headers headers = {{"Dummy", "Dummy"}};
  808. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  809. EXPECT_EQ(100ull, val);
  810. }
  811. TEST(GetHeaderValueTest, RegularValue) {
  812. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  813. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  814. EXPECT_STREQ("text/html", val);
  815. }
  816. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  817. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  818. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  819. EXPECT_STREQ("text/html", val);
  820. }
  821. TEST(GetHeaderValueTest, SetContent) {
  822. Response res;
  823. res.set_content("html", "text/html");
  824. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  825. res.set_content("text", "text/plain");
  826. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  827. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  828. }
  829. TEST(GetHeaderValueTest, RegularValueInt) {
  830. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  831. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  832. EXPECT_EQ(100ull, val);
  833. }
  834. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  835. Headers headers = {{"Content-Length", "x"}};
  836. auto is_invalid_value = false;
  837. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  838. is_invalid_value);
  839. EXPECT_EQ(0ull, val);
  840. EXPECT_TRUE(is_invalid_value);
  841. }
  842. TEST(GetHeaderValueTest, Range) {
  843. {
  844. Headers headers = {make_range_header({{1, -1}})};
  845. auto val = detail::get_header_value(headers, "Range", 0, 0);
  846. EXPECT_STREQ("bytes=1-", val);
  847. }
  848. {
  849. Headers headers = {make_range_header({{-1, 1}})};
  850. auto val = detail::get_header_value(headers, "Range", 0, 0);
  851. EXPECT_STREQ("bytes=-1", val);
  852. }
  853. {
  854. Headers headers = {make_range_header({{1, 10}})};
  855. auto val = detail::get_header_value(headers, "Range", 0, 0);
  856. EXPECT_STREQ("bytes=1-10", val);
  857. }
  858. {
  859. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  860. auto val = detail::get_header_value(headers, "Range", 0, 0);
  861. EXPECT_STREQ("bytes=1-10, 100-", val);
  862. }
  863. {
  864. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  865. auto val = detail::get_header_value(headers, "Range", 0, 0);
  866. EXPECT_STREQ("bytes=1-10, 100-200", val);
  867. }
  868. {
  869. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  870. auto val = detail::get_header_value(headers, "Range", 0, 0);
  871. EXPECT_STREQ("bytes=0-0, -1", val);
  872. }
  873. }
  874. TEST(ParseHeaderValueTest, Range) {
  875. {
  876. Ranges ranges;
  877. auto ret = detail::parse_range_header("bytes=1-", ranges);
  878. EXPECT_TRUE(ret);
  879. EXPECT_EQ(1u, ranges.size());
  880. EXPECT_EQ(1u, ranges[0].first);
  881. EXPECT_EQ(-1, ranges[0].second);
  882. }
  883. {
  884. Ranges ranges;
  885. auto ret = detail::parse_range_header("bytes=-1", ranges);
  886. EXPECT_TRUE(ret);
  887. EXPECT_EQ(1u, ranges.size());
  888. EXPECT_EQ(-1, ranges[0].first);
  889. EXPECT_EQ(1u, ranges[0].second);
  890. }
  891. {
  892. Ranges ranges;
  893. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  894. EXPECT_TRUE(ret);
  895. EXPECT_EQ(1u, ranges.size());
  896. EXPECT_EQ(1u, ranges[0].first);
  897. EXPECT_EQ(10u, ranges[0].second);
  898. }
  899. {
  900. Ranges ranges;
  901. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  902. EXPECT_FALSE(ret);
  903. }
  904. {
  905. Ranges ranges;
  906. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  907. EXPECT_TRUE(ret);
  908. EXPECT_EQ(2u, ranges.size());
  909. EXPECT_EQ(1u, ranges[0].first);
  910. EXPECT_EQ(10u, ranges[0].second);
  911. EXPECT_EQ(100u, ranges[1].first);
  912. EXPECT_EQ(-1, ranges[1].second);
  913. }
  914. {
  915. Ranges ranges;
  916. auto ret =
  917. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  918. EXPECT_TRUE(ret);
  919. EXPECT_EQ(3u, ranges.size());
  920. EXPECT_EQ(1u, ranges[0].first);
  921. EXPECT_EQ(10u, ranges[0].second);
  922. EXPECT_EQ(100u, ranges[1].first);
  923. EXPECT_EQ(200u, ranges[1].second);
  924. EXPECT_EQ(300u, ranges[2].first);
  925. EXPECT_EQ(400u, ranges[2].second);
  926. }
  927. {
  928. Ranges ranges;
  929. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  930. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  936. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  942. EXPECT_TRUE(ranges.empty());
  943. }
  944. }
  945. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  946. Request req;
  947. req.set_header("Accept-Encoding", "gzip");
  948. Response res;
  949. res.set_header("Content-Type", "text/plain");
  950. auto ret = detail::encoding_type(req, res);
  951. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  952. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  953. #else
  954. EXPECT_TRUE(ret == detail::EncodingType::None);
  955. #endif
  956. }
  957. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  958. Request req;
  959. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  960. Response res;
  961. res.set_header("Content-Type", "text/plain");
  962. auto ret = detail::encoding_type(req, res);
  963. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  964. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  965. #elif CPPHTTPLIB_ZLIB_SUPPORT
  966. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  967. #elif CPPHTTPLIB_ZSTD_SUPPORT
  968. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  969. #else
  970. EXPECT_TRUE(ret == detail::EncodingType::None);
  971. #endif
  972. }
  973. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  974. Request req;
  975. req.set_header("Accept-Encoding",
  976. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  977. Response res;
  978. res.set_header("Content-Type", "text/plain");
  979. auto ret = detail::encoding_type(req, res);
  980. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  981. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  982. #elif CPPHTTPLIB_ZLIB_SUPPORT
  983. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  984. #elif CPPHTTPLIB_ZSTD_SUPPORT
  985. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  986. #else
  987. EXPECT_TRUE(ret == detail::EncodingType::None);
  988. #endif
  989. }
  990. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  991. // All supported encodings rejected with q=0 should return None
  992. Request req;
  993. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  994. Response res;
  995. res.set_header("Content-Type", "text/plain");
  996. auto ret = detail::encoding_type(req, res);
  997. EXPECT_TRUE(ret == detail::EncodingType::None);
  998. }
  999. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1000. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1001. Request req;
  1002. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1003. Response res;
  1004. res.set_header("Content-Type", "text/plain");
  1005. auto ret = detail::encoding_type(req, res);
  1006. EXPECT_TRUE(ret == detail::EncodingType::None);
  1007. }
  1008. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1009. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1010. Request req;
  1011. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1012. Response res;
  1013. res.set_header("Content-Type", "text/plain");
  1014. auto ret = detail::encoding_type(req, res);
  1015. EXPECT_TRUE(ret == detail::EncodingType::None);
  1016. }
  1017. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1018. // RFC 7231: Accept-Encoding values are case-insensitive
  1019. Request req;
  1020. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1021. Response res;
  1022. res.set_header("Content-Type", "text/plain");
  1023. auto ret = detail::encoding_type(req, res);
  1024. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1025. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1026. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1027. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1028. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1029. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1030. #else
  1031. EXPECT_TRUE(ret == detail::EncodingType::None);
  1032. #endif
  1033. }
  1034. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1035. // q value should determine priority, not hardcoded order
  1036. Request req;
  1037. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1038. Response res;
  1039. res.set_header("Content-Type", "text/plain");
  1040. auto ret = detail::encoding_type(req, res);
  1041. // gzip has highest q=1.0, so it should be selected even though
  1042. // br and zstd are also supported
  1043. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1044. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1045. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1046. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1047. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1048. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1049. #else
  1050. EXPECT_TRUE(ret == detail::EncodingType::None);
  1051. #endif
  1052. }
  1053. TEST(BufferStreamTest, read) {
  1054. detail::BufferStream strm1;
  1055. Stream &strm = strm1;
  1056. EXPECT_EQ(5, strm.write("hello"));
  1057. char buf[512];
  1058. EXPECT_EQ(2, strm.read(buf, 2));
  1059. EXPECT_EQ('h', buf[0]);
  1060. EXPECT_EQ('e', buf[1]);
  1061. EXPECT_EQ(2, strm.read(buf, 2));
  1062. EXPECT_EQ('l', buf[0]);
  1063. EXPECT_EQ('l', buf[1]);
  1064. EXPECT_EQ(1, strm.read(buf, 1));
  1065. EXPECT_EQ('o', buf[0]);
  1066. EXPECT_EQ(0, strm.read(buf, 1));
  1067. }
  1068. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1069. auto host = "www.httpwatch.com";
  1070. auto ip = hosted_at(host);
  1071. EXPECT_EQ("23.96.13.243", ip);
  1072. std::vector<std::string> addrs;
  1073. hosted_at(host, addrs);
  1074. EXPECT_EQ(1u, addrs.size());
  1075. }
  1076. #if 0 // It depends on each test environment...
  1077. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1078. auto host = "www.youtube.com";
  1079. std::vector<std::string> addrs;
  1080. hosted_at(host, addrs);
  1081. EXPECT_EQ(20u, addrs.size());
  1082. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1083. EXPECT_TRUE(it != addrs.end());
  1084. }
  1085. #endif
  1086. class ChunkedEncodingTest : public ::testing::Test {
  1087. protected:
  1088. ChunkedEncodingTest()
  1089. : cli_(HOST, PORT)
  1090. #ifdef CPPHTTPLIB_SSL_ENABLED
  1091. ,
  1092. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1093. #endif
  1094. {
  1095. cli_.set_connection_timeout(2);
  1096. #ifdef CPPHTTPLIB_SSL_ENABLED
  1097. cli_.enable_server_certificate_verification(false);
  1098. #endif
  1099. }
  1100. virtual void SetUp() {
  1101. read_file("./image.jpg", image_data_);
  1102. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1103. res.set_content("Hello World!", "text/plain");
  1104. });
  1105. svr_.Get(
  1106. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1107. res.set_chunked_content_provider(
  1108. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1109. size_t remaining = image_data_.size() - offset;
  1110. if (remaining == 0) {
  1111. sink.done();
  1112. } else {
  1113. constexpr size_t CHUNK_SIZE = 1024;
  1114. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1115. sink.write(&image_data_[offset], send_size);
  1116. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1117. }
  1118. return true;
  1119. });
  1120. });
  1121. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1122. svr_.wait_until_ready();
  1123. }
  1124. virtual void TearDown() {
  1125. svr_.stop();
  1126. if (!request_threads_.empty()) {
  1127. std::this_thread::sleep_for(std::chrono::seconds(1));
  1128. for (auto &t : request_threads_) {
  1129. t.join();
  1130. }
  1131. }
  1132. t_.join();
  1133. }
  1134. #ifdef CPPHTTPLIB_SSL_ENABLED
  1135. SSLClient cli_;
  1136. SSLServer svr_;
  1137. #else
  1138. Client cli_;
  1139. Server svr_;
  1140. #endif
  1141. thread t_;
  1142. std::vector<thread> request_threads_;
  1143. std::string image_data_;
  1144. };
  1145. TEST_F(ChunkedEncodingTest, NormalGet) {
  1146. auto res = cli_.Get("/chunked");
  1147. ASSERT_TRUE(res);
  1148. std::string out;
  1149. read_file("./image.jpg", out);
  1150. EXPECT_EQ(StatusCode::OK_200, res->status);
  1151. EXPECT_EQ(out, res->body);
  1152. }
  1153. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1154. std::string body;
  1155. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1156. body.append(data, data_length);
  1157. return true;
  1158. });
  1159. ASSERT_TRUE(res);
  1160. std::string out;
  1161. read_file("./image.jpg", out);
  1162. EXPECT_EQ(StatusCode::OK_200, res->status);
  1163. EXPECT_EQ(out, body);
  1164. }
  1165. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1166. std::string body;
  1167. auto res = cli_.Get(
  1168. "/chunked",
  1169. [&](const Response &response) {
  1170. EXPECT_EQ(StatusCode::OK_200, response.status);
  1171. return true;
  1172. },
  1173. [&](const char *data, size_t data_length) {
  1174. body.append(data, data_length);
  1175. return true;
  1176. });
  1177. ASSERT_TRUE(res);
  1178. std::string out;
  1179. read_file("./image.jpg", out);
  1180. EXPECT_EQ(StatusCode::OK_200, res->status);
  1181. EXPECT_EQ(out, body);
  1182. }
  1183. TEST(RangeTest, FromHTTPBin_Online) {
  1184. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1185. auto host = "httpcan.org";
  1186. auto path = std::string{"/range/32"};
  1187. #else
  1188. auto host = "nghttp2.org";
  1189. auto path = std::string{"/httpbin/range/32"};
  1190. #endif
  1191. #ifdef CPPHTTPLIB_SSL_ENABLED
  1192. auto port = 443;
  1193. SSLClient cli(host, port);
  1194. #else
  1195. auto port = 80;
  1196. Client cli(host, port);
  1197. #endif
  1198. cli.set_connection_timeout(5);
  1199. {
  1200. auto res = cli.Get(path);
  1201. ASSERT_TRUE(res);
  1202. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1203. EXPECT_EQ(StatusCode::OK_200, res->status);
  1204. }
  1205. {
  1206. Headers headers = {make_range_header({{1, -1}})};
  1207. auto res = cli.Get(path, headers);
  1208. ASSERT_TRUE(res);
  1209. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1210. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1211. }
  1212. {
  1213. Headers headers = {make_range_header({{1, 10}})};
  1214. auto res = cli.Get(path, headers);
  1215. ASSERT_TRUE(res);
  1216. EXPECT_EQ("bcdefghijk", res->body);
  1217. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1218. }
  1219. {
  1220. Headers headers = {make_range_header({{0, 31}})};
  1221. auto res = cli.Get(path, headers);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1224. EXPECT_EQ(StatusCode::OK_200, res->status);
  1225. }
  1226. {
  1227. Headers headers = {make_range_header({{0, -1}})};
  1228. auto res = cli.Get(path, headers);
  1229. ASSERT_TRUE(res);
  1230. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1231. EXPECT_EQ(StatusCode::OK_200, res->status);
  1232. }
  1233. {
  1234. Headers headers = {make_range_header({{0, 32}})};
  1235. auto res = cli.Get(path, headers);
  1236. ASSERT_TRUE(res);
  1237. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1238. }
  1239. }
  1240. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1241. auto host = "unresolvableaddress.local";
  1242. auto path = std::string{"/"};
  1243. #ifdef CPPHTTPLIB_SSL_ENABLED
  1244. auto port = 443;
  1245. SSLClient cli(host, port);
  1246. #else
  1247. auto port = 80;
  1248. Client cli(host, port);
  1249. #endif
  1250. cli.set_connection_timeout(1);
  1251. {
  1252. auto res = cli.Get(path);
  1253. ASSERT_FALSE(res);
  1254. }
  1255. std::this_thread::sleep_for(std::chrono::seconds(8));
  1256. }
  1257. TEST(ConnectionErrorTest, InvalidHost) {
  1258. auto host = "-abcde.com";
  1259. #ifdef CPPHTTPLIB_SSL_ENABLED
  1260. auto port = 443;
  1261. SSLClient cli(host, port);
  1262. #else
  1263. auto port = 80;
  1264. Client cli(host, port);
  1265. #endif
  1266. cli.set_connection_timeout(std::chrono::seconds(2));
  1267. auto res = cli.Get("/");
  1268. ASSERT_TRUE(!res);
  1269. EXPECT_EQ(Error::Connection, res.error());
  1270. }
  1271. TEST(ConnectionErrorTest, InvalidHost2) {
  1272. auto host = "httpcan.org/";
  1273. #ifdef CPPHTTPLIB_SSL_ENABLED
  1274. SSLClient cli(host);
  1275. #else
  1276. Client cli(host);
  1277. #endif
  1278. cli.set_connection_timeout(std::chrono::seconds(2));
  1279. auto res = cli.Get("/");
  1280. ASSERT_TRUE(!res);
  1281. EXPECT_EQ(Error::Connection, res.error());
  1282. }
  1283. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1284. auto host = "httpcan.org/";
  1285. #ifdef CPPHTTPLIB_SSL_ENABLED
  1286. SSLClient cli(host);
  1287. #else
  1288. Client cli(host);
  1289. #endif
  1290. cli.set_connection_timeout(std::chrono::seconds(2));
  1291. auto res = cli.Get("/");
  1292. ASSERT_TRUE(!res);
  1293. stringstream s;
  1294. s << "error code: " << res.error();
  1295. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1296. }
  1297. TEST(ConnectionErrorTest, InvalidPort) {
  1298. auto host = "localhost";
  1299. auto port = 44380;
  1300. #ifdef CPPHTTPLIB_SSL_ENABLED
  1301. SSLClient cli(host, port);
  1302. #else
  1303. Client cli(host, port);
  1304. #endif
  1305. cli.set_connection_timeout(std::chrono::seconds(2));
  1306. auto res = cli.Get("/");
  1307. ASSERT_TRUE(!res);
  1308. EXPECT_TRUE(Error::Connection == res.error() ||
  1309. Error::ConnectionTimeout == res.error());
  1310. }
  1311. TEST(ConnectionErrorTest, Timeout_Online) {
  1312. auto host = "google.com";
  1313. #ifdef CPPHTTPLIB_SSL_ENABLED
  1314. auto port = 44380;
  1315. SSLClient cli(host, port);
  1316. #else
  1317. auto port = 8080;
  1318. Client cli(host, port);
  1319. #endif
  1320. cli.set_connection_timeout(std::chrono::seconds(2));
  1321. // only probe one address type so that the error reason
  1322. // correlates to the timed-out IPv4, not the unsupported
  1323. // IPv6 connection attempt
  1324. cli.set_address_family(AF_INET);
  1325. auto res = cli.Get("/");
  1326. ASSERT_TRUE(!res);
  1327. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1328. }
  1329. TEST(CancelTest, NoCancel_Online) {
  1330. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1331. auto host = "httpcan.org";
  1332. auto path = std::string{"/range/32"};
  1333. #else
  1334. auto host = "nghttp2.org";
  1335. auto path = std::string{"/httpbin/range/32"};
  1336. #endif
  1337. #ifdef CPPHTTPLIB_SSL_ENABLED
  1338. auto port = 443;
  1339. SSLClient cli(host, port);
  1340. #else
  1341. auto port = 80;
  1342. Client cli(host, port);
  1343. #endif
  1344. cli.set_connection_timeout(std::chrono::seconds(5));
  1345. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1346. ASSERT_TRUE(res);
  1347. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1348. EXPECT_EQ(StatusCode::OK_200, res->status);
  1349. }
  1350. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1351. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1352. auto host = "httpcan.org";
  1353. auto path = std::string{"/range/32"};
  1354. #else
  1355. auto host = "nghttp2.org";
  1356. auto path = std::string{"/httpbin/range/32"};
  1357. #endif
  1358. #ifdef CPPHTTPLIB_SSL_ENABLED
  1359. auto port = 443;
  1360. SSLClient cli(host, port);
  1361. #else
  1362. auto port = 80;
  1363. Client cli(host, port);
  1364. #endif
  1365. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1366. cli.set_connection_timeout(std::chrono::seconds(5));
  1367. ASSERT_TRUE(!res);
  1368. EXPECT_EQ(Error::Canceled, res.error());
  1369. }
  1370. TEST(CancelTest, WithCancelLargePayload_Online) {
  1371. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1372. auto host = "httpcan.org";
  1373. auto path = std::string{"/range/65536"};
  1374. #else
  1375. auto host = "nghttp2.org";
  1376. auto path = std::string{"/httpbin/range/65536"};
  1377. #endif
  1378. #ifdef CPPHTTPLIB_SSL_ENABLED
  1379. auto port = 443;
  1380. SSLClient cli(host, port);
  1381. #else
  1382. auto port = 80;
  1383. Client cli(host, port);
  1384. #endif
  1385. cli.set_connection_timeout(std::chrono::seconds(5));
  1386. uint32_t count = 0;
  1387. auto res =
  1388. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1389. ASSERT_TRUE(!res);
  1390. EXPECT_EQ(Error::Canceled, res.error());
  1391. }
  1392. TEST(CancelTest, NoCancelPost) {
  1393. Server svr;
  1394. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1395. res.set_content("Hello World!", "text/plain");
  1396. });
  1397. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1398. auto se = detail::scope_exit([&] {
  1399. svr.stop();
  1400. thread.join();
  1401. ASSERT_FALSE(svr.is_running());
  1402. });
  1403. svr.wait_until_ready();
  1404. Client cli(HOST, PORT);
  1405. cli.set_connection_timeout(std::chrono::seconds(5));
  1406. auto res =
  1407. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1408. "application/json", [](uint64_t, uint64_t) { return true; });
  1409. ASSERT_TRUE(res);
  1410. EXPECT_EQ("Hello World!", res->body);
  1411. EXPECT_EQ(StatusCode::OK_200, res->status);
  1412. }
  1413. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1414. Server svr;
  1415. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1416. res.set_content("Hello World!", "text/plain");
  1417. });
  1418. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1419. auto se = detail::scope_exit([&] {
  1420. svr.stop();
  1421. thread.join();
  1422. ASSERT_FALSE(svr.is_running());
  1423. });
  1424. svr.wait_until_ready();
  1425. Client cli(HOST, PORT);
  1426. cli.set_connection_timeout(std::chrono::seconds(5));
  1427. auto res =
  1428. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1429. "application/json", [](uint64_t, uint64_t) { return false; });
  1430. ASSERT_TRUE(!res);
  1431. EXPECT_EQ(Error::Canceled, res.error());
  1432. }
  1433. TEST(CancelTest, WithCancelLargePayloadPost) {
  1434. Server svr;
  1435. svr.set_payload_max_length(200 * 1024 * 1024);
  1436. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1437. res.set_content(LARGE_DATA, "text/plain");
  1438. });
  1439. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1440. auto se = detail::scope_exit([&] {
  1441. svr.stop();
  1442. thread.join();
  1443. ASSERT_FALSE(svr.is_running());
  1444. });
  1445. svr.wait_until_ready();
  1446. Client cli(HOST, PORT);
  1447. cli.set_payload_max_length(200 * 1024 * 1024);
  1448. cli.set_connection_timeout(std::chrono::seconds(5));
  1449. auto res =
  1450. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1451. "application/json", [](uint64_t, uint64_t) { return false; });
  1452. ASSERT_TRUE(!res);
  1453. EXPECT_EQ(Error::Canceled, res.error());
  1454. }
  1455. TEST(CancelTest, NoCancelPut) {
  1456. Server svr;
  1457. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1458. res.set_content("Hello World!", "text/plain");
  1459. });
  1460. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1461. auto se = detail::scope_exit([&] {
  1462. svr.stop();
  1463. thread.join();
  1464. ASSERT_FALSE(svr.is_running());
  1465. });
  1466. svr.wait_until_ready();
  1467. Client cli(HOST, PORT);
  1468. cli.set_connection_timeout(std::chrono::seconds(5));
  1469. auto res =
  1470. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1471. "application/json", [](uint64_t, uint64_t) { return true; });
  1472. ASSERT_TRUE(res);
  1473. EXPECT_EQ("Hello World!", res->body);
  1474. EXPECT_EQ(StatusCode::OK_200, res->status);
  1475. }
  1476. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1477. Server svr;
  1478. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1479. res.set_content("Hello World!", "text/plain");
  1480. });
  1481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1482. auto se = detail::scope_exit([&] {
  1483. svr.stop();
  1484. thread.join();
  1485. ASSERT_FALSE(svr.is_running());
  1486. });
  1487. svr.wait_until_ready();
  1488. Client cli(HOST, PORT);
  1489. cli.set_connection_timeout(std::chrono::seconds(5));
  1490. auto res =
  1491. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1492. "application/json", [](uint64_t, uint64_t) { return false; });
  1493. ASSERT_TRUE(!res);
  1494. EXPECT_EQ(Error::Canceled, res.error());
  1495. }
  1496. TEST(CancelTest, WithCancelLargePayloadPut) {
  1497. Server svr;
  1498. svr.set_payload_max_length(200 * 1024 * 1024);
  1499. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1500. res.set_content(LARGE_DATA, "text/plain");
  1501. });
  1502. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1503. auto se = detail::scope_exit([&] {
  1504. svr.stop();
  1505. thread.join();
  1506. ASSERT_FALSE(svr.is_running());
  1507. });
  1508. svr.wait_until_ready();
  1509. Client cli(HOST, PORT);
  1510. cli.set_payload_max_length(200 * 1024 * 1024);
  1511. cli.set_connection_timeout(std::chrono::seconds(5));
  1512. auto res =
  1513. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1514. "application/json", [](uint64_t, uint64_t) { return false; });
  1515. ASSERT_TRUE(!res);
  1516. EXPECT_EQ(Error::Canceled, res.error());
  1517. }
  1518. TEST(CancelTest, NoCancelPatch) {
  1519. Server svr;
  1520. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1521. res.set_content("Hello World!", "text/plain");
  1522. });
  1523. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1524. auto se = detail::scope_exit([&] {
  1525. svr.stop();
  1526. thread.join();
  1527. ASSERT_FALSE(svr.is_running());
  1528. });
  1529. svr.wait_until_ready();
  1530. Client cli(HOST, PORT);
  1531. cli.set_connection_timeout(std::chrono::seconds(5));
  1532. auto res =
  1533. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1534. "application/json", [](uint64_t, uint64_t) { return true; });
  1535. ASSERT_TRUE(res);
  1536. EXPECT_EQ("Hello World!", res->body);
  1537. EXPECT_EQ(StatusCode::OK_200, res->status);
  1538. }
  1539. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1540. Server svr;
  1541. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1542. res.set_content("Hello World!", "text/plain");
  1543. });
  1544. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1545. auto se = detail::scope_exit([&] {
  1546. svr.stop();
  1547. thread.join();
  1548. ASSERT_FALSE(svr.is_running());
  1549. });
  1550. svr.wait_until_ready();
  1551. Client cli(HOST, PORT);
  1552. cli.set_connection_timeout(std::chrono::seconds(5));
  1553. auto res =
  1554. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1555. "application/json", [](uint64_t, uint64_t) { return false; });
  1556. ASSERT_TRUE(!res);
  1557. EXPECT_EQ(Error::Canceled, res.error());
  1558. }
  1559. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1560. Server svr;
  1561. svr.set_payload_max_length(200 * 1024 * 1024);
  1562. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1563. res.set_content(LARGE_DATA, "text/plain");
  1564. });
  1565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1566. auto se = detail::scope_exit([&] {
  1567. svr.stop();
  1568. thread.join();
  1569. ASSERT_FALSE(svr.is_running());
  1570. });
  1571. svr.wait_until_ready();
  1572. Client cli(HOST, PORT);
  1573. cli.set_payload_max_length(200 * 1024 * 1024);
  1574. cli.set_connection_timeout(std::chrono::seconds(5));
  1575. auto res =
  1576. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1577. "application/json", [](uint64_t, uint64_t) { return false; });
  1578. ASSERT_TRUE(!res);
  1579. EXPECT_EQ(Error::Canceled, res.error());
  1580. }
  1581. TEST(CancelTest, NoCancelDelete) {
  1582. Server svr;
  1583. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1584. res.set_content("Hello World!", "text/plain");
  1585. });
  1586. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1587. auto se = detail::scope_exit([&] {
  1588. svr.stop();
  1589. thread.join();
  1590. ASSERT_FALSE(svr.is_running());
  1591. });
  1592. svr.wait_until_ready();
  1593. Client cli(HOST, PORT);
  1594. cli.set_connection_timeout(std::chrono::seconds(5));
  1595. auto res =
  1596. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1597. "application/json", [](uint64_t, uint64_t) { return true; });
  1598. ASSERT_TRUE(res);
  1599. EXPECT_EQ("Hello World!", res->body);
  1600. EXPECT_EQ(StatusCode::OK_200, res->status);
  1601. }
  1602. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1603. Server svr;
  1604. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1605. res.set_content("Hello World!", "text/plain");
  1606. });
  1607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1608. auto se = detail::scope_exit([&] {
  1609. svr.stop();
  1610. thread.join();
  1611. ASSERT_FALSE(svr.is_running());
  1612. });
  1613. svr.wait_until_ready();
  1614. Client cli(HOST, PORT);
  1615. cli.set_connection_timeout(std::chrono::seconds(5));
  1616. auto res =
  1617. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1618. "application/json", [](uint64_t, uint64_t) { return false; });
  1619. ASSERT_TRUE(!res);
  1620. EXPECT_EQ(Error::Canceled, res.error());
  1621. }
  1622. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1623. Server svr;
  1624. svr.set_payload_max_length(200 * 1024 * 1024);
  1625. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1626. res.set_content(LARGE_DATA, "text/plain");
  1627. });
  1628. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1629. auto se = detail::scope_exit([&] {
  1630. svr.stop();
  1631. thread.join();
  1632. ASSERT_FALSE(svr.is_running());
  1633. });
  1634. svr.wait_until_ready();
  1635. Client cli(HOST, PORT);
  1636. cli.set_payload_max_length(200 * 1024 * 1024);
  1637. cli.set_connection_timeout(std::chrono::seconds(5));
  1638. auto res =
  1639. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1640. "application/json", [](uint64_t, uint64_t) { return false; });
  1641. ASSERT_TRUE(!res);
  1642. EXPECT_EQ(Error::Canceled, res.error());
  1643. }
  1644. static std::string remove_whitespace(const std::string &input) {
  1645. std::string output;
  1646. output.reserve(input.size());
  1647. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1648. [](unsigned char c) { return !std::isspace(c); });
  1649. return output;
  1650. }
  1651. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1652. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1653. auto host = "httpcan.org";
  1654. auto path = std::string{"/basic-auth/hello/world"};
  1655. #else
  1656. auto host = "nghttp2.org";
  1657. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1658. #endif
  1659. #ifdef CPPHTTPLIB_SSL_ENABLED
  1660. auto port = 443;
  1661. SSLClient cli(host, port);
  1662. #else
  1663. auto port = 80;
  1664. Client cli(host, port);
  1665. #endif
  1666. {
  1667. auto res = cli.Get(path);
  1668. ASSERT_TRUE(res);
  1669. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1670. }
  1671. {
  1672. auto res =
  1673. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1674. ASSERT_TRUE(res);
  1675. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1676. remove_whitespace(res->body));
  1677. EXPECT_EQ(StatusCode::OK_200, res->status);
  1678. }
  1679. {
  1680. cli.set_basic_auth("hello", "world");
  1681. auto res = cli.Get(path);
  1682. ASSERT_TRUE(res);
  1683. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1684. remove_whitespace(res->body));
  1685. EXPECT_EQ(StatusCode::OK_200, res->status);
  1686. }
  1687. {
  1688. cli.set_basic_auth("hello", "bad");
  1689. auto res = cli.Get(path);
  1690. ASSERT_TRUE(res);
  1691. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1692. }
  1693. {
  1694. cli.set_basic_auth("bad", "world");
  1695. auto res = cli.Get(path);
  1696. ASSERT_TRUE(res);
  1697. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1698. }
  1699. }
  1700. #ifdef CPPHTTPLIB_SSL_ENABLED
  1701. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1702. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1703. auto host = "httpcan.org";
  1704. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1705. auto paths = std::vector<std::string>{
  1706. "/digest-auth/auth/hello/world/MD5",
  1707. "/digest-auth/auth/hello/world/SHA-256",
  1708. "/digest-auth/auth/hello/world/SHA-512",
  1709. };
  1710. #else
  1711. auto host = "nghttp2.org";
  1712. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1713. auto paths = std::vector<std::string>{
  1714. "/httpbin/digest-auth/auth/hello/world/MD5",
  1715. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1716. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1717. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1718. };
  1719. #endif
  1720. auto port = 443;
  1721. SSLClient cli(host, port);
  1722. {
  1723. auto res = cli.Get(unauth_path);
  1724. ASSERT_TRUE(res);
  1725. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1726. }
  1727. {
  1728. cli.set_digest_auth("hello", "world");
  1729. for (const auto &path : paths) {
  1730. auto res = cli.Get(path.c_str());
  1731. ASSERT_TRUE(res);
  1732. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1733. std::string algo(path.substr(path.rfind('/') + 1));
  1734. EXPECT_EQ(
  1735. remove_whitespace("{\"algorithm\":\"" + algo +
  1736. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1737. remove_whitespace(res->body));
  1738. #else
  1739. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1740. remove_whitespace(res->body));
  1741. #endif
  1742. EXPECT_EQ(StatusCode::OK_200, res->status);
  1743. }
  1744. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1745. cli.set_digest_auth("hello", "bad");
  1746. for (const auto &path : paths) {
  1747. auto res = cli.Get(path.c_str());
  1748. ASSERT_TRUE(res);
  1749. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1750. }
  1751. #endif
  1752. }
  1753. }
  1754. #endif
  1755. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1756. auto host = "google.com";
  1757. auto another_host = "example.com";
  1758. auto wrong_ip = "0.0.0.0";
  1759. #ifdef CPPHTTPLIB_SSL_ENABLED
  1760. SSLClient cli(host);
  1761. #else
  1762. Client cli(host);
  1763. #endif
  1764. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1765. auto res = cli.Get("/");
  1766. ASSERT_TRUE(res);
  1767. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1768. }
  1769. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1770. auto host = "google.com";
  1771. auto wrong_ip = "0.0.0.0";
  1772. #ifdef CPPHTTPLIB_SSL_ENABLED
  1773. SSLClient cli(host);
  1774. #else
  1775. Client cli(host);
  1776. #endif
  1777. cli.set_hostname_addr_map({{host, wrong_ip}});
  1778. auto res = cli.Get("/");
  1779. ASSERT_TRUE(!res);
  1780. EXPECT_EQ(Error::Connection, res.error());
  1781. }
  1782. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1783. auto host = "nghttp2.org";
  1784. #ifdef CPPHTTPLIB_SSL_ENABLED
  1785. SSLClient cli(host);
  1786. #else
  1787. Client cli(host);
  1788. #endif
  1789. cli.set_follow_location(true);
  1790. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1791. ASSERT_TRUE(res);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. }
  1794. TEST(RedirectTest, Redirect_Online) {
  1795. auto host = "nghttp2.org";
  1796. #ifdef CPPHTTPLIB_SSL_ENABLED
  1797. SSLClient cli(host);
  1798. #else
  1799. Client cli(host);
  1800. #endif
  1801. cli.set_follow_location(true);
  1802. auto res = cli.Get("/httpbin/redirect/3");
  1803. ASSERT_TRUE(res);
  1804. EXPECT_EQ(StatusCode::OK_200, res->status);
  1805. }
  1806. TEST(RelativeRedirectTest, Redirect_Online) {
  1807. auto host = "nghttp2.org";
  1808. #ifdef CPPHTTPLIB_SSL_ENABLED
  1809. SSLClient cli(host);
  1810. #else
  1811. Client cli(host);
  1812. #endif
  1813. cli.set_follow_location(true);
  1814. auto res = cli.Get("/httpbin/relative-redirect/3");
  1815. ASSERT_TRUE(res);
  1816. EXPECT_EQ(StatusCode::OK_200, res->status);
  1817. }
  1818. TEST(TooManyRedirectTest, Redirect_Online) {
  1819. auto host = "nghttp2.org";
  1820. #ifdef CPPHTTPLIB_SSL_ENABLED
  1821. SSLClient cli(host);
  1822. #else
  1823. Client cli(host);
  1824. #endif
  1825. cli.set_follow_location(true);
  1826. auto res = cli.Get("/httpbin/redirect/21");
  1827. ASSERT_TRUE(!res);
  1828. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1829. }
  1830. #ifdef CPPHTTPLIB_SSL_ENABLED
  1831. TEST(YahooRedirectTest, Redirect_Online) {
  1832. Client cli("yahoo.com");
  1833. auto res = cli.Get("/");
  1834. ASSERT_TRUE(res);
  1835. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1836. cli.set_follow_location(true);
  1837. res = cli.Get("/");
  1838. ASSERT_TRUE(res);
  1839. EXPECT_EQ(StatusCode::OK_200, res->status);
  1840. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1841. }
  1842. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1843. #define REDIR_HOST "httpbingo.org"
  1844. #define REDIR_PATH "/redirect-to"
  1845. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1846. SSLClient cli(REDIR_HOST);
  1847. cli.set_follow_location(true);
  1848. auto res =
  1849. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1850. ASSERT_TRUE(res);
  1851. EXPECT_EQ(StatusCode::OK_200, res->status);
  1852. }
  1853. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1854. SSLClient cli(REDIR_HOST);
  1855. cli.set_follow_location(true);
  1856. Params params;
  1857. params.emplace("url", "http://example.com");
  1858. params.emplace("status_code", "302");
  1859. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1860. ASSERT_TRUE(res);
  1861. EXPECT_EQ(StatusCode::OK_200, res->status);
  1862. }
  1863. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1864. SSLClient cli(REDIR_HOST);
  1865. cli.set_follow_location(true);
  1866. Params params;
  1867. params.emplace("url", "http://example.com");
  1868. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1869. ASSERT_TRUE(res);
  1870. EXPECT_EQ(StatusCode::OK_200, res->status);
  1871. }
  1872. TEST(UrlWithSpace, Redirect_Online) {
  1873. SSLClient cli("edge.forgecdn.net");
  1874. cli.set_follow_location(true);
  1875. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1876. ASSERT_TRUE(res);
  1877. EXPECT_EQ(StatusCode::OK_200, res->status);
  1878. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1879. }
  1880. #endif
  1881. #if !defined(_WIN32) && !defined(_WIN64)
  1882. TEST(ReceiveSignals, Signal) {
  1883. auto setupSignalHandlers = []() {
  1884. struct sigaction act;
  1885. sigemptyset(&act.sa_mask);
  1886. act.sa_flags = SA_SIGINFO;
  1887. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1888. switch (sig) {
  1889. case SIGINT:
  1890. default: break;
  1891. }
  1892. };
  1893. ::sigaction(SIGINT, &act, nullptr);
  1894. };
  1895. Server svr;
  1896. int port = 0;
  1897. auto thread = std::thread([&]() {
  1898. setupSignalHandlers();
  1899. port = svr.bind_to_any_port(HOST);
  1900. svr.listen_after_bind();
  1901. });
  1902. auto se = detail::scope_exit([&] {
  1903. svr.stop();
  1904. thread.join();
  1905. ASSERT_FALSE(svr.is_running());
  1906. });
  1907. svr.wait_until_ready();
  1908. ASSERT_TRUE(svr.is_running());
  1909. pthread_kill(thread.native_handle(), SIGINT);
  1910. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1911. ASSERT_TRUE(svr.is_running());
  1912. }
  1913. #endif
  1914. TEST(RedirectToDifferentPort, Redirect) {
  1915. Server svr1;
  1916. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1917. res.set_content("Hello World!", "text/plain");
  1918. });
  1919. int svr1_port = 0;
  1920. auto thread1 = std::thread([&]() {
  1921. svr1_port = svr1.bind_to_any_port(HOST);
  1922. svr1.listen_after_bind();
  1923. });
  1924. Server svr2;
  1925. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1926. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1927. });
  1928. int svr2_port = 0;
  1929. auto thread2 = std::thread([&]() {
  1930. svr2_port = svr2.bind_to_any_port(HOST);
  1931. svr2.listen_after_bind();
  1932. });
  1933. auto se = detail::scope_exit([&] {
  1934. svr2.stop();
  1935. thread2.join();
  1936. svr1.stop();
  1937. thread1.join();
  1938. ASSERT_FALSE(svr2.is_running());
  1939. ASSERT_FALSE(svr1.is_running());
  1940. });
  1941. svr1.wait_until_ready();
  1942. svr2.wait_until_ready();
  1943. Client cli("localhost", svr2_port);
  1944. cli.set_follow_location(true);
  1945. auto res = cli.Get("/2");
  1946. ASSERT_TRUE(res);
  1947. EXPECT_EQ(StatusCode::OK_200, res->status);
  1948. EXPECT_EQ("Hello World!", res->body);
  1949. }
  1950. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1951. Server svr;
  1952. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1953. // Port number that overflows int — should not crash
  1954. res.set_redirect("http://localhost:99999999999999999999/target");
  1955. });
  1956. auto port = svr.bind_to_any_port(HOST);
  1957. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1958. auto se = detail::scope_exit([&] {
  1959. svr.stop();
  1960. thread.join();
  1961. ASSERT_FALSE(svr.is_running());
  1962. });
  1963. svr.wait_until_ready();
  1964. Client cli(HOST, port);
  1965. cli.set_follow_location(true);
  1966. auto res = cli.Get("/redir");
  1967. // Should fail gracefully, not crash (no valid response due to bad port)
  1968. EXPECT_FALSE(res);
  1969. }
  1970. TEST(RedirectFromPageWithContent, Redirect) {
  1971. Server svr;
  1972. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1973. res.set_content("___", "text/plain");
  1974. res.set_redirect("/2");
  1975. });
  1976. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1977. res.set_content("Hello World!", "text/plain");
  1978. });
  1979. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1980. auto se = detail::scope_exit([&] {
  1981. svr.stop();
  1982. th.join();
  1983. ASSERT_FALSE(svr.is_running());
  1984. });
  1985. svr.wait_until_ready();
  1986. {
  1987. Client cli("localhost", PORT);
  1988. cli.set_follow_location(true);
  1989. std::string body;
  1990. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1991. body.append(data, data_length);
  1992. return true;
  1993. });
  1994. ASSERT_TRUE(res);
  1995. EXPECT_EQ(StatusCode::OK_200, res->status);
  1996. EXPECT_EQ("Hello World!", body);
  1997. }
  1998. {
  1999. Client cli("localhost", PORT);
  2000. std::string body;
  2001. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2002. body.append(data, data_length);
  2003. return true;
  2004. });
  2005. ASSERT_TRUE(res);
  2006. EXPECT_EQ(StatusCode::Found_302, res->status);
  2007. EXPECT_EQ("___", body);
  2008. }
  2009. }
  2010. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2011. Server svr;
  2012. auto port_str = std::to_string(PORT);
  2013. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2014. auto expected_host = "[::1]:" + port_str;
  2015. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2016. res.set_content("___", "text/plain");
  2017. // res.set_redirect("/2");
  2018. res.set_redirect(redirect_url);
  2019. });
  2020. svr.Get("/2", [&](const Request &req, Response &res) {
  2021. auto host_header = req.headers.find("Host");
  2022. ASSERT_TRUE(host_header != req.headers.end());
  2023. EXPECT_EQ(expected_host, host_header->second);
  2024. res.set_content("Hello World!", "text/plain");
  2025. });
  2026. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2027. auto se = detail::scope_exit([&] {
  2028. svr.stop();
  2029. th.join();
  2030. ASSERT_FALSE(svr.is_running());
  2031. });
  2032. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2033. // actually starts anything, so the condition !svr.is_running() will
  2034. // always remain true, and the loop never stops.
  2035. // This basically counts how many milliseconds have passed since the
  2036. // call to svr.listen(), and if after 5 seconds nothing started yet
  2037. // aborts the test.
  2038. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2039. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2040. ASSERT_LT(milliseconds, 5000U);
  2041. }
  2042. {
  2043. Client cli("::1", PORT);
  2044. cli.set_follow_location(true);
  2045. std::string body;
  2046. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2047. body.append(data, data_length);
  2048. return true;
  2049. });
  2050. ASSERT_TRUE(res);
  2051. EXPECT_EQ(StatusCode::OK_200, res->status);
  2052. EXPECT_EQ("Hello World!", body);
  2053. }
  2054. {
  2055. Client cli("::1", PORT);
  2056. std::string body;
  2057. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2058. body.append(data, data_length);
  2059. return true;
  2060. });
  2061. ASSERT_TRUE(res);
  2062. EXPECT_EQ(StatusCode::Found_302, res->status);
  2063. EXPECT_EQ("___", body);
  2064. }
  2065. }
  2066. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2067. Server svr;
  2068. svr.Get("/foo", [](const Request &req, Response &res) {
  2069. auto a = req.params.find("a");
  2070. if (a != req.params.end()) {
  2071. res.set_content((*a).second, "text/plain");
  2072. res.status = StatusCode::OK_200;
  2073. } else {
  2074. res.status = StatusCode::BadRequest_400;
  2075. }
  2076. });
  2077. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2078. auto se = detail::scope_exit([&] {
  2079. svr.stop();
  2080. thread.join();
  2081. ASSERT_FALSE(svr.is_running());
  2082. });
  2083. svr.wait_until_ready();
  2084. {
  2085. Client cli(HOST, PORT);
  2086. cli.set_path_encode(false);
  2087. auto res = cli.Get("/foo?a=explicitly+encoded");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::OK_200, res->status);
  2090. // This expects it back with a space, as the `+` won't have been
  2091. // url-encoded, and server-side the params get decoded turning `+`
  2092. // into spaces.
  2093. EXPECT_EQ("explicitly encoded", res->body);
  2094. }
  2095. }
  2096. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2097. Server svr;
  2098. svr.Get("/", [](const Request &req, Response &) {
  2099. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2100. });
  2101. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2102. auto se = detail::scope_exit([&] {
  2103. svr.stop();
  2104. thread.join();
  2105. ASSERT_FALSE(svr.is_running());
  2106. });
  2107. svr.wait_until_ready();
  2108. {
  2109. Client cli(HOST, PORT);
  2110. cli.set_path_encode(false);
  2111. auto res = cli.Get("/?something=%0A");
  2112. ASSERT_TRUE(res);
  2113. EXPECT_EQ(StatusCode::OK_200, res->status);
  2114. }
  2115. }
  2116. TEST(BindServerTest, BindDualStack) {
  2117. Server svr;
  2118. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2119. res.set_content("Hello World!", "text/plain");
  2120. });
  2121. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2122. auto se = detail::scope_exit([&] {
  2123. svr.stop();
  2124. thread.join();
  2125. ASSERT_FALSE(svr.is_running());
  2126. });
  2127. svr.wait_until_ready();
  2128. {
  2129. Client cli("127.0.0.1", PORT);
  2130. auto res = cli.Get("/1");
  2131. ASSERT_TRUE(res);
  2132. EXPECT_EQ(StatusCode::OK_200, res->status);
  2133. EXPECT_EQ("Hello World!", res->body);
  2134. }
  2135. {
  2136. Client cli("::1", PORT);
  2137. auto res = cli.Get("/1");
  2138. ASSERT_TRUE(res);
  2139. EXPECT_EQ(StatusCode::OK_200, res->status);
  2140. EXPECT_EQ("Hello World!", res->body);
  2141. }
  2142. }
  2143. TEST(BindServerTest, BindAndListenSeparately) {
  2144. Server svr;
  2145. int port = svr.bind_to_any_port("0.0.0.0");
  2146. ASSERT_TRUE(svr.is_valid());
  2147. ASSERT_TRUE(port > 0);
  2148. svr.stop();
  2149. }
  2150. #ifdef CPPHTTPLIB_SSL_ENABLED
  2151. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2153. CLIENT_CA_CERT_DIR);
  2154. int port = svr.bind_to_any_port("0.0.0.0");
  2155. ASSERT_TRUE(svr.is_valid());
  2156. ASSERT_TRUE(port > 0);
  2157. svr.stop();
  2158. }
  2159. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2160. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2161. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2162. int port = svr.bind_to_any_port("0.0.0.0");
  2163. ASSERT_TRUE(svr.is_valid());
  2164. ASSERT_TRUE(port > 0);
  2165. svr.stop();
  2166. }
  2167. TEST(BindServerTest, UpdateCertsPem) {
  2168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2169. int port = svr.bind_to_any_port("0.0.0.0");
  2170. ASSERT_TRUE(svr.is_valid());
  2171. ASSERT_TRUE(port > 0);
  2172. // Read PEM files
  2173. std::string cert_pem, key_pem, ca_pem;
  2174. read_file(SERVER_CERT_FILE, cert_pem);
  2175. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2176. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2177. // Update server certificates using PEM API
  2178. ASSERT_TRUE(
  2179. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2180. ASSERT_TRUE(svr.is_valid());
  2181. svr.stop();
  2182. }
  2183. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2184. // Start server with client CA (enables client auth)
  2185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2186. ASSERT_TRUE(svr.is_valid());
  2187. bool handler_called = false;
  2188. svr.Get("/test", [&](const Request &req, Response &res) {
  2189. handler_called = true;
  2190. // Verify client certificate is present
  2191. auto cert = req.peer_cert();
  2192. EXPECT_TRUE(static_cast<bool>(cert));
  2193. res.set_content("ok", "text/plain");
  2194. });
  2195. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2196. auto se = detail::scope_exit([&] {
  2197. svr.stop();
  2198. t.join();
  2199. ASSERT_FALSE(svr.is_running());
  2200. });
  2201. svr.wait_until_ready();
  2202. // Read PEM files
  2203. std::string cert_pem, key_pem, ca_pem;
  2204. read_file(SERVER_CERT_FILE, cert_pem);
  2205. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2206. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2207. // Update server certificates and client CA using PEM API while server running
  2208. ASSERT_TRUE(
  2209. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2210. // Connect with client certificate
  2211. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2212. cli.enable_server_certificate_verification(false);
  2213. cli.set_connection_timeout(30);
  2214. auto res = cli.Get("/test");
  2215. ASSERT_TRUE(res);
  2216. ASSERT_EQ(StatusCode::OK_200, res->status);
  2217. ASSERT_TRUE(handler_called);
  2218. EXPECT_EQ("ok", res->body);
  2219. }
  2220. #endif
  2221. TEST(ErrorHandlerTest, ContentLength) {
  2222. Server svr;
  2223. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2224. res.status = StatusCode::OK_200;
  2225. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2226. "text/html"); // <= Content-Length still 13
  2227. });
  2228. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2229. res.set_content("Hello World!\n", "text/plain");
  2230. res.status = 524;
  2231. });
  2232. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2233. auto se = detail::scope_exit([&] {
  2234. svr.stop();
  2235. thread.join();
  2236. ASSERT_FALSE(svr.is_running());
  2237. });
  2238. svr.wait_until_ready();
  2239. {
  2240. Client cli(HOST, PORT);
  2241. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2242. ASSERT_TRUE(res);
  2243. EXPECT_EQ(StatusCode::OK_200, res->status);
  2244. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2245. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2246. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2247. }
  2248. }
  2249. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2250. TEST(ExceptionTest, WithoutExceptionHandler) {
  2251. Server svr;
  2252. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2253. throw std::runtime_error("exception...");
  2254. });
  2255. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2256. throw std::runtime_error("exception\r\n...");
  2257. });
  2258. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2259. auto se = detail::scope_exit([&] {
  2260. svr.stop();
  2261. listen_thread.join();
  2262. ASSERT_FALSE(svr.is_running());
  2263. });
  2264. svr.wait_until_ready();
  2265. Client cli("localhost", PORT);
  2266. {
  2267. auto res = cli.Get("/exception");
  2268. ASSERT_TRUE(res);
  2269. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2270. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2271. }
  2272. {
  2273. auto res = cli.Get("/unknown");
  2274. ASSERT_TRUE(res);
  2275. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2276. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2277. }
  2278. }
  2279. TEST(ExceptionTest, WithExceptionHandler) {
  2280. Server svr;
  2281. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2282. std::exception_ptr ep) {
  2283. EXPECT_FALSE(ep == nullptr);
  2284. try {
  2285. std::rethrow_exception(ep);
  2286. } catch (std::exception &e) {
  2287. EXPECT_EQ("abc", std::string(e.what()));
  2288. } catch (...) {}
  2289. res.status = StatusCode::InternalServerError_500;
  2290. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2291. "text/html"); // <= Content-Length still 13 at this point
  2292. });
  2293. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2294. res.set_content("Hello World!\n", "text/plain");
  2295. throw std::runtime_error("abc");
  2296. });
  2297. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2298. auto se = detail::scope_exit([&] {
  2299. svr.stop();
  2300. thread.join();
  2301. ASSERT_FALSE(svr.is_running());
  2302. });
  2303. svr.wait_until_ready();
  2304. for (size_t i = 0; i < 10; i++) {
  2305. Client cli(HOST, PORT);
  2306. for (size_t j = 0; j < 100; j++) {
  2307. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2308. ASSERT_TRUE(res);
  2309. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2310. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2311. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2312. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2313. }
  2314. cli.set_keep_alive(true);
  2315. for (size_t j = 0; j < 100; j++) {
  2316. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2317. ASSERT_TRUE(res);
  2318. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2319. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2320. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2321. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2322. }
  2323. }
  2324. }
  2325. TEST(ExceptionTest, AndErrorHandler) {
  2326. Server svr;
  2327. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2328. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2329. });
  2330. svr.set_exception_handler(
  2331. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2332. EXPECT_FALSE(ep == nullptr);
  2333. try {
  2334. std::rethrow_exception(ep);
  2335. } catch (std::exception &e) {
  2336. res.set_content(e.what(), "text/html");
  2337. } catch (...) {}
  2338. res.status = StatusCode::InternalServerError_500;
  2339. });
  2340. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2341. throw std::runtime_error("EXCEPTION");
  2342. });
  2343. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2344. res.set_content("ERROR", "text/html");
  2345. res.status = StatusCode::InternalServerError_500;
  2346. });
  2347. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2348. auto se = detail::scope_exit([&] {
  2349. svr.stop();
  2350. thread.join();
  2351. ASSERT_FALSE(svr.is_running());
  2352. });
  2353. svr.wait_until_ready();
  2354. Client cli(HOST, PORT);
  2355. {
  2356. auto res = cli.Get("/exception");
  2357. ASSERT_TRUE(res);
  2358. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2359. EXPECT_EQ("EXCEPTION", res->body);
  2360. }
  2361. {
  2362. auto res = cli.Get("/error");
  2363. ASSERT_TRUE(res);
  2364. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2365. EXPECT_EQ("ERROR", res->body);
  2366. }
  2367. {
  2368. auto res = cli.Get("/invalid");
  2369. ASSERT_TRUE(res);
  2370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2371. EXPECT_EQ("NOT_FOUND", res->body);
  2372. }
  2373. }
  2374. #endif
  2375. TEST(NoContentTest, ContentLength) {
  2376. Server svr;
  2377. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2378. res.status = StatusCode::NoContent_204;
  2379. });
  2380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2381. auto se = detail::scope_exit([&] {
  2382. svr.stop();
  2383. thread.join();
  2384. ASSERT_FALSE(svr.is_running());
  2385. });
  2386. svr.wait_until_ready();
  2387. {
  2388. Client cli(HOST, PORT);
  2389. auto res = cli.Get("/hi");
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2392. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2393. }
  2394. }
  2395. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2396. #ifdef CPPHTTPLIB_SSL_ENABLED
  2397. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2398. ASSERT_TRUE(svr.is_valid());
  2399. #else
  2400. Server svr;
  2401. #endif
  2402. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2403. if (req.path == "/routing_handler") {
  2404. res.set_header("PRE_ROUTING", "on");
  2405. res.set_content("Routing Handler", "text/plain");
  2406. return httplib::Server::HandlerResponse::Handled;
  2407. }
  2408. return httplib::Server::HandlerResponse::Unhandled;
  2409. });
  2410. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2411. res.set_content("Error", "text/html");
  2412. });
  2413. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2414. if (req.path == "/routing_handler") {
  2415. res.set_header("POST_ROUTING", "on");
  2416. }
  2417. });
  2418. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2419. res.set_content("Hello World!\n", "text/plain");
  2420. });
  2421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2422. auto se = detail::scope_exit([&] {
  2423. svr.stop();
  2424. thread.join();
  2425. ASSERT_FALSE(svr.is_running());
  2426. });
  2427. svr.wait_until_ready();
  2428. {
  2429. #ifdef CPPHTTPLIB_SSL_ENABLED
  2430. SSLClient cli(HOST, PORT);
  2431. cli.enable_server_certificate_verification(false);
  2432. #else
  2433. Client cli(HOST, PORT);
  2434. #endif
  2435. auto res = cli.Get("/routing_handler");
  2436. ASSERT_TRUE(res);
  2437. EXPECT_EQ(StatusCode::OK_200, res->status);
  2438. EXPECT_EQ("Routing Handler", res->body);
  2439. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2440. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2441. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2442. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2443. }
  2444. {
  2445. #ifdef CPPHTTPLIB_SSL_ENABLED
  2446. SSLClient cli(HOST, PORT);
  2447. cli.enable_server_certificate_verification(false);
  2448. #else
  2449. Client cli(HOST, PORT);
  2450. #endif
  2451. auto res = cli.Get("/hi");
  2452. ASSERT_TRUE(res);
  2453. EXPECT_EQ(StatusCode::OK_200, res->status);
  2454. EXPECT_EQ("Hello World!\n", res->body);
  2455. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2456. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2457. }
  2458. {
  2459. #ifdef CPPHTTPLIB_SSL_ENABLED
  2460. SSLClient cli(HOST, PORT);
  2461. cli.enable_server_certificate_verification(false);
  2462. #else
  2463. Client cli(HOST, PORT);
  2464. #endif
  2465. auto res = cli.Get("/aaa");
  2466. ASSERT_TRUE(res);
  2467. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2468. EXPECT_EQ("Error", res->body);
  2469. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2470. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2471. }
  2472. }
  2473. TEST(RequestHandlerTest, PreRequestHandler) {
  2474. auto route_path = "/user/:user";
  2475. Server svr;
  2476. svr.Get("/hi", [](const Request &, Response &res) {
  2477. res.set_content("hi", "text/plain");
  2478. });
  2479. svr.Get(route_path, [](const Request &req, Response &res) {
  2480. res.set_content(req.path_params.at("user"), "text/plain");
  2481. });
  2482. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2483. if (req.matched_route == route_path) {
  2484. auto user = req.path_params.at("user");
  2485. if (user != "john") {
  2486. res.status = StatusCode::Forbidden_403;
  2487. res.set_content("error", "text/html");
  2488. return Server::HandlerResponse::Handled;
  2489. }
  2490. }
  2491. return Server::HandlerResponse::Unhandled;
  2492. });
  2493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2494. auto se = detail::scope_exit([&] {
  2495. svr.stop();
  2496. thread.join();
  2497. ASSERT_FALSE(svr.is_running());
  2498. });
  2499. svr.wait_until_ready();
  2500. Client cli(HOST, PORT);
  2501. {
  2502. auto res = cli.Get("/hi");
  2503. ASSERT_TRUE(res);
  2504. EXPECT_EQ(StatusCode::OK_200, res->status);
  2505. EXPECT_EQ("hi", res->body);
  2506. }
  2507. {
  2508. auto res = cli.Get("/user/john");
  2509. ASSERT_TRUE(res);
  2510. EXPECT_EQ(StatusCode::OK_200, res->status);
  2511. EXPECT_EQ("john", res->body);
  2512. }
  2513. {
  2514. auto res = cli.Get("/user/invalid-user");
  2515. ASSERT_TRUE(res);
  2516. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2517. EXPECT_EQ("error", res->body);
  2518. }
  2519. }
  2520. TEST(AnyTest, BasicOperations) {
  2521. // Default construction
  2522. httplib::any a;
  2523. EXPECT_FALSE(a.has_value());
  2524. // Value construction and any_cast (pointer form, noexcept)
  2525. httplib::any b(42);
  2526. EXPECT_TRUE(b.has_value());
  2527. auto *p = httplib::any_cast<int>(&b);
  2528. ASSERT_NE(nullptr, p);
  2529. EXPECT_EQ(42, *p);
  2530. // Type mismatch → nullptr
  2531. auto *q = httplib::any_cast<std::string>(&b);
  2532. EXPECT_EQ(nullptr, q);
  2533. // any_cast (value form) succeeds
  2534. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2535. // any_cast (value form) throws on type mismatch
  2536. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2537. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2538. #endif
  2539. // Copy
  2540. httplib::any c = b;
  2541. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2542. // Move
  2543. httplib::any d = std::move(c);
  2544. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2545. // Assignment with different type
  2546. b = std::string("hello");
  2547. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2548. // Reset
  2549. b.reset();
  2550. EXPECT_FALSE(b.has_value());
  2551. }
  2552. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2553. struct AuthCtx {
  2554. std::string user_id;
  2555. };
  2556. Server svr;
  2557. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2558. res.user_data["auth"] = AuthCtx{"alice"};
  2559. return Server::HandlerResponse::Unhandled;
  2560. });
  2561. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2562. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2563. ASSERT_NE(nullptr, ctx);
  2564. res.set_content("Hello " + ctx->user_id, "text/plain");
  2565. });
  2566. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2567. auto se = detail::scope_exit([&] {
  2568. svr.stop();
  2569. thread.join();
  2570. ASSERT_FALSE(svr.is_running());
  2571. });
  2572. svr.wait_until_ready();
  2573. Client cli(HOST, PORT);
  2574. auto res = cli.Get("/me");
  2575. ASSERT_TRUE(res);
  2576. EXPECT_EQ(StatusCode::OK_200, res->status);
  2577. EXPECT_EQ("Hello alice", res->body);
  2578. }
  2579. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2580. struct RoleCtx {
  2581. std::string role;
  2582. };
  2583. Server svr;
  2584. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2585. res.user_data["role"] = RoleCtx{"admin"};
  2586. return Server::HandlerResponse::Unhandled;
  2587. });
  2588. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2589. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2590. ASSERT_NE(nullptr, ctx);
  2591. res.set_content(ctx->role, "text/plain");
  2592. });
  2593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2594. auto se = detail::scope_exit([&] {
  2595. svr.stop();
  2596. thread.join();
  2597. ASSERT_FALSE(svr.is_running());
  2598. });
  2599. svr.wait_until_ready();
  2600. Client cli(HOST, PORT);
  2601. auto res = cli.Get("/role");
  2602. ASSERT_TRUE(res);
  2603. EXPECT_EQ(StatusCode::OK_200, res->status);
  2604. EXPECT_EQ("admin", res->body);
  2605. }
  2606. TEST(InvalidFormatTest, StatusCode) {
  2607. Server svr;
  2608. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2609. res.set_content("Hello World!\n", "text/plain");
  2610. res.status = 9999; // Status should be a three-digit code...
  2611. });
  2612. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2613. auto se = detail::scope_exit([&] {
  2614. svr.stop();
  2615. thread.join();
  2616. ASSERT_FALSE(svr.is_running());
  2617. });
  2618. svr.wait_until_ready();
  2619. {
  2620. Client cli(HOST, PORT);
  2621. auto res = cli.Get("/hi");
  2622. ASSERT_FALSE(res);
  2623. }
  2624. }
  2625. TEST(URLFragmentTest, WithFragment) {
  2626. Server svr;
  2627. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2628. EXPECT_TRUE(req.target == "/hi");
  2629. });
  2630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2631. auto se = detail::scope_exit([&] {
  2632. svr.stop();
  2633. thread.join();
  2634. ASSERT_FALSE(svr.is_running());
  2635. });
  2636. svr.wait_until_ready();
  2637. {
  2638. Client cli(HOST, PORT);
  2639. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2640. EXPECT_TRUE(res);
  2641. EXPECT_EQ(StatusCode::OK_200, res->status);
  2642. res = cli.Get("/hi%23key1=val1=key2=val2");
  2643. EXPECT_TRUE(res);
  2644. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2645. }
  2646. }
  2647. TEST(HeaderWriter, SetHeaderWriter) {
  2648. Server svr;
  2649. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2650. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2651. return detail::write_headers(strm, hdrs);
  2652. });
  2653. svr.Get("/hi", [](const Request &req, Response &res) {
  2654. auto it = req.headers.find("CustomClientHeader");
  2655. EXPECT_TRUE(it != req.headers.end());
  2656. EXPECT_EQ(it->second, "CustomClientValue");
  2657. res.set_content("Hello World!\n", "text/plain");
  2658. });
  2659. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2660. auto se = detail::scope_exit([&] {
  2661. svr.stop();
  2662. thread.join();
  2663. ASSERT_FALSE(svr.is_running());
  2664. });
  2665. svr.wait_until_ready();
  2666. {
  2667. Client cli(HOST, PORT);
  2668. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2669. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2670. return detail::write_headers(strm, hdrs);
  2671. });
  2672. auto res = cli.Get("/hi");
  2673. EXPECT_TRUE(res);
  2674. EXPECT_EQ(StatusCode::OK_200, res->status);
  2675. auto it = res->headers.find("CustomServerHeader");
  2676. EXPECT_TRUE(it != res->headers.end());
  2677. EXPECT_EQ(it->second, "CustomServerValue");
  2678. }
  2679. }
  2680. class ServerTest : public ::testing::Test {
  2681. protected:
  2682. ServerTest()
  2683. : cli_(HOST, PORT)
  2684. #ifdef CPPHTTPLIB_SSL_ENABLED
  2685. ,
  2686. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2687. #endif
  2688. {
  2689. #ifdef CPPHTTPLIB_SSL_ENABLED
  2690. cli_.enable_server_certificate_verification(false);
  2691. #endif
  2692. // Allow LARGE_DATA (100MB) responses
  2693. cli_.set_payload_max_length(200 * 1024 * 1024);
  2694. }
  2695. virtual void SetUp() {
  2696. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2697. svr_.set_payload_max_length(200 * 1024 * 1024);
  2698. svr_.set_mount_point("/", "./www");
  2699. svr_.set_mount_point("/mount", "./www2");
  2700. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2701. svr_.Get("/hi",
  2702. [&](const Request & /*req*/, Response &res) {
  2703. res.set_content("Hello World!", "text/plain");
  2704. })
  2705. .Get("/file_content",
  2706. [&](const Request & /*req*/, Response &res) {
  2707. res.set_file_content("./www/dir/test.html");
  2708. })
  2709. .Get("/file_content_with_content_type",
  2710. [&](const Request & /*req*/, Response &res) {
  2711. res.set_file_content("./www/file", "text/plain");
  2712. })
  2713. .Get("/invalid_file_content",
  2714. [&](const Request & /*req*/, Response &res) {
  2715. res.set_file_content("./www/dir/invalid_file_path");
  2716. })
  2717. .Get("/http_response_splitting",
  2718. [&](const Request & /*req*/, Response &res) {
  2719. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2720. EXPECT_EQ(0U, res.headers.size());
  2721. EXPECT_FALSE(res.has_header("a"));
  2722. res.set_header("a", "1\nSet-Cookie: a=1");
  2723. EXPECT_EQ(0U, res.headers.size());
  2724. EXPECT_FALSE(res.has_header("a"));
  2725. res.set_header("a", "1\rSet-Cookie: a=1");
  2726. EXPECT_EQ(0U, res.headers.size());
  2727. EXPECT_FALSE(res.has_header("a"));
  2728. res.set_header("a\r\nb", "0");
  2729. EXPECT_EQ(0U, res.headers.size());
  2730. EXPECT_FALSE(res.has_header("a"));
  2731. res.set_header("a\rb", "0");
  2732. EXPECT_EQ(0U, res.headers.size());
  2733. EXPECT_FALSE(res.has_header("a"));
  2734. res.set_header("a\nb", "0");
  2735. EXPECT_EQ(0U, res.headers.size());
  2736. EXPECT_FALSE(res.has_header("a"));
  2737. res.set_redirect("1\r\nSet-Cookie: a=1");
  2738. EXPECT_EQ(0U, res.headers.size());
  2739. EXPECT_FALSE(res.has_header("Location"));
  2740. })
  2741. .Get("/slow",
  2742. [&](const Request & /*req*/, Response &res) {
  2743. std::this_thread::sleep_for(std::chrono::seconds(2));
  2744. res.set_content("slow", "text/plain");
  2745. })
  2746. #if 0
  2747. .Post("/slowpost",
  2748. [&](const Request & /*req*/, Response &res) {
  2749. std::this_thread::sleep_for(std::chrono::seconds(2));
  2750. res.set_content("slow", "text/plain");
  2751. })
  2752. #endif
  2753. .Get("/remote_addr",
  2754. [&](const Request &req, Response &res) {
  2755. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2756. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2757. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2758. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2759. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2760. #endif
  2761. res.set_content(req.remote_addr, "text/plain");
  2762. })
  2763. .Get("/local_addr",
  2764. [&](const Request &req, Response &res) {
  2765. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2766. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2767. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2768. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2769. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2770. #endif
  2771. auto local_addr = req.local_addr;
  2772. auto local_port = std::to_string(req.local_port);
  2773. res.set_content(local_addr.append(":").append(local_port),
  2774. "text/plain");
  2775. })
  2776. .Get("/endwith%",
  2777. [&](const Request & /*req*/, Response &res) {
  2778. res.set_content("Hello World!", "text/plain");
  2779. })
  2780. .Get("/a\\+\\+b",
  2781. [&](const Request &req, Response &res) {
  2782. ASSERT_TRUE(req.has_param("a +b"));
  2783. auto val = req.get_param_value("a +b");
  2784. res.set_content(val, "text/plain");
  2785. })
  2786. .Get("/", [&](const Request & /*req*/,
  2787. Response &res) { res.set_redirect("/hi"); })
  2788. .Post("/1",
  2789. [](const Request & /*req*/, Response &res) {
  2790. res.set_redirect("/2", StatusCode::SeeOther_303);
  2791. })
  2792. .Get("/2",
  2793. [](const Request & /*req*/, Response &res) {
  2794. res.set_content("redirected.", "text/plain");
  2795. res.status = StatusCode::OK_200;
  2796. })
  2797. .Post("/person",
  2798. [&](const Request &req, Response &res) {
  2799. if (req.has_param("name") && req.has_param("note")) {
  2800. persons_[req.get_param_value("name")] =
  2801. req.get_param_value("note");
  2802. } else {
  2803. res.status = StatusCode::BadRequest_400;
  2804. }
  2805. })
  2806. .Put("/person",
  2807. [&](const Request &req, Response &res) {
  2808. if (req.has_param("name") && req.has_param("note")) {
  2809. persons_[req.get_param_value("name")] =
  2810. req.get_param_value("note");
  2811. } else {
  2812. res.status = StatusCode::BadRequest_400;
  2813. }
  2814. })
  2815. .Get("/person/(.*)",
  2816. [&](const Request &req, Response &res) {
  2817. string name = req.matches[1];
  2818. if (persons_.find(name) != persons_.end()) {
  2819. auto note = persons_[name];
  2820. res.set_content(note, "text/plain");
  2821. } else {
  2822. res.status = StatusCode::NotFound_404;
  2823. }
  2824. })
  2825. .Delete("/person",
  2826. [&](const Request &req, Response &res) {
  2827. if (req.has_param("name")) {
  2828. string name = req.get_param_value("name");
  2829. if (persons_.find(name) != persons_.end()) {
  2830. persons_.erase(name);
  2831. res.set_content("DELETED", "text/plain");
  2832. } else {
  2833. res.status = StatusCode::NotFound_404;
  2834. }
  2835. } else {
  2836. res.status = StatusCode::BadRequest_400;
  2837. }
  2838. })
  2839. .Post("/x-www-form-urlencoded-json",
  2840. [&](const Request &req, Response &res) {
  2841. auto json = req.get_param_value("json");
  2842. ASSERT_EQ(JSON_DATA, json);
  2843. res.set_content(json, "appliation/json");
  2844. res.status = StatusCode::OK_200;
  2845. })
  2846. .Get("/streamed-chunked",
  2847. [&](const Request & /*req*/, Response &res) {
  2848. res.set_chunked_content_provider(
  2849. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2850. sink.os << "123";
  2851. sink.os << "456";
  2852. sink.os << "789";
  2853. sink.done();
  2854. return true;
  2855. });
  2856. })
  2857. .Get("/streamed-chunked-with-prohibited-trailer",
  2858. [&](const Request & /*req*/, Response &res) {
  2859. auto i = new int(0);
  2860. // Declare both a prohibited trailer (Content-Length) and an
  2861. // allowed one
  2862. res.set_header("Trailer", "Content-Length, X-Allowed");
  2863. res.set_chunked_content_provider(
  2864. "text/plain",
  2865. [i](size_t /*offset*/, DataSink &sink) {
  2866. switch (*i) {
  2867. case 0: sink.os << "123"; break;
  2868. case 1: sink.os << "456"; break;
  2869. case 2: sink.os << "789"; break;
  2870. case 3: {
  2871. sink.done_with_trailer(
  2872. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2873. } break;
  2874. }
  2875. (*i)++;
  2876. return true;
  2877. },
  2878. [i](bool success) {
  2879. EXPECT_TRUE(success);
  2880. delete i;
  2881. });
  2882. })
  2883. .Get("/streamed-chunked2",
  2884. [&](const Request & /*req*/, Response &res) {
  2885. auto i = new int(0);
  2886. res.set_chunked_content_provider(
  2887. "text/plain",
  2888. [i](size_t /*offset*/, DataSink &sink) {
  2889. switch (*i) {
  2890. case 0: sink.os << "123"; break;
  2891. case 1: sink.os << "456"; break;
  2892. case 2: sink.os << "789"; break;
  2893. case 3: sink.done(); break;
  2894. }
  2895. (*i)++;
  2896. return true;
  2897. },
  2898. [i](bool success) {
  2899. EXPECT_TRUE(success);
  2900. delete i;
  2901. });
  2902. })
  2903. .Get("/streamed-chunked-with-trailer",
  2904. [&](const Request & /*req*/, Response &res) {
  2905. auto i = new int(0);
  2906. res.set_header("Trailer", "Dummy1, Dummy2");
  2907. res.set_chunked_content_provider(
  2908. "text/plain",
  2909. [i](size_t /*offset*/, DataSink &sink) {
  2910. switch (*i) {
  2911. case 0: sink.os << "123"; break;
  2912. case 1: sink.os << "456"; break;
  2913. case 2: sink.os << "789"; break;
  2914. case 3: {
  2915. sink.done_with_trailer(
  2916. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2917. } break;
  2918. }
  2919. (*i)++;
  2920. return true;
  2921. },
  2922. [i](bool success) {
  2923. EXPECT_TRUE(success);
  2924. delete i;
  2925. });
  2926. })
  2927. .Get("/streamed",
  2928. [&](const Request & /*req*/, Response &res) {
  2929. res.set_content_provider(
  2930. 6, "text/plain",
  2931. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2932. sink.os << (offset < 3 ? "a" : "b");
  2933. return true;
  2934. });
  2935. })
  2936. .Get("/streamed-with-range",
  2937. [&](const Request &req, Response &res) {
  2938. auto data = new std::string("abcdefg");
  2939. res.set_content_provider(
  2940. data->size(), "text/plain",
  2941. [data](size_t offset, size_t length, DataSink &sink) {
  2942. size_t DATA_CHUNK_SIZE = 4;
  2943. const auto &d = *data;
  2944. auto out_len =
  2945. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2946. auto ret =
  2947. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2948. EXPECT_TRUE(ret);
  2949. return true;
  2950. },
  2951. [data, &req](bool success) {
  2952. EXPECT_EQ(success, !req.has_param("error"));
  2953. delete data;
  2954. });
  2955. })
  2956. .Get("/streamed-cancel",
  2957. [&](const Request & /*req*/, Response &res) {
  2958. res.set_content_provider(
  2959. size_t(-1), "text/plain",
  2960. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2961. sink.os << "data_chunk";
  2962. return true;
  2963. });
  2964. })
  2965. .Get("/regex-with-delimiter",
  2966. [&](const Request &req, Response & /*res*/) {
  2967. ASSERT_TRUE(req.has_param("key"));
  2968. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2969. })
  2970. .Get("/with-range",
  2971. [&](const Request & /*req*/, Response &res) {
  2972. res.set_content("abcdefg", "text/plain");
  2973. })
  2974. .Get("/test-start-time",
  2975. [&](const Request &req, Response & /*res*/) {
  2976. EXPECT_NE(req.start_time_,
  2977. std::chrono::steady_clock::time_point::min());
  2978. })
  2979. .Get("/with-range-customized-response",
  2980. [&](const Request & /*req*/, Response &res) {
  2981. res.status = StatusCode::BadRequest_400;
  2982. res.set_content(JSON_DATA, "application/json");
  2983. })
  2984. .Post("/chunked",
  2985. [&](const Request &req, Response & /*res*/) {
  2986. EXPECT_EQ(req.body, "dechunked post body");
  2987. })
  2988. .Post("/large-chunked",
  2989. [&](const Request &req, Response & /*res*/) {
  2990. std::string expected(6 * 30 * 1024u, 'a');
  2991. EXPECT_EQ(req.body, expected);
  2992. })
  2993. .Post("/multipart",
  2994. [&](const Request &req, Response & /*res*/) {
  2995. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2996. req.form.get_field_count("text2") +
  2997. req.form.get_field_count("file3") +
  2998. req.form.get_field_count("file4"));
  2999. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3000. req.form.get_file_count("file2"));
  3001. ASSERT_TRUE(!req.form.has_file("???"));
  3002. ASSERT_TRUE(!req.form.has_field("???"));
  3003. ASSERT_TRUE(req.body.empty());
  3004. {
  3005. const auto &text = req.form.get_field("text1");
  3006. EXPECT_EQ("text default", text);
  3007. }
  3008. {
  3009. const auto &text = req.form.get_field("text2");
  3010. EXPECT_EQ("aωb", text);
  3011. }
  3012. {
  3013. const auto &file = req.form.get_file("file1");
  3014. EXPECT_EQ("hello.txt", file.filename);
  3015. EXPECT_EQ("text/plain", file.content_type);
  3016. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3017. }
  3018. {
  3019. const auto &file = req.form.get_file("file2");
  3020. EXPECT_EQ("world.json", file.filename);
  3021. EXPECT_EQ("application/json", file.content_type);
  3022. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3023. }
  3024. {
  3025. const auto &text = req.form.get_field("file3");
  3026. EXPECT_EQ(0u, text.size());
  3027. }
  3028. {
  3029. const auto &text = req.form.get_field("file4");
  3030. EXPECT_EQ(0u, text.size());
  3031. }
  3032. })
  3033. .Post("/multipart/multi_file_values",
  3034. [&](const Request &req, Response & /*res*/) {
  3035. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3036. req.form.get_field_count("multi_text1"));
  3037. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3038. ASSERT_TRUE(!req.form.has_file("???"));
  3039. ASSERT_TRUE(!req.form.has_field("???"));
  3040. ASSERT_TRUE(req.body.empty());
  3041. {
  3042. const auto &text = req.form.get_field("text");
  3043. EXPECT_EQ("default text", text);
  3044. }
  3045. {
  3046. const auto &text1_values = req.form.get_fields("multi_text1");
  3047. EXPECT_EQ(2u, text1_values.size());
  3048. EXPECT_EQ("aaaaa", text1_values[0]);
  3049. EXPECT_EQ("bbbbb", text1_values[1]);
  3050. }
  3051. {
  3052. const auto &file1_values = req.form.get_files("multi_file1");
  3053. EXPECT_EQ(2u, file1_values.size());
  3054. auto file1 = file1_values[0];
  3055. EXPECT_EQ(file1.filename, "hello.txt");
  3056. EXPECT_EQ(file1.content_type, "text/plain");
  3057. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3058. auto file2 = file1_values[1];
  3059. EXPECT_EQ(file2.filename, "world.json");
  3060. EXPECT_EQ(file2.content_type, "application/json");
  3061. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3062. }
  3063. })
  3064. .Post("/empty",
  3065. [&](const Request &req, Response &res) {
  3066. EXPECT_EQ(req.body, "");
  3067. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3068. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3069. res.set_content("empty", "text/plain");
  3070. })
  3071. .Post("/empty-no-content-type",
  3072. [&](const Request &req, Response &res) {
  3073. EXPECT_EQ(req.body, "");
  3074. EXPECT_FALSE(req.has_header("Content-Type"));
  3075. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3076. res.set_content("empty-no-content-type", "text/plain");
  3077. })
  3078. .Post("/path-only",
  3079. [&](const Request &req, Response &res) {
  3080. EXPECT_EQ(req.body, "");
  3081. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3082. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3083. res.set_content("path-only", "text/plain");
  3084. })
  3085. .Post("/path-headers-only",
  3086. [&](const Request &req, Response &res) {
  3087. EXPECT_EQ(req.body, "");
  3088. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3089. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3090. EXPECT_EQ("world", req.get_header_value("hello"));
  3091. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3092. res.set_content("path-headers-only", "text/plain");
  3093. })
  3094. .Post("/post-large",
  3095. [&](const Request &req, Response &res) {
  3096. EXPECT_EQ(req.body, LARGE_DATA);
  3097. res.set_content(req.body, "text/plain");
  3098. })
  3099. .Post("/post-loopback",
  3100. [&](const Request &, Response &res,
  3101. ContentReader const &content_reader) {
  3102. std::string body;
  3103. content_reader([&](const char *data, size_t data_length) {
  3104. body.append(data, data_length);
  3105. return true;
  3106. });
  3107. res.set_content(body, "text/plain");
  3108. })
  3109. .Put("/put-loopback",
  3110. [&](const Request &, Response &res,
  3111. ContentReader const &content_reader) {
  3112. std::string body;
  3113. content_reader([&](const char *data, size_t data_length) {
  3114. body.append(data, data_length);
  3115. return true;
  3116. });
  3117. res.set_content(body, "text/plain");
  3118. })
  3119. .Patch("/patch-loopback",
  3120. [&](const Request &, Response &res,
  3121. ContentReader const &content_reader) {
  3122. std::string body;
  3123. content_reader([&](const char *data, size_t data_length) {
  3124. body.append(data, data_length);
  3125. return true;
  3126. });
  3127. res.set_content(body, "text/plain");
  3128. })
  3129. .Put("/empty-no-content-type",
  3130. [&](const Request &req, Response &res) {
  3131. EXPECT_EQ(req.body, "");
  3132. EXPECT_FALSE(req.has_header("Content-Type"));
  3133. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3134. res.set_content("empty-no-content-type", "text/plain");
  3135. })
  3136. .Put("/put",
  3137. [&](const Request &req, Response &res) {
  3138. EXPECT_EQ(req.body, "PUT");
  3139. res.set_content(req.body, "text/plain");
  3140. })
  3141. .Put("/put-large",
  3142. [&](const Request &req, Response &res) {
  3143. EXPECT_EQ(req.body, LARGE_DATA);
  3144. res.set_content(req.body, "text/plain");
  3145. })
  3146. .Patch("/patch",
  3147. [&](const Request &req, Response &res) {
  3148. EXPECT_EQ(req.body, "PATCH");
  3149. res.set_content(req.body, "text/plain");
  3150. })
  3151. .Delete("/delete",
  3152. [&](const Request & /*req*/, Response &res) {
  3153. res.set_content("DELETE", "text/plain");
  3154. })
  3155. .Delete("/delete-body",
  3156. [&](const Request &req, Response &res) {
  3157. EXPECT_EQ(req.body, "content");
  3158. res.set_content(req.body, "text/plain");
  3159. })
  3160. .Options(R"(\*)",
  3161. [&](const Request & /*req*/, Response &res) {
  3162. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3163. })
  3164. .Get("/request-target",
  3165. [&](const Request &req, Response & /*res*/) {
  3166. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3167. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3168. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3169. })
  3170. .Get("/long-query-value",
  3171. [&](const Request &req, Response & /*res*/) {
  3172. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3173. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3174. })
  3175. .Get("/too-long-query-value",
  3176. [&](const Request &req, Response & /*res*/) {
  3177. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3178. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3179. })
  3180. .Get("/array-param",
  3181. [&](const Request &req, Response & /*res*/) {
  3182. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3183. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3184. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3185. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3186. })
  3187. .Post("/validate-no-multiple-headers",
  3188. [&](const Request &req, Response & /*res*/) {
  3189. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3190. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3191. })
  3192. .Post("/content_receiver",
  3193. [&](const Request &req, Response &res,
  3194. const ContentReader &content_reader) {
  3195. if (req.is_multipart_form_data()) {
  3196. std::vector<FormData> items;
  3197. content_reader(
  3198. [&](const FormData &file) {
  3199. items.push_back(file);
  3200. return true;
  3201. },
  3202. [&](const char *data, size_t data_length) {
  3203. items.back().content.append(data, data_length);
  3204. return true;
  3205. });
  3206. EXPECT_EQ(5u, items.size());
  3207. {
  3208. const auto &file = get_file_value(items, "text1");
  3209. EXPECT_TRUE(file.filename.empty());
  3210. EXPECT_EQ("text default", file.content);
  3211. }
  3212. {
  3213. const auto &file = get_file_value(items, "text2");
  3214. EXPECT_TRUE(file.filename.empty());
  3215. EXPECT_EQ("aωb", file.content);
  3216. }
  3217. {
  3218. const auto &file = get_file_value(items, "file1");
  3219. EXPECT_EQ("hello.txt", file.filename);
  3220. EXPECT_EQ("text/plain", file.content_type);
  3221. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3222. }
  3223. {
  3224. const auto &file = get_file_value(items, "file2");
  3225. EXPECT_EQ("world.json", file.filename);
  3226. EXPECT_EQ("application/json", file.content_type);
  3227. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3228. }
  3229. {
  3230. const auto &file = get_file_value(items, "file3");
  3231. EXPECT_TRUE(file.filename.empty());
  3232. EXPECT_EQ("application/octet-stream", file.content_type);
  3233. EXPECT_EQ(0u, file.content.size());
  3234. }
  3235. } else {
  3236. std::string body;
  3237. content_reader([&](const char *data, size_t data_length) {
  3238. EXPECT_EQ(7U, data_length);
  3239. body.append(data, data_length);
  3240. return true;
  3241. });
  3242. EXPECT_EQ(body, "content");
  3243. res.set_content(body, "text/plain");
  3244. }
  3245. })
  3246. .Put("/content_receiver",
  3247. [&](const Request & /*req*/, Response &res,
  3248. const ContentReader &content_reader) {
  3249. std::string body;
  3250. content_reader([&](const char *data, size_t data_length) {
  3251. body.append(data, data_length);
  3252. return true;
  3253. });
  3254. EXPECT_EQ(body, "content");
  3255. res.set_content(body, "text/plain");
  3256. })
  3257. .Patch("/content_receiver",
  3258. [&](const Request & /*req*/, Response &res,
  3259. const ContentReader &content_reader) {
  3260. std::string body;
  3261. content_reader([&](const char *data, size_t data_length) {
  3262. body.append(data, data_length);
  3263. return true;
  3264. });
  3265. EXPECT_EQ(body, "content");
  3266. res.set_content(body, "text/plain");
  3267. })
  3268. .Post("/query-string-and-body",
  3269. [&](const Request &req, Response & /*res*/) {
  3270. ASSERT_TRUE(req.has_param("key"));
  3271. EXPECT_EQ(req.get_param_value("key"), "value");
  3272. EXPECT_EQ(req.body, "content");
  3273. })
  3274. .Get("/last-request",
  3275. [&](const Request &req, Response & /*res*/) {
  3276. EXPECT_EQ("close", req.get_header_value("Connection"));
  3277. })
  3278. .Get(R"(/redirect/(\d+))",
  3279. [&](const Request &req, Response &res) {
  3280. auto num = std::stoi(req.matches[1]) + 1;
  3281. std::string url = "/redirect/" + std::to_string(num);
  3282. res.set_redirect(url);
  3283. })
  3284. .Post("/binary",
  3285. [&](const Request &req, Response &res) {
  3286. EXPECT_EQ(4U, req.body.size());
  3287. EXPECT_EQ("application/octet-stream",
  3288. req.get_header_value("Content-Type"));
  3289. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3290. res.set_content(req.body, "application/octet-stream");
  3291. })
  3292. .Put("/binary",
  3293. [&](const Request &req, Response &res) {
  3294. EXPECT_EQ(4U, req.body.size());
  3295. EXPECT_EQ("application/octet-stream",
  3296. req.get_header_value("Content-Type"));
  3297. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3298. res.set_content(req.body, "application/octet-stream");
  3299. })
  3300. .Patch("/binary",
  3301. [&](const Request &req, Response &res) {
  3302. EXPECT_EQ(4U, req.body.size());
  3303. EXPECT_EQ("application/octet-stream",
  3304. req.get_header_value("Content-Type"));
  3305. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3306. res.set_content(req.body, "application/octet-stream");
  3307. })
  3308. .Delete("/binary",
  3309. [&](const Request &req, Response &res) {
  3310. EXPECT_EQ(4U, req.body.size());
  3311. EXPECT_EQ("application/octet-stream",
  3312. req.get_header_value("Content-Type"));
  3313. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3314. res.set_content(req.body, "application/octet-stream");
  3315. })
  3316. .Get("/issue1772",
  3317. [&](const Request & /*req*/, Response &res) {
  3318. res.status = 401;
  3319. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3320. })
  3321. .Delete("/issue609",
  3322. [](const httplib::Request &, httplib::Response &res,
  3323. const httplib::ContentReader &) {
  3324. res.set_content("ok", "text/plain");
  3325. })
  3326. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3327. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3328. .Get("/compress",
  3329. [&](const Request & /*req*/, Response &res) {
  3330. res.set_content(
  3331. "12345678901234567890123456789012345678901234567890123456789"
  3332. "01234567890123456789012345678901234567890",
  3333. "text/plain");
  3334. })
  3335. .Get("/compress-with-charset",
  3336. [&](const Request & /*req*/, Response &res) {
  3337. res.set_content(
  3338. "12345678901234567890123456789012345678901234567890123456789"
  3339. "01234567890123456789012345678901234567890",
  3340. "application/json; charset=utf-8");
  3341. })
  3342. .Get("/nocompress",
  3343. [&](const Request & /*req*/, Response &res) {
  3344. res.set_content(
  3345. "12345678901234567890123456789012345678901234567890123456789"
  3346. "01234567890123456789012345678901234567890",
  3347. "application/octet-stream");
  3348. })
  3349. .Post("/compress-multipart",
  3350. [&](const Request &req, Response & /*res*/) {
  3351. EXPECT_EQ(2u, req.form.fields.size());
  3352. ASSERT_TRUE(!req.form.has_field("???"));
  3353. {
  3354. const auto &text = req.form.get_field("key1");
  3355. EXPECT_EQ("test", text);
  3356. }
  3357. {
  3358. const auto &text = req.form.get_field("key2");
  3359. EXPECT_EQ("--abcdefg123", text);
  3360. }
  3361. })
  3362. #endif
  3363. ;
  3364. persons_["john"] = "programmer";
  3365. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3366. svr_.wait_until_ready();
  3367. }
  3368. virtual void TearDown() {
  3369. svr_.stop();
  3370. if (!request_threads_.empty()) {
  3371. std::this_thread::sleep_for(std::chrono::seconds(1));
  3372. for (auto &t : request_threads_) {
  3373. t.join();
  3374. }
  3375. }
  3376. t_.join();
  3377. }
  3378. map<string, string> persons_;
  3379. #ifdef CPPHTTPLIB_SSL_ENABLED
  3380. SSLClient cli_;
  3381. SSLServer svr_;
  3382. #else
  3383. Client cli_;
  3384. Server svr_;
  3385. #endif
  3386. thread t_;
  3387. std::vector<thread> request_threads_;
  3388. };
  3389. TEST_F(ServerTest, GetMethod200) {
  3390. auto res = cli_.Get("/hi");
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ("HTTP/1.1", res->version);
  3393. EXPECT_EQ(StatusCode::OK_200, res->status);
  3394. EXPECT_EQ("OK", res->reason);
  3395. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3396. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3397. EXPECT_EQ("Hello World!", res->body);
  3398. }
  3399. TEST_F(ServerTest, GetEmptyFile) {
  3400. auto res = cli_.Get("/empty_file");
  3401. ASSERT_TRUE(res);
  3402. EXPECT_EQ(StatusCode::OK_200, res->status);
  3403. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3404. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3405. EXPECT_EQ("", res->body);
  3406. }
  3407. TEST_F(ServerTest, GetFileContent) {
  3408. auto res = cli_.Get("/file_content");
  3409. ASSERT_TRUE(res);
  3410. EXPECT_EQ(StatusCode::OK_200, res->status);
  3411. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3412. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3413. EXPECT_EQ("test.html", res->body);
  3414. }
  3415. TEST_F(ServerTest, GetFileContentWithRange) {
  3416. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3417. ASSERT_TRUE(res);
  3418. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3419. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3420. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3421. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3422. EXPECT_EQ("est", res->body);
  3423. }
  3424. TEST_F(ServerTest, GetFileContentWithContentType) {
  3425. auto res = cli_.Get("/file_content_with_content_type");
  3426. ASSERT_TRUE(res);
  3427. EXPECT_EQ(StatusCode::OK_200, res->status);
  3428. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3429. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3430. EXPECT_EQ("file\n", res->body);
  3431. }
  3432. TEST_F(ServerTest, GetInvalidFileContent) {
  3433. auto res = cli_.Get("/invalid_file_content");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3436. }
  3437. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3438. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3439. ASSERT_TRUE(res);
  3440. EXPECT_EQ("HTTP/1.1", res->version);
  3441. EXPECT_EQ(StatusCode::OK_200, res->status);
  3442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3443. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3444. EXPECT_EQ("Hello World!", res->body);
  3445. }
  3446. TEST_F(ServerTest, GetMethod302) {
  3447. auto res = cli_.Get("/");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::Found_302, res->status);
  3450. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3451. }
  3452. TEST_F(ServerTest, GetMethod302Redirect) {
  3453. cli_.set_follow_location(true);
  3454. auto res = cli_.Get("/");
  3455. ASSERT_TRUE(res);
  3456. EXPECT_EQ(StatusCode::OK_200, res->status);
  3457. EXPECT_EQ("Hello World!", res->body);
  3458. EXPECT_EQ("/hi", res->location);
  3459. }
  3460. TEST_F(ServerTest, GetMethod404) {
  3461. auto res = cli_.Get("/invalid");
  3462. ASSERT_TRUE(res);
  3463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3464. }
  3465. TEST_F(ServerTest, HeadMethod200) {
  3466. auto res = cli_.Head("/hi");
  3467. ASSERT_TRUE(res);
  3468. EXPECT_EQ(StatusCode::OK_200, res->status);
  3469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3470. EXPECT_TRUE(res->body.empty());
  3471. }
  3472. TEST_F(ServerTest, HeadMethod200Static) {
  3473. auto res = cli_.Head("/mount/dir/index.html");
  3474. ASSERT_TRUE(res);
  3475. EXPECT_EQ(StatusCode::OK_200, res->status);
  3476. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3477. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3478. EXPECT_TRUE(res->body.empty());
  3479. }
  3480. TEST_F(ServerTest, HeadMethod404) {
  3481. auto res = cli_.Head("/invalid");
  3482. ASSERT_TRUE(res);
  3483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3484. EXPECT_TRUE(res->body.empty());
  3485. }
  3486. TEST_F(ServerTest, GetMethodPersonJohn) {
  3487. auto res = cli_.Get("/person/john");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::OK_200, res->status);
  3490. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3491. EXPECT_EQ("programmer", res->body);
  3492. }
  3493. TEST_F(ServerTest, PostMethod1) {
  3494. auto res = cli_.Get("/person/john1");
  3495. ASSERT_TRUE(res);
  3496. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3497. res = cli_.Post("/person", "name=john1&note=coder",
  3498. "application/x-www-form-urlencoded");
  3499. ASSERT_TRUE(res);
  3500. ASSERT_EQ(StatusCode::OK_200, res->status);
  3501. res = cli_.Get("/person/john1");
  3502. ASSERT_TRUE(res);
  3503. ASSERT_EQ(StatusCode::OK_200, res->status);
  3504. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3505. ASSERT_EQ("coder", res->body);
  3506. }
  3507. TEST_F(ServerTest, PostMethod2) {
  3508. auto res = cli_.Get("/person/john2");
  3509. ASSERT_TRUE(res);
  3510. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3511. Params params;
  3512. params.emplace("name", "john2");
  3513. params.emplace("note", "coder");
  3514. res = cli_.Post("/person", params);
  3515. ASSERT_TRUE(res);
  3516. ASSERT_EQ(StatusCode::OK_200, res->status);
  3517. res = cli_.Get("/person/john2");
  3518. ASSERT_TRUE(res);
  3519. ASSERT_EQ(StatusCode::OK_200, res->status);
  3520. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3521. ASSERT_EQ("coder", res->body);
  3522. }
  3523. TEST_F(ServerTest, PutMethod3) {
  3524. auto res = cli_.Get("/person/john3");
  3525. ASSERT_TRUE(res);
  3526. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3527. Params params;
  3528. params.emplace("name", "john3");
  3529. params.emplace("note", "coder");
  3530. res = cli_.Put("/person", params);
  3531. ASSERT_TRUE(res);
  3532. ASSERT_EQ(StatusCode::OK_200, res->status);
  3533. res = cli_.Get("/person/john3");
  3534. ASSERT_TRUE(res);
  3535. ASSERT_EQ(StatusCode::OK_200, res->status);
  3536. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3537. ASSERT_EQ("coder", res->body);
  3538. }
  3539. TEST_F(ServerTest, DeleteMethod1) {
  3540. auto res = cli_.Get("/person/john4");
  3541. ASSERT_TRUE(res);
  3542. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3543. Params params;
  3544. params.emplace("name", "john4");
  3545. params.emplace("note", "coder");
  3546. res = cli_.Post("/person", params);
  3547. ASSERT_TRUE(res);
  3548. ASSERT_EQ(StatusCode::OK_200, res->status);
  3549. res = cli_.Get("/person/john4");
  3550. ASSERT_TRUE(res);
  3551. ASSERT_EQ(StatusCode::OK_200, res->status);
  3552. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3553. ASSERT_EQ("coder", res->body);
  3554. Params delete_params;
  3555. delete_params.emplace("name", "john4");
  3556. res = cli_.Delete("/person", delete_params);
  3557. ASSERT_TRUE(res);
  3558. ASSERT_EQ(StatusCode::OK_200, res->status);
  3559. ASSERT_EQ("DELETED", res->body);
  3560. res = cli_.Get("/person/john4");
  3561. ASSERT_TRUE(res);
  3562. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3563. }
  3564. TEST_F(ServerTest, DeleteMethod2) {
  3565. auto res = cli_.Get("/person/john5");
  3566. ASSERT_TRUE(res);
  3567. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3568. Params params;
  3569. params.emplace("name", "john5");
  3570. params.emplace("note", "developer");
  3571. res = cli_.Post("/person", params);
  3572. ASSERT_TRUE(res);
  3573. ASSERT_EQ(StatusCode::OK_200, res->status);
  3574. res = cli_.Get("/person/john5");
  3575. ASSERT_TRUE(res);
  3576. ASSERT_EQ(StatusCode::OK_200, res->status);
  3577. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3578. ASSERT_EQ("developer", res->body);
  3579. Params delete_params;
  3580. delete_params.emplace("name", "john5");
  3581. Headers headers;
  3582. headers.emplace("Custom-Header", "test-value");
  3583. res = cli_.Delete("/person", headers, delete_params);
  3584. ASSERT_TRUE(res);
  3585. ASSERT_EQ(StatusCode::OK_200, res->status);
  3586. ASSERT_EQ("DELETED", res->body);
  3587. res = cli_.Get("/person/john5");
  3588. ASSERT_TRUE(res);
  3589. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3590. }
  3591. TEST_F(ServerTest, DeleteMethod3) {
  3592. auto res = cli_.Get("/person/john6");
  3593. ASSERT_TRUE(res);
  3594. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3595. Params params;
  3596. params.emplace("name", "john6");
  3597. params.emplace("note", "tester");
  3598. res = cli_.Post("/person", params);
  3599. ASSERT_TRUE(res);
  3600. ASSERT_EQ(StatusCode::OK_200, res->status);
  3601. res = cli_.Get("/person/john6");
  3602. ASSERT_TRUE(res);
  3603. ASSERT_EQ(StatusCode::OK_200, res->status);
  3604. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3605. ASSERT_EQ("tester", res->body);
  3606. Params delete_params;
  3607. delete_params.emplace("name", "john6");
  3608. Headers headers;
  3609. headers.emplace("Custom-Header", "test-value");
  3610. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3611. ASSERT_TRUE(res);
  3612. ASSERT_EQ(StatusCode::OK_200, res->status);
  3613. ASSERT_EQ("DELETED", res->body);
  3614. res = cli_.Get("/person/john6");
  3615. ASSERT_TRUE(res);
  3616. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3617. }
  3618. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3619. Params params;
  3620. params.emplace("json", JSON_DATA);
  3621. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3622. ASSERT_TRUE(res);
  3623. ASSERT_EQ(StatusCode::OK_200, res->status);
  3624. ASSERT_EQ(JSON_DATA, res->body);
  3625. }
  3626. TEST_F(ServerTest, PostEmptyContent) {
  3627. auto res = cli_.Post("/empty", "", "text/plain");
  3628. ASSERT_TRUE(res);
  3629. ASSERT_EQ(StatusCode::OK_200, res->status);
  3630. ASSERT_EQ("empty", res->body);
  3631. }
  3632. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3633. auto res = cli_.Post("/empty-no-content-type");
  3634. ASSERT_TRUE(res);
  3635. ASSERT_EQ(StatusCode::OK_200, res->status);
  3636. ASSERT_EQ("empty-no-content-type", res->body);
  3637. }
  3638. TEST_F(ServerTest, PostPathOnly) {
  3639. auto res = cli_.Post("/path-only");
  3640. ASSERT_TRUE(res);
  3641. ASSERT_EQ(StatusCode::OK_200, res->status);
  3642. ASSERT_EQ("path-only", res->body);
  3643. }
  3644. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3645. auto res = cli_.Post("/path-headers-only",
  3646. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3647. ASSERT_TRUE(res);
  3648. ASSERT_EQ(StatusCode::OK_200, res->status);
  3649. ASSERT_EQ("path-headers-only", res->body);
  3650. }
  3651. TEST_F(ServerTest, PostLarge) {
  3652. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3653. ASSERT_TRUE(res);
  3654. ASSERT_EQ(StatusCode::OK_200, res->status);
  3655. EXPECT_EQ(LARGE_DATA, res->body);
  3656. }
  3657. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3658. auto res = cli_.Put("/empty-no-content-type");
  3659. ASSERT_TRUE(res);
  3660. ASSERT_EQ(StatusCode::OK_200, res->status);
  3661. ASSERT_EQ("empty-no-content-type", res->body);
  3662. }
  3663. TEST_F(ServerTest, GetMethodDir) {
  3664. auto res = cli_.Get("/dir/");
  3665. ASSERT_TRUE(res);
  3666. EXPECT_EQ(StatusCode::OK_200, res->status);
  3667. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3668. auto body = R"(<html>
  3669. <head>
  3670. </head>
  3671. <body>
  3672. <a href="/dir/test.html">Test</a>
  3673. <a href="/hi">hi</a>
  3674. </body>
  3675. </html>
  3676. )";
  3677. EXPECT_EQ(body, res->body);
  3678. }
  3679. TEST_F(ServerTest, GetMethodDirTest) {
  3680. auto res = cli_.Get("/dir/test.html");
  3681. ASSERT_TRUE(res);
  3682. EXPECT_EQ(StatusCode::OK_200, res->status);
  3683. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3684. EXPECT_EQ("test.html", res->body);
  3685. }
  3686. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3687. auto res = cli_.Get("/dir/../dir/test.html");
  3688. ASSERT_TRUE(res);
  3689. EXPECT_EQ(StatusCode::OK_200, res->status);
  3690. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3691. EXPECT_EQ("test.html", res->body);
  3692. }
  3693. TEST_F(ServerTest, GetMethodInvalidPath) {
  3694. auto res = cli_.Get("/dir/../test.html");
  3695. ASSERT_TRUE(res);
  3696. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3697. }
  3698. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3699. auto res = cli_.Get("/../www/dir/test.html");
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3702. }
  3703. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3704. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3705. ASSERT_TRUE(res);
  3706. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3707. }
  3708. TEST_F(ServerTest, GetMethodDirMountTest) {
  3709. auto res = cli_.Get("/mount/dir/test.html");
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::OK_200, res->status);
  3712. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3713. EXPECT_EQ("test.html", res->body);
  3714. }
  3715. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3716. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::OK_200, res->status);
  3719. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3720. EXPECT_EQ("test.html", res->body);
  3721. }
  3722. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3723. auto res = cli_.Get("/mount/dir/../test.html");
  3724. ASSERT_TRUE(res);
  3725. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3726. }
  3727. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3728. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3729. ASSERT_TRUE(res);
  3730. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3731. }
  3732. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3733. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3734. ASSERT_TRUE(res);
  3735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3736. }
  3737. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3738. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3739. ASSERT_TRUE(res);
  3740. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3741. }
  3742. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3743. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3744. ASSERT_TRUE(res);
  3745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3746. }
  3747. TEST_F(ServerTest, PostMethod303) {
  3748. auto res = cli_.Post("/1", "body", "text/plain");
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3751. EXPECT_EQ("/2", res->get_header_value("Location"));
  3752. }
  3753. TEST_F(ServerTest, PostMethod303Redirect) {
  3754. cli_.set_follow_location(true);
  3755. auto res = cli_.Post("/1", "body", "text/plain");
  3756. ASSERT_TRUE(res);
  3757. EXPECT_EQ(StatusCode::OK_200, res->status);
  3758. EXPECT_EQ("redirected.", res->body);
  3759. EXPECT_EQ("/2", res->location);
  3760. }
  3761. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3762. auto res = cli_.Get("/dir/test.abcde");
  3763. ASSERT_TRUE(res);
  3764. EXPECT_EQ(StatusCode::OK_200, res->status);
  3765. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3766. EXPECT_EQ("abcde", res->body);
  3767. }
  3768. TEST_F(ServerTest, StaticFileRange) {
  3769. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3770. ASSERT_TRUE(res);
  3771. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3772. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3773. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3774. EXPECT_EQ(true, res->has_header("Content-Range"));
  3775. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3776. EXPECT_EQ(std::string("cd"), res->body);
  3777. }
  3778. TEST_F(ServerTest, StaticFileRanges) {
  3779. auto res =
  3780. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3781. ASSERT_TRUE(res);
  3782. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3783. EXPECT_TRUE(
  3784. res->get_header_value("Content-Type")
  3785. .find(
  3786. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3787. 0);
  3788. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3789. }
  3790. TEST_F(ServerTest, StaticFileRangeHead) {
  3791. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3792. ASSERT_TRUE(res);
  3793. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3794. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3795. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3796. EXPECT_EQ(true, res->has_header("Content-Range"));
  3797. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3798. }
  3799. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3800. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3801. ASSERT_TRUE(res);
  3802. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3803. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3804. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3805. EXPECT_EQ(true, res->has_header("Content-Range"));
  3806. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3807. res->get_header_value("Content-Range"));
  3808. EXPECT_EQ("LAST\n", res->body);
  3809. }
  3810. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3811. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3812. ASSERT_TRUE(res);
  3813. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3814. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3815. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3816. EXPECT_EQ(true, res->has_header("Content-Range"));
  3817. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3818. }
  3819. TEST_F(ServerTest, StaticFileBigFile) {
  3820. auto res = cli_.Get("/dir/1MB.txt");
  3821. ASSERT_TRUE(res);
  3822. EXPECT_EQ(StatusCode::OK_200, res->status);
  3823. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3824. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3825. }
  3826. TEST_F(ServerTest, InvalidBaseDirMount) {
  3827. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3828. }
  3829. TEST_F(ServerTest, Binary) {
  3830. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3831. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3832. "application/octet-stream");
  3833. ASSERT_TRUE(res);
  3834. ASSERT_EQ(StatusCode::OK_200, res->status);
  3835. ASSERT_EQ(4U, res->body.size());
  3836. res = cli_.Put("/binary", binary.data(), binary.size(),
  3837. "application/octet-stream");
  3838. ASSERT_TRUE(res);
  3839. ASSERT_EQ(StatusCode::OK_200, res->status);
  3840. ASSERT_EQ(4U, res->body.size());
  3841. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3842. "application/octet-stream");
  3843. ASSERT_TRUE(res);
  3844. ASSERT_EQ(StatusCode::OK_200, res->status);
  3845. ASSERT_EQ(4U, res->body.size());
  3846. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3847. "application/octet-stream");
  3848. ASSERT_TRUE(res);
  3849. ASSERT_EQ(StatusCode::OK_200, res->status);
  3850. ASSERT_EQ(4U, res->body.size());
  3851. }
  3852. TEST_F(ServerTest, BinaryString) {
  3853. auto binary = std::string("\x00\x01\x02\x03", 4);
  3854. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3855. ASSERT_TRUE(res);
  3856. ASSERT_EQ(StatusCode::OK_200, res->status);
  3857. ASSERT_EQ(4U, res->body.size());
  3858. res = cli_.Put("/binary", binary, "application/octet-stream");
  3859. ASSERT_TRUE(res);
  3860. ASSERT_EQ(StatusCode::OK_200, res->status);
  3861. ASSERT_EQ(4U, res->body.size());
  3862. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3863. ASSERT_TRUE(res);
  3864. ASSERT_EQ(StatusCode::OK_200, res->status);
  3865. ASSERT_EQ(4U, res->body.size());
  3866. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3867. ASSERT_TRUE(res);
  3868. ASSERT_EQ(StatusCode::OK_200, res->status);
  3869. ASSERT_EQ(4U, res->body.size());
  3870. }
  3871. TEST_F(ServerTest, EmptyRequest) {
  3872. auto res = cli_.Get("");
  3873. ASSERT_TRUE(!res);
  3874. EXPECT_EQ(Error::Connection, res.error());
  3875. }
  3876. TEST_F(ServerTest, LongRequest) {
  3877. std::string request;
  3878. for (size_t i = 0; i < 545; i++) {
  3879. request += "/TooLongRequest";
  3880. }
  3881. request += "OK";
  3882. auto res = cli_.Get(request.c_str());
  3883. ASSERT_TRUE(res);
  3884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3885. }
  3886. TEST_F(ServerTest, TooLongRequest) {
  3887. std::string request;
  3888. for (size_t i = 0; i < 546; i++) {
  3889. request += "/TooLongRequest";
  3890. }
  3891. request += "_NG";
  3892. auto start = std::chrono::high_resolution_clock::now();
  3893. cli_.set_keep_alive(true);
  3894. auto res = cli_.Get(request.c_str());
  3895. auto end = std::chrono::high_resolution_clock::now();
  3896. auto elapsed =
  3897. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3898. .count();
  3899. ASSERT_TRUE(res);
  3900. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3901. EXPECT_LE(elapsed, 1000);
  3902. EXPECT_EQ("close", res->get_header_value("Connection"));
  3903. EXPECT_FALSE(cli_.is_socket_open());
  3904. }
  3905. TEST_F(ServerTest, AlmostTooLongRequest) {
  3906. // test for #2046 - URI length check shouldn't include other content on req
  3907. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3908. // leading /, space, HTTP/1.1)
  3909. std::string request =
  3910. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3911. auto res = cli_.Get(request.c_str());
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3914. }
  3915. TEST_F(ServerTest, LongHeader) {
  3916. Request req;
  3917. req.method = "GET";
  3918. req.path = "/hi";
  3919. std::string host_and_port;
  3920. host_and_port += HOST;
  3921. host_and_port += ":";
  3922. host_and_port += std::to_string(PORT);
  3923. req.headers.emplace("Host", host_and_port.c_str());
  3924. req.headers.emplace("Accept", "*/*");
  3925. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3926. req.headers.emplace(
  3927. "Header-Name",
  3928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3956. "@@@@@@@@@@@@@@@@");
  3957. auto res = std::make_shared<Response>();
  3958. auto error = Error::Success;
  3959. auto ret = cli_.send(req, *res, error);
  3960. ASSERT_TRUE(ret);
  3961. EXPECT_EQ(StatusCode::OK_200, res->status);
  3962. }
  3963. TEST_F(ServerTest, LongQueryValue) {
  3964. auto start = std::chrono::high_resolution_clock::now();
  3965. cli_.set_keep_alive(true);
  3966. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3967. auto end = std::chrono::high_resolution_clock::now();
  3968. auto elapsed =
  3969. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3970. .count();
  3971. ASSERT_TRUE(res);
  3972. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3973. EXPECT_LE(elapsed, 1000);
  3974. EXPECT_EQ("close", res->get_header_value("Connection"));
  3975. EXPECT_FALSE(cli_.is_socket_open());
  3976. }
  3977. TEST_F(ServerTest, TooLongQueryValue) {
  3978. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3979. ASSERT_FALSE(res);
  3980. EXPECT_EQ(Error::Read, res.error());
  3981. }
  3982. TEST_F(ServerTest, TooLongHeader) {
  3983. Request req;
  3984. req.method = "GET";
  3985. req.path = "/hi";
  3986. std::string host_and_port;
  3987. host_and_port += HOST;
  3988. host_and_port += ":";
  3989. host_and_port += std::to_string(PORT);
  3990. req.headers.emplace("Host", host_and_port.c_str());
  3991. req.headers.emplace("Accept", "*/*");
  3992. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3993. req.headers.emplace(
  3994. "Header-Name",
  3995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4011. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4012. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4013. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4014. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4015. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4016. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4017. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4018. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4020. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4021. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4022. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4023. "@@@@@@@@@@@@@@@@@");
  4024. auto res = std::make_shared<Response>();
  4025. auto error = Error::Success;
  4026. auto ret = cli_.send(req, *res, error);
  4027. ASSERT_TRUE(ret);
  4028. EXPECT_EQ(StatusCode::OK_200, res->status);
  4029. }
  4030. TEST_F(ServerTest, HeaderCountAtLimit) {
  4031. // Test with headers just under the 100 limit
  4032. httplib::Headers headers;
  4033. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4034. // This should keep us just under the 100 header limit
  4035. for (int i = 0; i < 95; i++) {
  4036. std::string name = "X-Test-Header-" + std::to_string(i);
  4037. std::string value = "value" + std::to_string(i);
  4038. headers.emplace(name, value);
  4039. }
  4040. // This should work fine as we're under the limit
  4041. auto res = cli_.Get("/hi", headers);
  4042. EXPECT_TRUE(res);
  4043. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4044. }
  4045. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4046. // Test with many headers to exceed the 100 limit
  4047. httplib::Headers headers;
  4048. // Add 150 headers to definitely exceed the 100 limit
  4049. for (int i = 0; i < 150; i++) {
  4050. std::string name = "X-Test-Header-" + std::to_string(i);
  4051. std::string value = "value" + std::to_string(i);
  4052. headers.emplace(name, value);
  4053. }
  4054. // This should fail due to exceeding header count limit
  4055. cli_.set_keep_alive(true);
  4056. auto res = cli_.Get("/hi", headers);
  4057. // The server should respond with 400 Bad Request
  4058. ASSERT_TRUE(res);
  4059. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4060. EXPECT_EQ("close", res->get_header_value("Connection"));
  4061. EXPECT_FALSE(cli_.is_socket_open());
  4062. }
  4063. TEST_F(ServerTest, PercentEncoding) {
  4064. auto res = cli_.Get("/e%6edwith%");
  4065. ASSERT_TRUE(res);
  4066. EXPECT_EQ(StatusCode::OK_200, res->status);
  4067. }
  4068. TEST_F(ServerTest, PercentEncodingUnicode) {
  4069. auto res = cli_.Get("/e%u006edwith%");
  4070. ASSERT_TRUE(res);
  4071. EXPECT_EQ(StatusCode::OK_200, res->status);
  4072. }
  4073. TEST_F(ServerTest, InvalidPercentEncoding) {
  4074. auto res = cli_.Get("/%endwith%");
  4075. ASSERT_TRUE(res);
  4076. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4077. }
  4078. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4079. auto res = cli_.Get("/%uendwith%");
  4080. ASSERT_TRUE(res);
  4081. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4082. }
  4083. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4084. auto res = cli_.Get("/hello?aaa=bbb%");
  4085. ASSERT_TRUE(res);
  4086. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4087. }
  4088. TEST_F(ServerTest, PlusSignEncoding) {
  4089. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4090. ASSERT_TRUE(res);
  4091. EXPECT_EQ(StatusCode::OK_200, res->status);
  4092. EXPECT_EQ("a +b", res->body);
  4093. }
  4094. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4095. // This test simulates a potential DoS attack using many headers
  4096. // to verify our security fix prevents memory exhaustion
  4097. httplib::Headers attack_headers;
  4098. // Attempt to add many headers like an attacker would (200 headers to far
  4099. // exceed limit)
  4100. for (int i = 0; i < 200; i++) {
  4101. std::string name = "X-Attack-Header-" + std::to_string(i);
  4102. std::string value = "attack_payload_" + std::to_string(i);
  4103. attack_headers.emplace(name, value);
  4104. }
  4105. // Try to POST with excessive headers
  4106. cli_.set_keep_alive(true);
  4107. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4108. // Should either fail or return 400 Bad Request due to security limit
  4109. if (res) {
  4110. // If we get a response, it should be 400 Bad Request
  4111. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4112. EXPECT_EQ("close", res->get_header_value("Connection"));
  4113. }
  4114. EXPECT_FALSE(cli_.is_socket_open());
  4115. }
  4116. TEST_F(ServerTest, MultipartFormData) {
  4117. UploadFormDataItems items = {
  4118. {"text1", "text default", "", ""},
  4119. {"text2", "aωb", "", ""},
  4120. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4121. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4122. {"file3", "", "", "application/octet-stream"},
  4123. {"file4", "", "", " application/json tmp-string "}};
  4124. auto res = cli_.Post("/multipart", items);
  4125. ASSERT_TRUE(res);
  4126. EXPECT_EQ(StatusCode::OK_200, res->status);
  4127. }
  4128. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4129. UploadFormDataItems items = {
  4130. {"text", "default text", "", ""},
  4131. {"multi_text1", "aaaaa", "", ""},
  4132. {"multi_text1", "bbbbb", "", ""},
  4133. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4134. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4135. "application/json"},
  4136. };
  4137. auto res = cli_.Post("/multipart/multi_file_values", items);
  4138. ASSERT_TRUE(res);
  4139. EXPECT_EQ(StatusCode::OK_200, res->status);
  4140. }
  4141. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4142. auto res = cli_.Get("/hi");
  4143. ASSERT_TRUE(res);
  4144. EXPECT_EQ(StatusCode::OK_200, res->status);
  4145. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4146. EXPECT_EQ("Hello World!", res->body);
  4147. }
  4148. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4149. Request req;
  4150. req.method = "POST";
  4151. req.path = "/chunked";
  4152. std::string host_and_port;
  4153. host_and_port += HOST;
  4154. host_and_port += ":";
  4155. host_and_port += std::to_string(PORT);
  4156. req.headers.emplace("Host", host_and_port.c_str());
  4157. req.headers.emplace("Accept", "*/*");
  4158. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4159. req.headers.emplace("Content-Type", "text/plain");
  4160. req.headers.emplace("Content-Length", "0");
  4161. req.headers.emplace(
  4162. "Transfer-Encoding",
  4163. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4164. // Client does not chunk, so make a chunked body manually.
  4165. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4166. auto res = std::make_shared<Response>();
  4167. auto error = Error::Success;
  4168. auto ret = cli_.send(req, *res, error);
  4169. ASSERT_TRUE(ret);
  4170. EXPECT_EQ(StatusCode::OK_200, res->status);
  4171. }
  4172. TEST_F(ServerTest, GetStreamed2) {
  4173. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4174. ASSERT_TRUE(res);
  4175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4176. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4177. EXPECT_EQ(true, res->has_header("Content-Range"));
  4178. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4179. EXPECT_EQ(std::string("ab"), res->body);
  4180. }
  4181. TEST_F(ServerTest, GetStreamed) {
  4182. auto res = cli_.Get("/streamed");
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ(StatusCode::OK_200, res->status);
  4185. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4186. EXPECT_EQ(std::string("aaabbb"), res->body);
  4187. }
  4188. TEST_F(ServerTest, GetStreamedWithRange1) {
  4189. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4190. ASSERT_TRUE(res);
  4191. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4192. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4193. EXPECT_EQ(true, res->has_header("Content-Range"));
  4194. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4195. EXPECT_EQ(std::string("def"), res->body);
  4196. }
  4197. TEST_F(ServerTest, GetStreamedWithRange2) {
  4198. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4199. ASSERT_TRUE(res);
  4200. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4201. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4202. EXPECT_EQ(true, res->has_header("Content-Range"));
  4203. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4204. EXPECT_EQ(std::string("bcdefg"), res->body);
  4205. }
  4206. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4207. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4208. ASSERT_TRUE(res);
  4209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4210. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4211. EXPECT_EQ(true, res->has_header("Content-Range"));
  4212. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4213. EXPECT_EQ(std::string("efg"), res->body);
  4214. }
  4215. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4216. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4217. ASSERT_TRUE(res);
  4218. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4219. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4220. EXPECT_EQ(false, res->has_header("Content-Range"));
  4221. EXPECT_EQ(0U, res->body.size());
  4222. }
  4223. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4224. auto res = cli_.Get("/streamed-with-range",
  4225. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4226. "92233720368547758079223372036854775807"}});
  4227. ASSERT_TRUE(res);
  4228. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4229. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4230. EXPECT_EQ(false, res->has_header("Content-Range"));
  4231. EXPECT_EQ(0U, res->body.size());
  4232. }
  4233. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4234. auto res = cli_.Get(
  4235. "/with-range",
  4236. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4237. {"Accept-Encoding", ""}});
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4240. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4241. EXPECT_EQ(true, res->has_header("Content-Range"));
  4242. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4243. EXPECT_EQ(std::string("abcdefg"), res->body);
  4244. }
  4245. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4246. auto res = cli_.Get("/with-range", {
  4247. {"Range", "bytes=0-"},
  4248. {"Accept-Encoding", ""},
  4249. });
  4250. ASSERT_TRUE(res);
  4251. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4252. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4253. EXPECT_EQ(true, res->has_header("Content-Range"));
  4254. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4255. EXPECT_EQ(std::string("abcdefg"), res->body);
  4256. }
  4257. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4258. auto res =
  4259. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4262. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4263. EXPECT_EQ(false, res->has_header("Content-Range"));
  4264. EXPECT_EQ(267U, res->body.size());
  4265. // Check that both range contents are present
  4266. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4267. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4268. // Check that Content-Range headers are present for both ranges
  4269. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4270. std::string::npos);
  4271. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4272. std::string::npos);
  4273. }
  4274. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4275. Ranges ranges;
  4276. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4277. ranges.emplace_back(0, -1);
  4278. }
  4279. auto res =
  4280. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4281. ASSERT_TRUE(res);
  4282. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4283. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4284. EXPECT_EQ(false, res->has_header("Content-Range"));
  4285. EXPECT_EQ(0U, res->body.size());
  4286. }
  4287. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4288. auto res =
  4289. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4292. EXPECT_EQ(5U, res->body.size());
  4293. // Check that overlapping ranges are coalesced into a single range
  4294. EXPECT_EQ("bcdef", res->body);
  4295. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4296. // Should be single range, not multipart
  4297. EXPECT_TRUE(res->has_header("Content-Range"));
  4298. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4299. }
  4300. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4301. auto res =
  4302. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4305. EXPECT_EQ(268U, res->body.size());
  4306. // Check that both range contents are present
  4307. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4308. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4309. // Check that Content-Range headers are present for both ranges
  4310. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4311. std::string::npos);
  4312. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4313. std::string::npos);
  4314. }
  4315. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4316. auto res =
  4317. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4320. EXPECT_EQ(269U, res->body.size());
  4321. // Check that both duplicate range contents are present
  4322. size_t first_abc = res->body.find("abc\r\n");
  4323. EXPECT_TRUE(first_abc != std::string::npos);
  4324. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4325. EXPECT_TRUE(second_abc != std::string::npos);
  4326. // Check that Content-Range headers are present for both ranges
  4327. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4328. EXPECT_TRUE(first_range != std::string::npos);
  4329. size_t second_range =
  4330. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4331. EXPECT_TRUE(second_range != std::string::npos);
  4332. }
  4333. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4334. auto res = cli_.Get("/streamed-with-range?error",
  4335. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4336. ASSERT_TRUE(res);
  4337. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4338. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4339. EXPECT_EQ(false, res->has_header("Content-Range"));
  4340. EXPECT_EQ(0U, res->body.size());
  4341. }
  4342. TEST_F(ServerTest, GetStreamedEndless) {
  4343. uint64_t offset = 0;
  4344. auto res = cli_.Get("/streamed-cancel",
  4345. [&](const char * /*data*/, uint64_t data_length) {
  4346. if (offset < 100) {
  4347. offset += data_length;
  4348. return true;
  4349. }
  4350. return false;
  4351. });
  4352. ASSERT_TRUE(!res);
  4353. EXPECT_EQ(Error::Canceled, res.error());
  4354. }
  4355. TEST_F(ServerTest, ClientStop) {
  4356. std::atomic_size_t count{4};
  4357. std::vector<std::thread> threads;
  4358. for (auto i = count.load(); i != 0; --i) {
  4359. threads.emplace_back([&]() {
  4360. auto res = cli_.Get("/streamed-cancel",
  4361. [&](const char *, uint64_t) { return true; });
  4362. --count;
  4363. ASSERT_TRUE(!res);
  4364. EXPECT_TRUE(res.error() == Error::Canceled ||
  4365. res.error() == Error::Read || res.error() == Error::Write);
  4366. });
  4367. }
  4368. std::this_thread::sleep_for(std::chrono::seconds(2));
  4369. while (count != 0) {
  4370. cli_.stop();
  4371. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4372. }
  4373. for (auto &t : threads) {
  4374. t.join();
  4375. }
  4376. }
  4377. TEST_F(ServerTest, GetWithRange1) {
  4378. auto res = cli_.Get("/with-range", {
  4379. make_range_header({{3, 5}}),
  4380. {"Accept-Encoding", ""},
  4381. });
  4382. ASSERT_TRUE(res);
  4383. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4384. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4385. EXPECT_EQ(true, res->has_header("Content-Range"));
  4386. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4387. EXPECT_EQ(std::string("def"), res->body);
  4388. }
  4389. TEST_F(ServerTest, GetWithRange2) {
  4390. auto res = cli_.Get("/with-range", {
  4391. make_range_header({{1, -1}}),
  4392. {"Accept-Encoding", ""},
  4393. });
  4394. ASSERT_TRUE(res);
  4395. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4396. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4397. EXPECT_EQ(true, res->has_header("Content-Range"));
  4398. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4399. EXPECT_EQ(std::string("bcdefg"), res->body);
  4400. }
  4401. TEST_F(ServerTest, GetWithRange3) {
  4402. auto res = cli_.Get("/with-range", {
  4403. make_range_header({{0, 0}}),
  4404. {"Accept-Encoding", ""},
  4405. });
  4406. ASSERT_TRUE(res);
  4407. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4408. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4409. EXPECT_EQ(true, res->has_header("Content-Range"));
  4410. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4411. EXPECT_EQ(std::string("a"), res->body);
  4412. }
  4413. TEST_F(ServerTest, GetWithRange4) {
  4414. auto res = cli_.Get("/with-range", {
  4415. make_range_header({{-1, 2}}),
  4416. {"Accept-Encoding", ""},
  4417. });
  4418. ASSERT_TRUE(res);
  4419. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4420. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4421. EXPECT_EQ(true, res->has_header("Content-Range"));
  4422. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4423. EXPECT_EQ(std::string("fg"), res->body);
  4424. }
  4425. TEST_F(ServerTest, GetWithRange5) {
  4426. auto res = cli_.Get("/with-range", {
  4427. make_range_header({{0, 5}}),
  4428. {"Accept-Encoding", ""},
  4429. });
  4430. ASSERT_TRUE(res);
  4431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4432. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4433. EXPECT_EQ(true, res->has_header("Content-Range"));
  4434. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4435. EXPECT_EQ(std::string("abcdef"), res->body);
  4436. }
  4437. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4438. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4439. ASSERT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4441. }
  4442. TEST_F(ServerTest, GetWithRangeMultipart) {
  4443. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4444. ASSERT_TRUE(res);
  4445. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4446. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4447. EXPECT_EQ(false, res->has_header("Content-Range"));
  4448. EXPECT_EQ(267U, res->body.size());
  4449. }
  4450. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4451. auto res =
  4452. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4453. ASSERT_TRUE(res);
  4454. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4455. }
  4456. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4457. auto res = cli_.Get("/with-range-customized-response",
  4458. {{make_range_header({{1, 2}})}});
  4459. ASSERT_TRUE(res);
  4460. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4461. EXPECT_EQ(true, res->has_header("Content-Length"));
  4462. EXPECT_EQ(false, res->has_header("Content-Range"));
  4463. EXPECT_EQ(JSON_DATA, res->body);
  4464. }
  4465. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4466. auto res = cli_.Get("/with-range-customized-response",
  4467. {{make_range_header({{1, 2}, {4, 5}})}});
  4468. ASSERT_TRUE(res);
  4469. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4470. EXPECT_EQ(true, res->has_header("Content-Length"));
  4471. EXPECT_EQ(false, res->has_header("Content-Range"));
  4472. EXPECT_EQ(JSON_DATA, res->body);
  4473. }
  4474. TEST_F(ServerTest, Issue1772) {
  4475. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4476. ASSERT_TRUE(res);
  4477. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4478. }
  4479. TEST_F(ServerTest, Issue609) {
  4480. auto res = cli_.Delete("/issue609");
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. EXPECT_EQ(std::string("ok"), res->body);
  4484. }
  4485. TEST_F(ServerTest, GetStreamedChunked) {
  4486. auto res = cli_.Get("/streamed-chunked");
  4487. ASSERT_TRUE(res);
  4488. EXPECT_EQ(StatusCode::OK_200, res->status);
  4489. EXPECT_EQ(std::string("123456789"), res->body);
  4490. }
  4491. TEST_F(ServerTest, GetStreamedChunked2) {
  4492. auto res = cli_.Get("/streamed-chunked2");
  4493. ASSERT_TRUE(res);
  4494. EXPECT_EQ(StatusCode::OK_200, res->status);
  4495. EXPECT_EQ(std::string("123456789"), res->body);
  4496. }
  4497. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4498. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4499. ASSERT_TRUE(res);
  4500. EXPECT_EQ(StatusCode::OK_200, res->status);
  4501. EXPECT_EQ(std::string("123456789"), res->body);
  4502. EXPECT_TRUE(res->has_header("Trailer"));
  4503. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4504. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4505. // Trailers are now stored separately from headers (security fix)
  4506. EXPECT_EQ(2U, res->trailers.size());
  4507. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4508. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4509. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4510. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4511. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4512. // Verify trailers are NOT in headers (security verification)
  4513. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4514. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4515. }
  4516. TEST_F(ServerTest, LargeChunkedPost) {
  4517. Request req;
  4518. req.method = "POST";
  4519. req.path = "/large-chunked";
  4520. std::string host_and_port;
  4521. host_and_port += HOST;
  4522. host_and_port += ":";
  4523. host_and_port += std::to_string(PORT);
  4524. req.headers.emplace("Host", host_and_port.c_str());
  4525. req.headers.emplace("Accept", "*/*");
  4526. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4527. req.headers.emplace("Content-Type", "text/plain");
  4528. req.headers.emplace("Content-Length", "0");
  4529. req.headers.emplace("Transfer-Encoding", "chunked");
  4530. std::string long_string(30 * 1024u, 'a');
  4531. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4532. // Attempt to make a large enough post to exceed OS buffers, to test that
  4533. // the server handles short reads if the full chunk data isn't available.
  4534. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4535. auto res = std::make_shared<Response>();
  4536. auto error = Error::Success;
  4537. auto ret = cli_.send(req, *res, error);
  4538. ASSERT_TRUE(ret);
  4539. EXPECT_EQ(StatusCode::OK_200, res->status);
  4540. }
  4541. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4542. auto res = cli_.Get("/remote_addr");
  4543. ASSERT_TRUE(res);
  4544. EXPECT_EQ(StatusCode::OK_200, res->status);
  4545. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4546. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4547. }
  4548. TEST_F(ServerTest, GetMethodLocalAddr) {
  4549. auto res = cli_.Get("/local_addr");
  4550. ASSERT_TRUE(res);
  4551. EXPECT_EQ(StatusCode::OK_200, res->status);
  4552. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4553. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4554. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4555. }
  4556. TEST_F(ServerTest, HTTPResponseSplitting) {
  4557. auto res = cli_.Get("/http_response_splitting");
  4558. ASSERT_TRUE(res);
  4559. EXPECT_EQ(StatusCode::OK_200, res->status);
  4560. }
  4561. TEST_F(ServerTest, SlowRequest) {
  4562. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4563. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4564. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4565. }
  4566. #if 0
  4567. TEST_F(ServerTest, SlowPost) {
  4568. char buffer[64 * 1024];
  4569. memset(buffer, 0x42, sizeof(buffer));
  4570. auto res = cli_.Post(
  4571. "/slowpost", 64 * 1024 * 1024,
  4572. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4573. auto ret = sink.write(buffer, sizeof(buffer));
  4574. EXPECT_TRUE(ret);
  4575. return true;
  4576. },
  4577. "text/plain");
  4578. ASSERT_TRUE(res);
  4579. EXPECT_EQ(StatusCode::OK_200, res->status);
  4580. }
  4581. TEST_F(ServerTest, SlowPostFail) {
  4582. char buffer[64 * 1024];
  4583. memset(buffer, 0x42, sizeof(buffer));
  4584. cli_.set_write_timeout(std::chrono::seconds(0));
  4585. auto res = cli_.Post(
  4586. "/slowpost", 64 * 1024 * 1024,
  4587. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4588. sink.write(buffer, sizeof(buffer));
  4589. return true;
  4590. },
  4591. "text/plain");
  4592. ASSERT_TRUE(!res);
  4593. EXPECT_EQ(Error::Write, res.error());
  4594. }
  4595. #endif
  4596. TEST_F(ServerTest, Put) {
  4597. auto res = cli_.Put("/put", "PUT", "text/plain");
  4598. ASSERT_TRUE(res);
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. EXPECT_EQ("PUT", res->body);
  4601. }
  4602. TEST_F(ServerTest, PutWithContentProvider) {
  4603. auto res = cli_.Put(
  4604. "/put", 3,
  4605. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4606. sink.os << "PUT";
  4607. return true;
  4608. },
  4609. "text/plain");
  4610. ASSERT_TRUE(res);
  4611. EXPECT_EQ(StatusCode::OK_200, res->status);
  4612. EXPECT_EQ("PUT", res->body);
  4613. }
  4614. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4615. auto res = cli_.Post(
  4616. "/post", 42,
  4617. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4618. return false;
  4619. },
  4620. "text/plain");
  4621. ASSERT_TRUE(!res);
  4622. EXPECT_EQ(Error::Canceled, res.error());
  4623. }
  4624. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4625. auto res = cli_.Put(
  4626. "/put",
  4627. [](size_t /*offset*/, DataSink &sink) {
  4628. sink.os << "PUT";
  4629. sink.done();
  4630. return true;
  4631. },
  4632. "text/plain");
  4633. ASSERT_TRUE(res);
  4634. EXPECT_EQ(StatusCode::OK_200, res->status);
  4635. EXPECT_EQ("PUT", res->body);
  4636. }
  4637. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4638. auto res = cli_.Post(
  4639. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4640. "text/plain");
  4641. ASSERT_TRUE(!res);
  4642. EXPECT_EQ(Error::Canceled, res.error());
  4643. }
  4644. TEST_F(ServerTest, PostLoopBack) {
  4645. std::string body;
  4646. auto res = cli_.Post(
  4647. "/post-loopback", 9,
  4648. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4649. EXPECT_EQ(9u, length);
  4650. sink.write("123", 3);
  4651. sink.write("456", 3);
  4652. sink.write("789", 3);
  4653. return true;
  4654. },
  4655. "text/plain",
  4656. [&body](const char *data, size_t data_length) {
  4657. body.append(data, data_length);
  4658. return true;
  4659. });
  4660. ASSERT_TRUE(res);
  4661. EXPECT_EQ(StatusCode::OK_200, res->status);
  4662. EXPECT_EQ("123456789", body);
  4663. }
  4664. TEST_F(ServerTest, PutLoopBack) {
  4665. std::string body;
  4666. auto res = cli_.Put(
  4667. "/put-loopback", 9,
  4668. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4669. EXPECT_EQ(9u, length);
  4670. sink.write("123", 3);
  4671. sink.write("456", 3);
  4672. sink.write("789", 3);
  4673. return true;
  4674. },
  4675. "text/plain",
  4676. [&body](const char *data, size_t data_length) {
  4677. body.append(data, data_length);
  4678. return true;
  4679. });
  4680. ASSERT_TRUE(res);
  4681. EXPECT_EQ(StatusCode::OK_200, res->status);
  4682. EXPECT_EQ("123456789", body);
  4683. }
  4684. TEST_F(ServerTest, PatchLoopBack) {
  4685. std::string body;
  4686. auto res = cli_.Patch(
  4687. "/patch-loopback", 9,
  4688. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4689. EXPECT_EQ(9u, length);
  4690. sink.write("123", 3);
  4691. sink.write("456", 3);
  4692. sink.write("789", 3);
  4693. return true;
  4694. },
  4695. "text/plain",
  4696. [&body](const char *data, size_t data_length) {
  4697. body.append(data, data_length);
  4698. return true;
  4699. });
  4700. ASSERT_TRUE(res);
  4701. EXPECT_EQ(StatusCode::OK_200, res->status);
  4702. EXPECT_EQ("123456789", body);
  4703. }
  4704. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4705. std::string body;
  4706. auto res = cli_.Post(
  4707. "/post-loopback",
  4708. [](size_t /*offset*/, DataSink &sink) {
  4709. sink.write("123", 3);
  4710. sink.write("456", 3);
  4711. sink.write("789", 3);
  4712. sink.done();
  4713. return true;
  4714. },
  4715. "text/plain",
  4716. [&body](const char *data, size_t data_length) {
  4717. body.append(data, data_length);
  4718. return true;
  4719. });
  4720. ASSERT_TRUE(res);
  4721. EXPECT_EQ(StatusCode::OK_200, res->status);
  4722. EXPECT_EQ("123456789", body);
  4723. }
  4724. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4725. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4726. cli_.set_compress(true);
  4727. auto res = cli_.Put(
  4728. "/put", 3,
  4729. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4730. sink.os << "PUT";
  4731. return true;
  4732. },
  4733. "text/plain");
  4734. ASSERT_TRUE(res);
  4735. EXPECT_EQ(StatusCode::OK_200, res->status);
  4736. EXPECT_EQ("PUT", res->body);
  4737. }
  4738. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4739. cli_.set_compress(true);
  4740. auto res = cli_.Post(
  4741. "/post", 42,
  4742. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4743. return false;
  4744. },
  4745. "text/plain");
  4746. ASSERT_TRUE(!res);
  4747. EXPECT_EQ(Error::Canceled, res.error());
  4748. }
  4749. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4750. cli_.set_compress(true);
  4751. auto res = cli_.Put(
  4752. "/put",
  4753. [](size_t /*offset*/, DataSink &sink) {
  4754. sink.os << "PUT";
  4755. sink.done();
  4756. return true;
  4757. },
  4758. "text/plain");
  4759. ASSERT_TRUE(res);
  4760. EXPECT_EQ(StatusCode::OK_200, res->status);
  4761. EXPECT_EQ("PUT", res->body);
  4762. }
  4763. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4764. cli_.set_compress(true);
  4765. auto res = cli_.Post(
  4766. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4767. "text/plain");
  4768. ASSERT_TRUE(!res);
  4769. EXPECT_EQ(Error::Canceled, res.error());
  4770. }
  4771. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4772. cli_.set_compress(true);
  4773. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4774. ASSERT_TRUE(res);
  4775. EXPECT_EQ(StatusCode::OK_200, res->status);
  4776. EXPECT_EQ(LARGE_DATA, res->body);
  4777. }
  4778. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4779. #ifdef CPPHTTPLIB_SSL_ENABLED
  4780. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4781. Client cli(s.c_str());
  4782. cli.enable_server_certificate_verification(false);
  4783. #else
  4784. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4785. Client cli(s.c_str());
  4786. #endif
  4787. cli.set_compress(true);
  4788. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4789. ASSERT_TRUE(res);
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ(LARGE_DATA, res->body);
  4792. // The compressed size should be less than a 10th of the original. May vary
  4793. // depending on the zlib library.
  4794. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4795. static_cast<uint64_t>(10 * 1024 * 1024));
  4796. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4797. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4798. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4799. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4800. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4801. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4802. #endif
  4803. }
  4804. TEST_F(ServerTest, PutContentWithDeflate) {
  4805. cli_.set_compress(false);
  4806. Headers headers;
  4807. headers.emplace("Content-Encoding", "deflate");
  4808. // PUT in deflate format:
  4809. auto res = cli_.Put("/put", headers,
  4810. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4811. ASSERT_TRUE(res);
  4812. EXPECT_EQ(StatusCode::OK_200, res->status);
  4813. EXPECT_EQ("PUT", res->body);
  4814. }
  4815. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4816. Headers headers;
  4817. headers.emplace("Accept-Encoding", "gzip, deflate");
  4818. auto res = cli_.Get("/streamed-chunked", headers);
  4819. ASSERT_TRUE(res);
  4820. EXPECT_EQ(StatusCode::OK_200, res->status);
  4821. EXPECT_EQ(std::string("123456789"), res->body);
  4822. }
  4823. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4824. Headers headers;
  4825. headers.emplace("Accept-Encoding", "gzip, deflate");
  4826. auto res = cli_.Get("/streamed-chunked2", headers);
  4827. ASSERT_TRUE(res);
  4828. EXPECT_EQ(StatusCode::OK_200, res->status);
  4829. EXPECT_EQ(std::string("123456789"), res->body);
  4830. }
  4831. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4832. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4833. ASSERT_TRUE(res);
  4834. EXPECT_EQ(StatusCode::OK_200, res->status);
  4835. }
  4836. TEST(GzipDecompressor, ChunkedDecompression) {
  4837. std::string data;
  4838. for (size_t i = 0; i < 32 * 1024; ++i) {
  4839. data.push_back(static_cast<char>('a' + i % 26));
  4840. }
  4841. std::string compressed_data;
  4842. {
  4843. httplib::detail::gzip_compressor compressor;
  4844. bool result = compressor.compress(
  4845. data.data(), data.size(),
  4846. /*last=*/true,
  4847. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4848. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4849. compressed_data_size);
  4850. return true;
  4851. });
  4852. ASSERT_TRUE(result);
  4853. }
  4854. std::string decompressed_data;
  4855. {
  4856. httplib::detail::gzip_decompressor decompressor;
  4857. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4858. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4859. size_t chunk_size = 130;
  4860. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4861. chunk_begin += chunk_size) {
  4862. size_t current_chunk_size =
  4863. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4864. bool result = decompressor.decompress(
  4865. compressed_data.data() + chunk_begin, current_chunk_size,
  4866. [&](const char *decompressed_data_chunk,
  4867. size_t decompressed_data_chunk_size) {
  4868. decompressed_data.insert(decompressed_data.size(),
  4869. decompressed_data_chunk,
  4870. decompressed_data_chunk_size);
  4871. return true;
  4872. });
  4873. ASSERT_TRUE(result);
  4874. }
  4875. }
  4876. ASSERT_EQ(data, decompressed_data);
  4877. }
  4878. TEST(GzipDecompressor, DeflateDecompression) {
  4879. std::string original_text = "Raw deflate without gzip";
  4880. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4881. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4882. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4883. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4884. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4885. std::string decompressed_data;
  4886. {
  4887. httplib::detail::gzip_decompressor decompressor;
  4888. bool result = decompressor.decompress(
  4889. compressed_data.data(), compressed_data.size(),
  4890. [&](const char *decompressed_data_chunk,
  4891. size_t decompressed_data_chunk_size) {
  4892. decompressed_data.insert(decompressed_data.size(),
  4893. decompressed_data_chunk,
  4894. decompressed_data_chunk_size);
  4895. return true;
  4896. });
  4897. ASSERT_TRUE(result);
  4898. }
  4899. ASSERT_EQ(original_text, decompressed_data);
  4900. }
  4901. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4902. std::string original_text = "Raw deflate without gzip";
  4903. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4904. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4905. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4906. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4907. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4908. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4909. std::string decompressed_data;
  4910. {
  4911. httplib::detail::gzip_decompressor decompressor;
  4912. bool result = decompressor.decompress(
  4913. compressed_data.data(), compressed_data.size(),
  4914. [&](const char *decompressed_data_chunk,
  4915. size_t decompressed_data_chunk_size) {
  4916. decompressed_data.insert(decompressed_data.size(),
  4917. decompressed_data_chunk,
  4918. decompressed_data_chunk_size);
  4919. return true;
  4920. });
  4921. ASSERT_TRUE(result);
  4922. }
  4923. ASSERT_EQ(original_text, decompressed_data);
  4924. }
  4925. #endif
  4926. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4927. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4928. Headers headers;
  4929. headers.emplace("Accept-Encoding", "br");
  4930. auto res = cli_.Get("/streamed-chunked", headers);
  4931. ASSERT_TRUE(res);
  4932. EXPECT_EQ(StatusCode::OK_200, res->status);
  4933. EXPECT_EQ(std::string("123456789"), res->body);
  4934. }
  4935. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4936. Headers headers;
  4937. headers.emplace("Accept-Encoding", "br");
  4938. auto res = cli_.Get("/streamed-chunked2", headers);
  4939. ASSERT_TRUE(res);
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. EXPECT_EQ(std::string("123456789"), res->body);
  4942. }
  4943. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4944. cli_.set_compress(true);
  4945. auto res = cli_.Put(
  4946. "/put", 3,
  4947. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4948. sink.os << "PUT";
  4949. return true;
  4950. },
  4951. "text/plain");
  4952. ASSERT_TRUE(res);
  4953. EXPECT_EQ(StatusCode::OK_200, res->status);
  4954. EXPECT_EQ("PUT", res->body);
  4955. }
  4956. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4957. cli_.set_compress(true);
  4958. auto res = cli_.Put(
  4959. "/put",
  4960. [](size_t /*offset*/, DataSink &sink) {
  4961. sink.os << "PUT";
  4962. sink.done();
  4963. return true;
  4964. },
  4965. "text/plain");
  4966. ASSERT_TRUE(res);
  4967. EXPECT_EQ(StatusCode::OK_200, res->status);
  4968. EXPECT_EQ("PUT", res->body);
  4969. }
  4970. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  4971. cli_.set_compress(true);
  4972. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4973. ASSERT_TRUE(res);
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. EXPECT_EQ(LARGE_DATA, res->body);
  4976. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4977. }
  4978. #endif
  4979. TEST_F(ServerTest, Patch) {
  4980. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4981. ASSERT_TRUE(res);
  4982. EXPECT_EQ(StatusCode::OK_200, res->status);
  4983. EXPECT_EQ("PATCH", res->body);
  4984. }
  4985. TEST_F(ServerTest, Delete) {
  4986. auto res = cli_.Delete("/delete");
  4987. ASSERT_TRUE(res);
  4988. EXPECT_EQ(StatusCode::OK_200, res->status);
  4989. EXPECT_EQ("DELETE", res->body);
  4990. }
  4991. TEST_F(ServerTest, DeleteContentReceiver) {
  4992. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4993. ASSERT_TRUE(res);
  4994. EXPECT_EQ(StatusCode::OK_200, res->status);
  4995. EXPECT_EQ("content", res->body);
  4996. }
  4997. TEST_F(ServerTest, Options) {
  4998. auto res = cli_.Options("*");
  4999. ASSERT_TRUE(res);
  5000. EXPECT_EQ(StatusCode::OK_200, res->status);
  5001. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5002. EXPECT_TRUE(res->body.empty());
  5003. }
  5004. TEST_F(ServerTest, URL) {
  5005. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5006. ASSERT_TRUE(res);
  5007. EXPECT_EQ(StatusCode::OK_200, res->status);
  5008. }
  5009. TEST_F(ServerTest, ArrayParam) {
  5010. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5011. ASSERT_TRUE(res);
  5012. EXPECT_EQ(StatusCode::OK_200, res->status);
  5013. }
  5014. TEST_F(ServerTest, NoMultipleHeaders) {
  5015. Headers headers = {{"Content-Length", "5"}};
  5016. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5017. "text/plain");
  5018. ASSERT_TRUE(res);
  5019. EXPECT_EQ(StatusCode::OK_200, res->status);
  5020. }
  5021. TEST_F(ServerTest, PostContentReceiver) {
  5022. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5023. ASSERT_TRUE(res);
  5024. ASSERT_EQ(StatusCode::OK_200, res->status);
  5025. ASSERT_EQ("content", res->body);
  5026. }
  5027. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5028. UploadFormDataItems items = {
  5029. {"text1", "text default", "", ""},
  5030. {"text2", "aωb", "", ""},
  5031. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5032. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5033. {"file3", "", "", "application/octet-stream"},
  5034. };
  5035. auto res = cli_.Post("/content_receiver", items);
  5036. ASSERT_TRUE(res);
  5037. EXPECT_EQ(StatusCode::OK_200, res->status);
  5038. }
  5039. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5040. UploadFormDataItems items = {
  5041. {"text1", "text default", "", ""},
  5042. {"text2", "aωb", "", ""},
  5043. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5044. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5045. {"file3", "", "", "application/octet-stream"},
  5046. };
  5047. auto boundary = std::string("+++++");
  5048. std::string body;
  5049. for (const auto &item : items) {
  5050. body += "--" + boundary + "\r\n";
  5051. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5052. if (!item.filename.empty()) {
  5053. body += "; filename=\"" + item.filename + "\"";
  5054. }
  5055. body += "\r\n";
  5056. if (!item.content_type.empty()) {
  5057. body += "Content-Type: " + item.content_type + "\r\n";
  5058. }
  5059. body += "\r\n";
  5060. body += item.content + "\r\n";
  5061. }
  5062. body += "--" + boundary + "--\r\n";
  5063. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5064. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5065. ASSERT_TRUE(res);
  5066. EXPECT_EQ(StatusCode::OK_200, res->status);
  5067. }
  5068. TEST_F(ServerTest, PostContentReceiverGzip) {
  5069. cli_.set_compress(true);
  5070. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5071. ASSERT_TRUE(res);
  5072. ASSERT_EQ(StatusCode::OK_200, res->status);
  5073. ASSERT_EQ("content", res->body);
  5074. }
  5075. TEST_F(ServerTest, PutContentReceiver) {
  5076. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5077. ASSERT_TRUE(res);
  5078. ASSERT_EQ(StatusCode::OK_200, res->status);
  5079. ASSERT_EQ("content", res->body);
  5080. }
  5081. TEST_F(ServerTest, PatchContentReceiver) {
  5082. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5083. ASSERT_TRUE(res);
  5084. ASSERT_EQ(StatusCode::OK_200, res->status);
  5085. ASSERT_EQ("content", res->body);
  5086. }
  5087. template <typename ClientType>
  5088. void TestWithHeadersAndContentReceiver(
  5089. ClientType &cli,
  5090. std::function<Result(ClientType &, const std::string &, const Headers &,
  5091. const std::string &, const std::string &,
  5092. ContentReceiver, DownloadProgress)>
  5093. request_func) {
  5094. Headers headers;
  5095. headers.emplace("X-Custom-Header", "test-value");
  5096. std::string received_body;
  5097. auto res = request_func(
  5098. cli, "/content_receiver", headers, "content", "application/json",
  5099. [&](const char *data, size_t data_length) {
  5100. received_body.append(data, data_length);
  5101. return true;
  5102. },
  5103. nullptr);
  5104. ASSERT_TRUE(res);
  5105. EXPECT_EQ(StatusCode::OK_200, res->status);
  5106. EXPECT_EQ("content", received_body);
  5107. }
  5108. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5109. #ifdef CPPHTTPLIB_SSL_ENABLED
  5110. using ClientT = SSLClient;
  5111. #else
  5112. using ClientT = Client;
  5113. #endif
  5114. TestWithHeadersAndContentReceiver<ClientT>(
  5115. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5116. const std::string &body, const std::string &content_type,
  5117. ContentReceiver receiver, DownloadProgress progress) {
  5118. return cli.Post(path, headers, body, content_type, receiver, progress);
  5119. });
  5120. }
  5121. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5122. #ifdef CPPHTTPLIB_SSL_ENABLED
  5123. using ClientT = SSLClient;
  5124. #else
  5125. using ClientT = Client;
  5126. #endif
  5127. TestWithHeadersAndContentReceiver<ClientT>(
  5128. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5129. const std::string &body, const std::string &content_type,
  5130. ContentReceiver receiver, DownloadProgress progress) {
  5131. return cli.Put(path, headers, body, content_type, receiver, progress);
  5132. });
  5133. }
  5134. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5135. #ifdef CPPHTTPLIB_SSL_ENABLED
  5136. using ClientT = SSLClient;
  5137. #else
  5138. using ClientT = Client;
  5139. #endif
  5140. TestWithHeadersAndContentReceiver<ClientT>(
  5141. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5142. const std::string &body, const std::string &content_type,
  5143. ContentReceiver receiver, DownloadProgress progress) {
  5144. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5145. });
  5146. }
  5147. template <typename ClientType>
  5148. void TestWithHeadersAndContentReceiverWithProgress(
  5149. ClientType &cli,
  5150. std::function<Result(ClientType &, const std::string &, const Headers &,
  5151. const std::string &, const std::string &,
  5152. ContentReceiver, DownloadProgress)>
  5153. request_func) {
  5154. Headers headers;
  5155. headers.emplace("X-Test-Header", "progress-test");
  5156. std::string received_body;
  5157. auto progress_called = false;
  5158. auto res = request_func(
  5159. cli, "/content_receiver", headers, "content", "text/plain",
  5160. [&](const char *data, size_t data_length) {
  5161. received_body.append(data, data_length);
  5162. return true;
  5163. },
  5164. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5165. progress_called = true;
  5166. return true;
  5167. });
  5168. ASSERT_TRUE(res);
  5169. EXPECT_EQ(StatusCode::OK_200, res->status);
  5170. EXPECT_EQ("content", received_body);
  5171. EXPECT_TRUE(progress_called);
  5172. }
  5173. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5174. #ifdef CPPHTTPLIB_SSL_ENABLED
  5175. using ClientT = SSLClient;
  5176. #else
  5177. using ClientT = Client;
  5178. #endif
  5179. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5180. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5181. const std::string &body, const std::string &content_type,
  5182. ContentReceiver receiver, DownloadProgress progress) {
  5183. return cli.Post(path, headers, body, content_type, receiver, progress);
  5184. });
  5185. }
  5186. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5187. #ifdef CPPHTTPLIB_SSL_ENABLED
  5188. using ClientT = SSLClient;
  5189. #else
  5190. using ClientT = Client;
  5191. #endif
  5192. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5193. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5194. const std::string &body, const std::string &content_type,
  5195. ContentReceiver receiver, DownloadProgress progress) {
  5196. return cli.Put(path, headers, body, content_type, receiver, progress);
  5197. });
  5198. }
  5199. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5200. #ifdef CPPHTTPLIB_SSL_ENABLED
  5201. using ClientT = SSLClient;
  5202. #else
  5203. using ClientT = Client;
  5204. #endif
  5205. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5206. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5207. const std::string &body, const std::string &content_type,
  5208. ContentReceiver receiver, DownloadProgress progress) {
  5209. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5210. });
  5211. }
  5212. template <typename ClientType>
  5213. void TestWithHeadersAndContentReceiverError(
  5214. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5215. const Headers &, const std::string &,
  5216. const std::string &, ContentReceiver)>
  5217. request_func) {
  5218. Headers headers;
  5219. headers.emplace("X-Error-Test", "true");
  5220. std::string received_body;
  5221. auto receiver_failed = false;
  5222. auto res =
  5223. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5224. [&](const char *data, size_t data_length) {
  5225. received_body.append(data, data_length);
  5226. receiver_failed = true;
  5227. return false;
  5228. });
  5229. ASSERT_FALSE(res);
  5230. EXPECT_TRUE(receiver_failed);
  5231. }
  5232. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5233. #ifdef CPPHTTPLIB_SSL_ENABLED
  5234. using ClientT = SSLClient;
  5235. #else
  5236. using ClientT = Client;
  5237. #endif
  5238. TestWithHeadersAndContentReceiverError<ClientT>(
  5239. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5240. const std::string &body, const std::string &content_type,
  5241. ContentReceiver receiver) {
  5242. return cli.Post(path, headers, body, content_type, receiver);
  5243. });
  5244. }
  5245. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5246. #ifdef CPPHTTPLIB_SSL_ENABLED
  5247. using ClientT = SSLClient;
  5248. #else
  5249. using ClientT = Client;
  5250. #endif
  5251. TestWithHeadersAndContentReceiverError<ClientT>(
  5252. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5253. const std::string &body, const std::string &content_type,
  5254. ContentReceiver receiver) {
  5255. return cli.Put(path, headers, body, content_type, receiver);
  5256. });
  5257. }
  5258. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5259. #ifdef CPPHTTPLIB_SSL_ENABLED
  5260. using ClientT = SSLClient;
  5261. #else
  5262. using ClientT = Client;
  5263. #endif
  5264. TestWithHeadersAndContentReceiverError<ClientT>(
  5265. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5266. const std::string &body, const std::string &content_type,
  5267. ContentReceiver receiver) {
  5268. return cli.Patch(path, headers, body, content_type, receiver);
  5269. });
  5270. }
  5271. TEST_F(ServerTest, PostQueryStringAndBody) {
  5272. auto res =
  5273. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5274. ASSERT_TRUE(res);
  5275. ASSERT_EQ(StatusCode::OK_200, res->status);
  5276. }
  5277. TEST_F(ServerTest, HTTP2Magic) {
  5278. Request req;
  5279. req.method = "PRI";
  5280. req.path = "*";
  5281. req.body = "SM";
  5282. auto res = std::make_shared<Response>();
  5283. auto error = Error::Success;
  5284. auto ret = cli_.send(req, *res, error);
  5285. ASSERT_TRUE(ret);
  5286. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5287. }
  5288. TEST_F(ServerTest, KeepAlive) {
  5289. auto res = cli_.Get("/hi");
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5293. EXPECT_EQ("Hello World!", res->body);
  5294. res = cli_.Get("/hi");
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5298. EXPECT_EQ("Hello World!", res->body);
  5299. res = cli_.Get("/hi");
  5300. ASSERT_TRUE(res);
  5301. EXPECT_EQ(StatusCode::OK_200, res->status);
  5302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5303. EXPECT_EQ("Hello World!", res->body);
  5304. res = cli_.Get("/not-exist");
  5305. ASSERT_TRUE(res);
  5306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5307. res = cli_.Post("/empty", "", "text/plain");
  5308. ASSERT_TRUE(res);
  5309. EXPECT_EQ(StatusCode::OK_200, res->status);
  5310. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5311. EXPECT_EQ("empty", res->body);
  5312. EXPECT_EQ("close", res->get_header_value("Connection"));
  5313. res = cli_.Post(
  5314. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5315. "text/plain");
  5316. ASSERT_TRUE(res);
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5319. EXPECT_EQ("empty", res->body);
  5320. cli_.set_keep_alive(false);
  5321. res = cli_.Get("/last-request");
  5322. ASSERT_TRUE(res);
  5323. EXPECT_EQ(StatusCode::OK_200, res->status);
  5324. EXPECT_EQ("close", res->get_header_value("Connection"));
  5325. }
  5326. TEST_F(ServerTest, TooManyRedirect) {
  5327. cli_.set_follow_location(true);
  5328. auto res = cli_.Get("/redirect/0");
  5329. ASSERT_TRUE(!res);
  5330. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5331. }
  5332. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5333. Request req;
  5334. req.method = "FOOBAR";
  5335. req.path = "/hi";
  5336. cli_.set_keep_alive(true);
  5337. auto res = cli_.send(req);
  5338. ASSERT_TRUE(res);
  5339. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5340. EXPECT_EQ("close", res->get_header_value("Connection"));
  5341. EXPECT_FALSE(cli_.is_socket_open());
  5342. }
  5343. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5344. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5345. TEST_F(ServerTest, Gzip) {
  5346. Headers headers;
  5347. headers.emplace("Accept-Encoding", "gzip, deflate");
  5348. auto res = cli_.Get("/compress", headers);
  5349. ASSERT_TRUE(res);
  5350. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5352. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5353. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5354. "7890123456789012345678901234567890",
  5355. res->body);
  5356. EXPECT_EQ(StatusCode::OK_200, res->status);
  5357. }
  5358. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5359. Headers headers;
  5360. headers.emplace("Accept-Encoding", "gzip, deflate");
  5361. auto res = cli_.Get("/compress-with-charset", headers);
  5362. ASSERT_TRUE(res);
  5363. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5364. EXPECT_EQ("application/json; charset=utf-8",
  5365. res->get_header_value("Content-Type"));
  5366. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5367. "7890123456789012345678901234567890",
  5368. res->body);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. }
  5371. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5372. Headers headers;
  5373. headers.emplace("Accept-Encoding", "");
  5374. auto res = cli_.Get("/compress", headers);
  5375. ASSERT_TRUE(res);
  5376. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5377. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5378. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5379. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5380. "7890123456789012345678901234567890",
  5381. res->body);
  5382. EXPECT_EQ(StatusCode::OK_200, res->status);
  5383. }
  5384. TEST_F(ServerTest, GzipWithContentReceiver) {
  5385. Headers headers;
  5386. headers.emplace("Accept-Encoding", "gzip, deflate");
  5387. std::string body;
  5388. auto res = cli_.Get("/compress", headers,
  5389. [&](const char *data, uint64_t data_length) {
  5390. EXPECT_EQ(100U, data_length);
  5391. body.append(data, data_length);
  5392. return true;
  5393. });
  5394. ASSERT_TRUE(res);
  5395. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5396. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5397. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5398. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5399. "7890123456789012345678901234567890",
  5400. body);
  5401. EXPECT_EQ(StatusCode::OK_200, res->status);
  5402. }
  5403. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5404. Headers headers;
  5405. headers.emplace("Accept-Encoding", "gzip, deflate");
  5406. cli_.set_decompress(false);
  5407. auto res = cli_.Get("/compress", headers);
  5408. ASSERT_TRUE(res);
  5409. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5410. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5411. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5412. EXPECT_EQ(33U, res->body.size());
  5413. EXPECT_EQ(StatusCode::OK_200, res->status);
  5414. }
  5415. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5416. Headers headers;
  5417. headers.emplace("Accept-Encoding", "");
  5418. std::string body;
  5419. auto res = cli_.Get("/compress", headers,
  5420. [&](const char *data, uint64_t data_length) {
  5421. EXPECT_EQ(100U, data_length);
  5422. body.append(data, data_length);
  5423. return true;
  5424. });
  5425. ASSERT_TRUE(res);
  5426. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5428. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5429. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5430. "7890123456789012345678901234567890",
  5431. body);
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. }
  5434. TEST_F(ServerTest, NoGzip) {
  5435. Headers headers;
  5436. headers.emplace("Accept-Encoding", "gzip, deflate");
  5437. auto res = cli_.Get("/nocompress", headers);
  5438. ASSERT_TRUE(res);
  5439. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5440. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5441. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5442. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5443. "7890123456789012345678901234567890",
  5444. res->body);
  5445. EXPECT_EQ(StatusCode::OK_200, res->status);
  5446. }
  5447. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5448. Headers headers;
  5449. headers.emplace("Accept-Encoding", "gzip, deflate");
  5450. std::string body;
  5451. auto res = cli_.Get("/nocompress", headers,
  5452. [&](const char *data, uint64_t data_length) {
  5453. EXPECT_EQ(100U, data_length);
  5454. body.append(data, data_length);
  5455. return true;
  5456. });
  5457. ASSERT_TRUE(res);
  5458. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5459. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5460. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5461. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5462. "7890123456789012345678901234567890",
  5463. body);
  5464. EXPECT_EQ(StatusCode::OK_200, res->status);
  5465. }
  5466. TEST_F(ServerTest, MultipartFormDataGzip) {
  5467. UploadFormDataItems items = {
  5468. {"key1", "test", "", ""},
  5469. {"key2", "--abcdefg123", "", ""},
  5470. };
  5471. cli_.set_compress(true);
  5472. auto res = cli_.Post("/compress-multipart", items);
  5473. ASSERT_TRUE(res);
  5474. EXPECT_EQ(StatusCode::OK_200, res->status);
  5475. }
  5476. #endif
  5477. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5478. TEST_F(ServerTest, Brotli) {
  5479. Headers headers;
  5480. headers.emplace("Accept-Encoding", "br");
  5481. auto res = cli_.Get("/compress", headers);
  5482. ASSERT_TRUE(res);
  5483. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5484. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5485. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5486. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5487. "7890123456789012345678901234567890",
  5488. res->body);
  5489. EXPECT_EQ(StatusCode::OK_200, res->status);
  5490. }
  5491. #endif
  5492. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5493. TEST_F(ServerTest, Zstd) {
  5494. Headers headers;
  5495. headers.emplace("Accept-Encoding", "zstd");
  5496. auto res = cli_.Get("/compress", headers);
  5497. ASSERT_TRUE(res);
  5498. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5500. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5501. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5502. "7890123456789012345678901234567890",
  5503. res->body);
  5504. EXPECT_EQ(StatusCode::OK_200, res->status);
  5505. }
  5506. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5507. Headers headers;
  5508. headers.emplace("Accept-Encoding", "");
  5509. auto res = cli_.Get("/compress", headers);
  5510. ASSERT_TRUE(res);
  5511. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5513. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5514. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5515. "7890123456789012345678901234567890",
  5516. res->body);
  5517. EXPECT_EQ(StatusCode::OK_200, res->status);
  5518. }
  5519. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5520. Headers headers;
  5521. headers.emplace("Accept-Encoding", "zstd");
  5522. std::string body;
  5523. auto res = cli_.Get("/compress", headers,
  5524. [&](const char *data, uint64_t data_length) {
  5525. EXPECT_EQ(100U, data_length);
  5526. body.append(data, data_length);
  5527. return true;
  5528. });
  5529. ASSERT_TRUE(res);
  5530. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5531. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5532. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5533. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5534. "7890123456789012345678901234567890",
  5535. body);
  5536. EXPECT_EQ(StatusCode::OK_200, res->status);
  5537. }
  5538. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5539. Headers headers;
  5540. headers.emplace("Accept-Encoding", "zstd");
  5541. cli_.set_decompress(false);
  5542. auto res = cli_.Get("/compress", headers);
  5543. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5544. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5545. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5546. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5547. ASSERT_TRUE(res);
  5548. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5550. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5551. EXPECT_EQ(StatusCode::OK_200, res->status);
  5552. ASSERT_EQ(26U, res->body.size());
  5553. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5554. 0);
  5555. }
  5556. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5557. Headers headers;
  5558. headers.emplace("Accept-Encoding", "");
  5559. std::string body;
  5560. auto res = cli_.Get("/compress", headers,
  5561. [&](const char *data, uint64_t data_length) {
  5562. EXPECT_EQ(100U, data_length);
  5563. body.append(data, data_length);
  5564. return true;
  5565. });
  5566. ASSERT_TRUE(res);
  5567. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5569. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5571. "7890123456789012345678901234567890",
  5572. body);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. }
  5575. TEST_F(ServerTest, NoZstd) {
  5576. Headers headers;
  5577. headers.emplace("Accept-Encoding", "zstd");
  5578. auto res = cli_.Get("/nocompress", headers);
  5579. ASSERT_TRUE(res);
  5580. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5581. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5582. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5583. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5584. "7890123456789012345678901234567890",
  5585. res->body);
  5586. EXPECT_EQ(StatusCode::OK_200, res->status);
  5587. }
  5588. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5589. Headers headers;
  5590. headers.emplace("Accept-Encoding", "zstd");
  5591. std::string body;
  5592. auto res = cli_.Get("/nocompress", headers,
  5593. [&](const char *data, uint64_t data_length) {
  5594. EXPECT_EQ(100U, data_length);
  5595. body.append(data, data_length);
  5596. return true;
  5597. });
  5598. ASSERT_TRUE(res);
  5599. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5600. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5601. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5602. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5603. "7890123456789012345678901234567890",
  5604. body);
  5605. EXPECT_EQ(StatusCode::OK_200, res->status);
  5606. }
  5607. // TODO: How to enable zstd ??
  5608. TEST_F(ServerTest, MultipartFormDataZstd) {
  5609. UploadFormDataItems items = {
  5610. {"key1", "test", "", ""},
  5611. {"key2", "--abcdefg123", "", ""},
  5612. };
  5613. Headers headers;
  5614. headers.emplace("Accept-Encoding", "zstd");
  5615. cli_.set_compress(true);
  5616. auto res = cli_.Post("/compress-multipart", headers, items);
  5617. ASSERT_TRUE(res);
  5618. EXPECT_EQ(StatusCode::OK_200, res->status);
  5619. }
  5620. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5621. Headers headers;
  5622. headers.emplace("Accept-Encoding", "zstd");
  5623. cli_.set_compress(true);
  5624. auto res = cli_.Put(
  5625. "/put", headers, 3,
  5626. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5627. sink.os << "PUT";
  5628. return true;
  5629. },
  5630. "text/plain");
  5631. ASSERT_TRUE(res);
  5632. EXPECT_EQ(StatusCode::OK_200, res->status);
  5633. EXPECT_EQ("PUT", res->body);
  5634. }
  5635. // Pre-compression logging tests
  5636. TEST_F(ServerTest, PreCompressionLogging) {
  5637. // Test data for compression (matches the actual /compress endpoint content)
  5638. const std::string test_content =
  5639. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5640. "3456789012345678901234567890";
  5641. // Variables to capture logging data
  5642. std::string pre_compression_body;
  5643. std::string pre_compression_content_type;
  5644. std::string pre_compression_content_encoding;
  5645. std::string post_compression_body;
  5646. std::string post_compression_content_type;
  5647. std::string post_compression_content_encoding;
  5648. // Set up pre-compression logger
  5649. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5650. const Response &res) {
  5651. pre_compression_body = res.body;
  5652. pre_compression_content_type = res.get_header_value("Content-Type");
  5653. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5654. });
  5655. // Set up post-compression logger
  5656. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5657. post_compression_body = res.body;
  5658. post_compression_content_type = res.get_header_value("Content-Type");
  5659. post_compression_content_encoding =
  5660. res.get_header_value("Content-Encoding");
  5661. });
  5662. // Test with gzip compression
  5663. Headers headers;
  5664. headers.emplace("Accept-Encoding", "gzip");
  5665. auto res = cli_.Get("/compress", headers);
  5666. // Verify response was compressed
  5667. ASSERT_TRUE(res);
  5668. EXPECT_EQ(StatusCode::OK_200, res->status);
  5669. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5670. // Verify pre-compression logger captured uncompressed content
  5671. EXPECT_EQ(test_content, pre_compression_body);
  5672. EXPECT_EQ("text/plain", pre_compression_content_type);
  5673. EXPECT_TRUE(pre_compression_content_encoding
  5674. .empty()); // No encoding header before compression
  5675. // Verify post-compression logger captured compressed content
  5676. EXPECT_NE(test_content,
  5677. post_compression_body); // Should be different after compression
  5678. EXPECT_EQ("text/plain", post_compression_content_type);
  5679. EXPECT_EQ("gzip", post_compression_content_encoding);
  5680. // Verify compressed content is smaller
  5681. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5682. }
  5683. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5684. const std::string test_content =
  5685. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5686. "3456789012345678901234567890";
  5687. std::string pre_compression_body;
  5688. std::string post_compression_body;
  5689. svr_.set_pre_compression_logger(
  5690. [&](const Request & /*req*/, const Response &res) {
  5691. pre_compression_body = res.body;
  5692. });
  5693. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5694. post_compression_body = res.body;
  5695. });
  5696. Headers headers;
  5697. headers.emplace("Accept-Encoding", "br");
  5698. auto res = cli_.Get("/compress", headers);
  5699. ASSERT_TRUE(res);
  5700. EXPECT_EQ(StatusCode::OK_200, res->status);
  5701. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5702. // Verify pre-compression content is uncompressed
  5703. EXPECT_EQ(test_content, pre_compression_body);
  5704. // Verify post-compression content is compressed
  5705. EXPECT_NE(test_content, post_compression_body);
  5706. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5707. }
  5708. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5709. const std::string test_content =
  5710. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5711. "3456789012345678901234567890";
  5712. std::string pre_compression_body;
  5713. std::string post_compression_body;
  5714. svr_.set_pre_compression_logger(
  5715. [&](const Request & /*req*/, const Response &res) {
  5716. pre_compression_body = res.body;
  5717. });
  5718. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5719. post_compression_body = res.body;
  5720. });
  5721. // Request without compression (use /nocompress endpoint)
  5722. Headers headers;
  5723. auto res = cli_.Get("/nocompress", headers);
  5724. ASSERT_TRUE(res);
  5725. EXPECT_EQ(StatusCode::OK_200, res->status);
  5726. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5727. // Pre-compression logger should not be called when no compression is applied
  5728. EXPECT_TRUE(
  5729. pre_compression_body.empty()); // Pre-compression logger not called
  5730. EXPECT_EQ(
  5731. test_content,
  5732. post_compression_body); // Post-compression logger captures final content
  5733. }
  5734. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5735. const std::string test_content =
  5736. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5737. "3456789012345678901234567890";
  5738. std::string pre_compression_body;
  5739. bool pre_logger_called = false;
  5740. // Set only pre-compression logger
  5741. svr_.set_pre_compression_logger(
  5742. [&](const Request & /*req*/, const Response &res) {
  5743. pre_compression_body = res.body;
  5744. pre_logger_called = true;
  5745. });
  5746. Headers headers;
  5747. headers.emplace("Accept-Encoding", "gzip");
  5748. auto res = cli_.Get("/compress", headers);
  5749. ASSERT_TRUE(res);
  5750. EXPECT_EQ(StatusCode::OK_200, res->status);
  5751. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5752. // Verify pre-compression logger was called
  5753. EXPECT_TRUE(pre_logger_called);
  5754. EXPECT_EQ(test_content, pre_compression_body);
  5755. }
  5756. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5757. {
  5758. // Test with Expect: 100-continue header - success case
  5759. // Server returns 100 Continue, client sends body, server returns 200 OK
  5760. Request req;
  5761. req.method = "POST";
  5762. req.path = "/post-large";
  5763. req.set_header("Expect", "100-continue");
  5764. req.body = LARGE_DATA;
  5765. Response res;
  5766. auto error = Error::Success;
  5767. cli_.set_keep_alive(true);
  5768. auto ret = cli_.send(req, res, error);
  5769. EXPECT_TRUE(ret);
  5770. EXPECT_EQ(StatusCode::OK_200, res.status);
  5771. EXPECT_EQ(LARGE_DATA, res.body);
  5772. }
  5773. {
  5774. // Test with Expect: 100-continue header - error case
  5775. // Client should not send the body when server returns an error
  5776. Request req;
  5777. req.method = "POST";
  5778. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5779. req.set_header("Expect", "100-continue");
  5780. req.body = LARGE_DATA;
  5781. Response res;
  5782. auto error = Error::Success;
  5783. auto start = std::chrono::high_resolution_clock::now();
  5784. cli_.set_keep_alive(true);
  5785. auto ret = cli_.send(req, res, error);
  5786. auto end = std::chrono::high_resolution_clock::now();
  5787. auto elapsed =
  5788. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5789. .count();
  5790. // With Expect: 100-continue, request completes successfully but with error
  5791. EXPECT_TRUE(ret);
  5792. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5793. EXPECT_EQ("close", res.get_header_value("Connection"));
  5794. EXPECT_FALSE(cli_.is_socket_open());
  5795. EXPECT_LE(elapsed, 200);
  5796. }
  5797. {
  5798. // Send an extra GET request to ensure error recovery without hanging
  5799. Request req;
  5800. req.method = "GET";
  5801. req.path = "/hi";
  5802. auto start = std::chrono::high_resolution_clock::now();
  5803. auto res = cli_.send(req);
  5804. auto end = std::chrono::high_resolution_clock::now();
  5805. auto elapsed =
  5806. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5807. .count();
  5808. ASSERT_TRUE(res);
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. EXPECT_EQ("Hello World!", res->body);
  5811. EXPECT_LE(elapsed, 500);
  5812. }
  5813. }
  5814. TEST(ZstdDecompressor, ChunkedDecompression) {
  5815. std::string data;
  5816. for (size_t i = 0; i < 32 * 1024; ++i) {
  5817. data.push_back(static_cast<char>('a' + i % 26));
  5818. }
  5819. std::string compressed_data;
  5820. {
  5821. httplib::detail::zstd_compressor compressor;
  5822. bool result = compressor.compress(
  5823. data.data(), data.size(),
  5824. /*last=*/true,
  5825. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5826. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5827. compressed_data_size);
  5828. return true;
  5829. });
  5830. ASSERT_TRUE(result);
  5831. }
  5832. std::string decompressed_data;
  5833. {
  5834. httplib::detail::zstd_decompressor decompressor;
  5835. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5836. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5837. size_t chunk_size = 130;
  5838. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5839. chunk_begin += chunk_size) {
  5840. size_t current_chunk_size =
  5841. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5842. bool result = decompressor.decompress(
  5843. compressed_data.data() + chunk_begin, current_chunk_size,
  5844. [&](const char *decompressed_data_chunk,
  5845. size_t decompressed_data_chunk_size) {
  5846. decompressed_data.insert(decompressed_data.size(),
  5847. decompressed_data_chunk,
  5848. decompressed_data_chunk_size);
  5849. return true;
  5850. });
  5851. ASSERT_TRUE(result);
  5852. }
  5853. }
  5854. ASSERT_EQ(data, decompressed_data);
  5855. }
  5856. TEST(ZstdDecompressor, Decompress) {
  5857. std::string original_text = "Compressed with ZSTD";
  5858. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5859. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5860. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5861. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5862. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5863. std::string decompressed_data;
  5864. {
  5865. httplib::detail::zstd_decompressor decompressor;
  5866. bool result = decompressor.decompress(
  5867. compressed_data.data(), compressed_data.size(),
  5868. [&](const char *decompressed_data_chunk,
  5869. size_t decompressed_data_chunk_size) {
  5870. decompressed_data.insert(decompressed_data.size(),
  5871. decompressed_data_chunk,
  5872. decompressed_data_chunk_size);
  5873. return true;
  5874. });
  5875. ASSERT_TRUE(result);
  5876. }
  5877. ASSERT_EQ(original_text, decompressed_data);
  5878. }
  5879. #endif
  5880. // Sends a raw request to a server listening at HOST:PORT.
  5881. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5882. std::string *resp = nullptr) {
  5883. auto error = Error::Success;
  5884. auto client_sock = detail::create_client_socket(
  5885. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5886. /*connection_timeout_sec=*/5, 0,
  5887. /*read_timeout_sec=*/5, 0,
  5888. /*write_timeout_sec=*/5, 0, std::string(), error);
  5889. if (client_sock == INVALID_SOCKET) { return false; }
  5890. auto ret = detail::process_client_socket(
  5891. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5892. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5893. if (req.size() !=
  5894. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5895. return false;
  5896. }
  5897. char buf[512];
  5898. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5899. while (line_reader.getline()) {
  5900. if (resp) { *resp += line_reader.ptr(); }
  5901. }
  5902. return true;
  5903. });
  5904. detail::close_socket(client_sock);
  5905. return ret;
  5906. }
  5907. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5908. Server svr;
  5909. std::string header_value;
  5910. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5911. header_value = req.get_header_value("foo");
  5912. res.set_content("ok", "text/plain");
  5913. });
  5914. thread t = thread([&] { svr.listen(HOST, PORT); });
  5915. auto se = detail::scope_exit([&] {
  5916. svr.stop();
  5917. t.join();
  5918. ASSERT_FALSE(svr.is_running());
  5919. });
  5920. svr.wait_until_ready();
  5921. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5922. // like characters are not treated the same - use vertical tab and escape.
  5923. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5924. "foo: \t \v bar \x1B\t \r\n"
  5925. "Connection: close\r\n"
  5926. "\r\n";
  5927. std::string res;
  5928. ASSERT_TRUE(send_request(5, req, &res));
  5929. EXPECT_EQ(header_value, "");
  5930. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5931. }
  5932. // Sends a raw request and verifies that there isn't a crash or exception.
  5933. static void test_raw_request(const std::string &req,
  5934. std::string *out = nullptr) {
  5935. Server svr;
  5936. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5937. res.set_content("ok", "text/plain");
  5938. });
  5939. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5940. res.set_content("ok", "text/plain");
  5941. });
  5942. svr.Get("/header_field_value_check",
  5943. [&](const Request & /*req*/, Response &res) {
  5944. res.set_content("ok", "text/plain");
  5945. });
  5946. // Server read timeout must be longer than the client read timeout for the
  5947. // bug to reproduce, probably to force the server to process a request
  5948. // without a trailing blank line.
  5949. const time_t client_read_timeout_sec = 1;
  5950. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5951. bool listen_thread_ok = false;
  5952. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5953. auto se = detail::scope_exit([&] {
  5954. svr.stop();
  5955. t.join();
  5956. ASSERT_FALSE(svr.is_running());
  5957. EXPECT_TRUE(listen_thread_ok);
  5958. });
  5959. svr.wait_until_ready();
  5960. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5961. }
  5962. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5963. // A certain header line causes an exception if the header property is parsed
  5964. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5965. test_raw_request(
  5966. "GET /hi HTTP/1.1\r\n"
  5967. " : "
  5968. " "
  5969. " ");
  5970. }
  5971. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5972. // A certain header line causes an exception if the header property *name* is
  5973. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5974. // greedy matcher and requires backtracking when there are a lot of ":"
  5975. // characters.
  5976. // This occurs with libc++ but not libstdc++.
  5977. test_raw_request(
  5978. "GET /hi HTTP/1.1\r\n"
  5979. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5980. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5981. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5982. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5983. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5984. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5985. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5986. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5987. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5988. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5989. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5990. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5991. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5992. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5993. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5994. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5995. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5996. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5997. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5998. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5999. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6000. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6001. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6002. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6003. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6004. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6005. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6006. "&&&%%%");
  6007. }
  6008. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6009. // Make sure this doesn't crash the server.
  6010. // In a previous version of the header line regex, the "\r" rendered the line
  6011. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6012. // a new position where the leading white space ended and the field value
  6013. // began.
  6014. // The crash occurs with libc++ but not libstdc++.
  6015. test_raw_request("GET /hi HTTP/1.1\r\n"
  6016. "a:" +
  6017. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6018. "\r\n"
  6019. "\r\n");
  6020. }
  6021. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6022. std::string out;
  6023. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6024. "Content-Type: text/plain\r\n"
  6025. "Transfer-Encoding: chunked\r\n"
  6026. "\r\n"
  6027. "nothex\r\n",
  6028. &out);
  6029. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6030. }
  6031. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6032. std::string out;
  6033. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6034. "Content-Type: text/plain\r\n"
  6035. "Transfer-Encoding: chunked\r\n"
  6036. "\r\n"
  6037. "3\r\n"
  6038. "xyz\r\n"
  6039. "NaN\r\n",
  6040. &out);
  6041. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6042. }
  6043. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6044. std::string out;
  6045. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6046. "Content-Type: text/plain\r\n"
  6047. "Transfer-Encoding: chunked\r\n"
  6048. "\r\n"
  6049. // Length is too large for 64 bits.
  6050. "1ffffffffffffffff\r\n"
  6051. "xyz\r\n",
  6052. &out);
  6053. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6054. }
  6055. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6056. test_raw_request("GET /hi HTTP/1.1\r\n"
  6057. "Content-Type: text/plain\r\n\r");
  6058. }
  6059. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6060. std::string out;
  6061. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6062. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6063. }
  6064. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6065. Server svr;
  6066. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6067. EXPECT_TRUE(!req.remote_addr.empty());
  6068. });
  6069. thread t = thread([&] { svr.listen(HOST, PORT); });
  6070. auto se = detail::scope_exit([&] {
  6071. svr.stop();
  6072. t.join();
  6073. ASSERT_FALSE(svr.is_running());
  6074. });
  6075. svr.wait_until_ready();
  6076. // Send an invalid request line to trigger Bad Request
  6077. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6078. std::string out;
  6079. ASSERT_TRUE(send_request(5, bad_req, &out));
  6080. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6081. }
  6082. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6083. std::string out;
  6084. std::string request(
  6085. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6086. test_raw_request(request, &out);
  6087. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6088. }
  6089. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6090. std::string out;
  6091. std::string request(
  6092. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6093. test_raw_request(request, &out);
  6094. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6095. }
  6096. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6097. std::string out;
  6098. std::string request(
  6099. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6100. test_raw_request(request, &out);
  6101. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6102. }
  6103. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6104. std::string out;
  6105. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6106. "Test: \r\n\r\n",
  6107. &out);
  6108. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6109. }
  6110. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6111. Server svr;
  6112. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6113. res.set_header("Cache-Control", "no-cache");
  6114. res.set_chunked_content_provider(
  6115. "text/event-stream", [](size_t offset, DataSink &sink) {
  6116. std::string s = "data:";
  6117. s += std::to_string(offset);
  6118. s += "\n\n";
  6119. auto ret = sink.write(s.data(), s.size());
  6120. EXPECT_TRUE(ret);
  6121. std::this_thread::sleep_for(std::chrono::seconds(1));
  6122. return true;
  6123. });
  6124. });
  6125. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6126. svr.wait_until_ready();
  6127. Client client(HOST, PORT);
  6128. const Headers headers = {{"Accept", "text/event-stream"}};
  6129. auto get_thread = std::thread([&client, &headers]() {
  6130. auto res = client.Get(
  6131. "/events", headers,
  6132. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6133. });
  6134. auto se = detail::scope_exit([&] {
  6135. svr.stop();
  6136. get_thread.join();
  6137. listen_thread.join();
  6138. ASSERT_FALSE(svr.is_running());
  6139. });
  6140. // Give GET time to get a few messages.
  6141. std::this_thread::sleep_for(std::chrono::seconds(2));
  6142. }
  6143. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6144. httplib::Server svr;
  6145. svr.Post("/hi",
  6146. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6147. res.status = StatusCode::OK_200;
  6148. });
  6149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6150. svr.wait_until_ready();
  6151. Client cli(HOST, PORT);
  6152. auto res = cli.Post("/hi", "data", "text/plain");
  6153. ASSERT_TRUE(res);
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. svr.stop();
  6156. thread.join();
  6157. ASSERT_FALSE(svr.is_running());
  6158. res = cli.Post("/hi", "data", "text/plain");
  6159. ASSERT_FALSE(res);
  6160. }
  6161. TEST(ServerStopTest, ListenFailure) {
  6162. Server svr;
  6163. auto t = thread([&]() {
  6164. auto ret = svr.listen("????", PORT);
  6165. EXPECT_FALSE(ret);
  6166. });
  6167. svr.wait_until_ready();
  6168. svr.stop();
  6169. t.join();
  6170. }
  6171. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6172. TEST(ServerStopTest, Decommision) {
  6173. Server svr;
  6174. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6175. for (int i = 0; i < 4; i++) {
  6176. auto is_even = !(i % 2);
  6177. std::thread t{[&] {
  6178. try {
  6179. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6180. if (is_even) {
  6181. throw std::runtime_error("Some thing that happens to go wrong.");
  6182. }
  6183. svr.listen(HOST, PORT);
  6184. } catch (...) { svr.decommission(); }
  6185. }};
  6186. svr.wait_until_ready();
  6187. // Server is up
  6188. {
  6189. Client cli(HOST, PORT);
  6190. auto res = cli.Get("/hi");
  6191. if (is_even) {
  6192. EXPECT_FALSE(res);
  6193. } else {
  6194. EXPECT_TRUE(res);
  6195. EXPECT_EQ("hi...", res->body);
  6196. }
  6197. }
  6198. svr.stop();
  6199. t.join();
  6200. // Server is down...
  6201. {
  6202. Client cli(HOST, PORT);
  6203. auto res = cli.Get("/hi");
  6204. EXPECT_FALSE(res);
  6205. }
  6206. }
  6207. }
  6208. #endif
  6209. // Helper function for string body upload progress tests
  6210. template <typename SetupHandler, typename ClientCall>
  6211. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6212. ClientCall &&client_call,
  6213. const string &body) {
  6214. Server svr;
  6215. setup_handler(svr);
  6216. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6217. auto se = detail::scope_exit([&] {
  6218. svr.stop();
  6219. t.join();
  6220. });
  6221. svr.wait_until_ready();
  6222. Client cli(HOST, PORT);
  6223. vector<uint64_t> progress_values;
  6224. bool progress_called = false;
  6225. auto res =
  6226. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6227. progress_values.push_back(current);
  6228. progress_called = true;
  6229. return true;
  6230. });
  6231. ASSERT_TRUE(res);
  6232. EXPECT_EQ(200, res->status);
  6233. EXPECT_TRUE(progress_called);
  6234. }
  6235. TEST(UploadProgressTest, PostStringBodyBasic) {
  6236. TestStringBodyUploadProgress(
  6237. [](Server &svr) {
  6238. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6239. res.set_content("received", "text/plain");
  6240. });
  6241. },
  6242. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6243. return cli.Post("/test", body, "text/plain", progress_callback);
  6244. },
  6245. "test data for upload progress");
  6246. }
  6247. TEST(UploadProgressTest, PutStringBodyBasic) {
  6248. TestStringBodyUploadProgress(
  6249. [](Server &svr) {
  6250. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6251. res.set_content("put received", "text/plain");
  6252. });
  6253. },
  6254. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6255. return cli.Put("/test", body, "text/plain", progress_callback);
  6256. },
  6257. "put test data for upload progress");
  6258. }
  6259. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6260. TestStringBodyUploadProgress(
  6261. [](Server &svr) {
  6262. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6263. res.set_content("patch received", "text/plain");
  6264. });
  6265. },
  6266. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6267. return cli.Patch("/test", body, "text/plain", progress_callback);
  6268. },
  6269. "patch test data for upload progress");
  6270. }
  6271. // Helper function for content provider upload progress tests
  6272. template <typename SetupHandler, typename ClientCall>
  6273. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6274. ClientCall &&client_call) {
  6275. Server svr;
  6276. setup_handler(svr);
  6277. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6278. auto se = detail::scope_exit([&] {
  6279. svr.stop();
  6280. t.join();
  6281. });
  6282. svr.wait_until_ready();
  6283. Client cli(HOST, PORT);
  6284. vector<uint64_t> progress_values;
  6285. auto res =
  6286. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6287. progress_values.push_back(current);
  6288. return true;
  6289. });
  6290. ASSERT_TRUE(res);
  6291. EXPECT_EQ(200, res->status);
  6292. EXPECT_FALSE(progress_values.empty());
  6293. }
  6294. TEST(UploadProgressTest, PostContentProviderProgress) {
  6295. TestContentProviderUploadProgress(
  6296. [](Server &svr) {
  6297. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6298. res.set_content("provider received", "text/plain");
  6299. });
  6300. },
  6301. [](Client &cli, UploadProgress progress_callback) {
  6302. return cli.Post(
  6303. "/test", 10,
  6304. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6305. sink.os << "test data";
  6306. return true;
  6307. },
  6308. "text/plain", progress_callback);
  6309. });
  6310. }
  6311. // Helper function for multipart upload progress tests
  6312. template <typename SetupHandler, typename ClientCall>
  6313. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6314. ClientCall &&client_call,
  6315. const string &endpoint) {
  6316. Server svr;
  6317. setup_handler(svr);
  6318. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6319. auto se = detail::scope_exit([&] {
  6320. svr.stop();
  6321. t.join();
  6322. });
  6323. svr.wait_until_ready();
  6324. Client cli(HOST, PORT);
  6325. vector<uint64_t> progress_values;
  6326. UploadFormDataItems items = {
  6327. {"field1", "value1", "", ""},
  6328. {"field2", "longer value for progress tracking test", "", ""},
  6329. {"file1", "file content data for upload progress", "test.txt",
  6330. "text/plain"}};
  6331. auto res = client_call(cli, endpoint, items,
  6332. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6333. progress_values.push_back(current);
  6334. return true;
  6335. });
  6336. ASSERT_TRUE(res);
  6337. EXPECT_EQ(200, res->status);
  6338. EXPECT_FALSE(progress_values.empty());
  6339. }
  6340. TEST(UploadProgressTest, PostMultipartProgress) {
  6341. TestMultipartUploadProgress(
  6342. [](Server &svr) {
  6343. svr.Post("/multipart", [](const Request &req, Response &res) {
  6344. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6345. res.set_content("multipart received", "text/plain");
  6346. });
  6347. },
  6348. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6349. UploadProgress progress_callback) {
  6350. return cli.Post(endpoint, items, progress_callback);
  6351. },
  6352. "/multipart");
  6353. }
  6354. // Helper function for basic download progress tests
  6355. template <typename SetupHandler, typename ClientCall>
  6356. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6357. ClientCall &&client_call, const string &endpoint,
  6358. size_t expected_content_size) {
  6359. Server svr;
  6360. setup_handler(svr);
  6361. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6362. auto se = detail::scope_exit([&] {
  6363. svr.stop();
  6364. t.join();
  6365. });
  6366. svr.wait_until_ready();
  6367. Client cli(HOST, PORT);
  6368. vector<uint64_t> progress_values;
  6369. auto res = client_call(cli, endpoint,
  6370. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6371. progress_values.push_back(current);
  6372. return true;
  6373. });
  6374. ASSERT_TRUE(res);
  6375. EXPECT_EQ(200, res->status);
  6376. EXPECT_FALSE(progress_values.empty());
  6377. EXPECT_EQ(expected_content_size, res->body.size());
  6378. }
  6379. TEST(DownloadProgressTest, GetBasic) {
  6380. TestBasicDownloadProgress(
  6381. [](Server &svr) {
  6382. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6383. string content(1000, 'D');
  6384. res.set_content(content, "text/plain");
  6385. });
  6386. },
  6387. [](Client &cli, const string &endpoint,
  6388. DownloadProgress progress_callback) {
  6389. return cli.Get(endpoint, progress_callback);
  6390. },
  6391. "/download", 1000u);
  6392. }
  6393. // Helper function for content receiver download progress tests
  6394. template <typename SetupHandler, typename ClientCall>
  6395. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6396. ClientCall &&client_call,
  6397. const string &endpoint,
  6398. size_t expected_content_size) {
  6399. Server svr;
  6400. setup_handler(svr);
  6401. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6402. auto se = detail::scope_exit([&] {
  6403. svr.stop();
  6404. t.join();
  6405. });
  6406. svr.wait_until_ready();
  6407. Client cli(HOST, PORT);
  6408. vector<uint64_t> progress_values;
  6409. string received_body;
  6410. auto res = client_call(
  6411. cli, endpoint,
  6412. [&](const char *data, size_t data_length) -> bool {
  6413. received_body.append(data, data_length);
  6414. return true;
  6415. },
  6416. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6417. progress_values.push_back(current);
  6418. return true;
  6419. });
  6420. ASSERT_TRUE(res);
  6421. EXPECT_EQ(200, res->status);
  6422. EXPECT_FALSE(progress_values.empty());
  6423. EXPECT_EQ(expected_content_size, received_body.size());
  6424. EXPECT_TRUE(res->body.empty());
  6425. }
  6426. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6427. TestContentReceiverDownloadProgress(
  6428. [](Server &svr) {
  6429. svr.Get("/download-receiver",
  6430. [](const Request & /*req*/, Response &res) {
  6431. string content(2000, 'R');
  6432. res.set_content(content, "text/plain");
  6433. });
  6434. },
  6435. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6436. DownloadProgress progress_callback) {
  6437. return cli.Get(endpoint, content_receiver, progress_callback);
  6438. },
  6439. "/download-receiver", 2000u);
  6440. }
  6441. TEST(StreamingTest, NoContentLengthStreaming) {
  6442. Server svr;
  6443. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6444. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6445. if (offset < 6) {
  6446. sink.os << (offset < 3 ? "a" : "b");
  6447. } else {
  6448. sink.done();
  6449. }
  6450. return true;
  6451. });
  6452. });
  6453. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6454. auto listen_se = detail::scope_exit([&] {
  6455. svr.stop();
  6456. listen_thread.join();
  6457. ASSERT_FALSE(svr.is_running());
  6458. });
  6459. svr.wait_until_ready();
  6460. Client client(HOST, PORT);
  6461. auto get_thread = std::thread([&client]() {
  6462. std::string s;
  6463. auto res =
  6464. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6465. s += std::string(data, len);
  6466. return true;
  6467. });
  6468. ASSERT_TRUE(res);
  6469. EXPECT_EQ(StatusCode::OK_200, res->status);
  6470. EXPECT_EQ("aaabbb", s);
  6471. });
  6472. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6473. // Give GET time to get a few messages.
  6474. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6475. }
  6476. TEST(MountTest, Unmount) {
  6477. Server svr;
  6478. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6479. auto se = detail::scope_exit([&] {
  6480. svr.stop();
  6481. listen_thread.join();
  6482. ASSERT_FALSE(svr.is_running());
  6483. });
  6484. svr.wait_until_ready();
  6485. Client cli("localhost", PORT);
  6486. svr.set_mount_point("/mount2", "./www2");
  6487. auto res = cli.Get("/");
  6488. ASSERT_TRUE(res);
  6489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6490. res = cli.Get("/mount2/dir/test.html");
  6491. ASSERT_TRUE(res);
  6492. EXPECT_EQ(StatusCode::OK_200, res->status);
  6493. svr.set_mount_point("/", "./www");
  6494. res = cli.Get("/dir/");
  6495. ASSERT_TRUE(res);
  6496. EXPECT_EQ(StatusCode::OK_200, res->status);
  6497. svr.remove_mount_point("/");
  6498. res = cli.Get("/dir/");
  6499. ASSERT_TRUE(res);
  6500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6501. svr.remove_mount_point("/mount2");
  6502. res = cli.Get("/mount2/dir/test.html");
  6503. ASSERT_TRUE(res);
  6504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6505. }
  6506. TEST(MountTest, Redicect) {
  6507. Server svr;
  6508. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6509. auto se = detail::scope_exit([&] {
  6510. svr.stop();
  6511. listen_thread.join();
  6512. ASSERT_FALSE(svr.is_running());
  6513. });
  6514. svr.set_mount_point("/", "./www");
  6515. svr.wait_until_ready();
  6516. Client cli("localhost", PORT);
  6517. auto res = cli.Get("/dir/");
  6518. ASSERT_TRUE(res);
  6519. EXPECT_EQ(StatusCode::OK_200, res->status);
  6520. res = cli.Get("/dir");
  6521. ASSERT_TRUE(res);
  6522. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6523. res = cli.Get("/file");
  6524. ASSERT_TRUE(res);
  6525. EXPECT_EQ(StatusCode::OK_200, res->status);
  6526. res = cli.Get("/file/");
  6527. ASSERT_TRUE(res);
  6528. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6529. cli.set_follow_location(true);
  6530. res = cli.Get("/dir");
  6531. ASSERT_TRUE(res);
  6532. EXPECT_EQ(StatusCode::OK_200, res->status);
  6533. }
  6534. TEST(MountTest, MultibytesPathName) {
  6535. Server svr;
  6536. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6537. auto se = detail::scope_exit([&] {
  6538. svr.stop();
  6539. listen_thread.join();
  6540. ASSERT_FALSE(svr.is_running());
  6541. });
  6542. svr.set_mount_point("/", "./www");
  6543. svr.wait_until_ready();
  6544. Client cli("localhost", PORT);
  6545. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6546. ASSERT_TRUE(res);
  6547. EXPECT_EQ(StatusCode::OK_200, res->status);
  6548. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6549. }
  6550. TEST(KeepAliveTest, ReadTimeout) {
  6551. Server svr;
  6552. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6553. std::this_thread::sleep_for(std::chrono::seconds(2));
  6554. res.set_content("a", "text/plain");
  6555. });
  6556. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6557. res.set_content("b", "text/plain");
  6558. });
  6559. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6560. auto se = detail::scope_exit([&] {
  6561. svr.stop();
  6562. listen_thread.join();
  6563. ASSERT_FALSE(svr.is_running());
  6564. });
  6565. svr.wait_until_ready();
  6566. Client cli("localhost", PORT);
  6567. cli.set_keep_alive(true);
  6568. cli.set_read_timeout(std::chrono::seconds(1));
  6569. auto resa = cli.Get("/a");
  6570. ASSERT_FALSE(resa);
  6571. EXPECT_EQ(Error::Read, resa.error());
  6572. auto resb = cli.Get("/b");
  6573. ASSERT_TRUE(resb);
  6574. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6575. EXPECT_EQ("b", resb->body);
  6576. }
  6577. TEST(KeepAliveTest, MaxCount) {
  6578. size_t keep_alive_max_count = 3;
  6579. Server svr;
  6580. svr.set_keep_alive_max_count(keep_alive_max_count);
  6581. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6582. res.set_content("Hello World!", "text/plain");
  6583. });
  6584. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6585. auto se = detail::scope_exit([&] {
  6586. svr.stop();
  6587. listen_thread.join();
  6588. ASSERT_FALSE(svr.is_running());
  6589. });
  6590. svr.wait_until_ready();
  6591. Client cli(HOST, PORT);
  6592. cli.set_keep_alive(true);
  6593. for (size_t i = 0; i < 5; i++) {
  6594. auto result = cli.Get("/hi");
  6595. ASSERT_TRUE(result);
  6596. EXPECT_EQ(StatusCode::OK_200, result->status);
  6597. if (i == keep_alive_max_count - 1) {
  6598. EXPECT_EQ("close", result->get_header_value("Connection"));
  6599. } else {
  6600. EXPECT_FALSE(result->has_header("Connection"));
  6601. }
  6602. }
  6603. }
  6604. TEST(KeepAliveTest, Issue1041) {
  6605. Server svr;
  6606. svr.set_keep_alive_timeout(3);
  6607. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6608. res.set_content("Hello World!", "text/plain");
  6609. });
  6610. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6611. auto se = detail::scope_exit([&] {
  6612. svr.stop();
  6613. listen_thread.join();
  6614. ASSERT_FALSE(svr.is_running());
  6615. });
  6616. svr.wait_until_ready();
  6617. Client cli(HOST, PORT);
  6618. cli.set_keep_alive(true);
  6619. auto result = cli.Get("/hi");
  6620. ASSERT_TRUE(result);
  6621. EXPECT_EQ(StatusCode::OK_200, result->status);
  6622. std::this_thread::sleep_for(std::chrono::seconds(5));
  6623. result = cli.Get("/hi");
  6624. ASSERT_TRUE(result);
  6625. EXPECT_EQ(StatusCode::OK_200, result->status);
  6626. }
  6627. TEST(KeepAliveTest, Issue1959) {
  6628. Server svr;
  6629. svr.set_keep_alive_timeout(5);
  6630. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6631. res.set_content("a", "text/plain");
  6632. });
  6633. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6634. auto se = detail::scope_exit([&] {
  6635. if (!svr.is_running()) return;
  6636. svr.stop();
  6637. listen_thread.join();
  6638. ASSERT_FALSE(svr.is_running());
  6639. });
  6640. svr.wait_until_ready();
  6641. Client cli("localhost", PORT);
  6642. cli.set_keep_alive(true);
  6643. using namespace std::chrono;
  6644. auto start = steady_clock::now();
  6645. cli.Get("/a");
  6646. svr.stop();
  6647. listen_thread.join();
  6648. auto end = steady_clock::now();
  6649. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6650. EXPECT_LT(elapsed, 5000);
  6651. }
  6652. #ifdef CPPHTTPLIB_SSL_ENABLED
  6653. TEST(KeepAliveTest, SSLClientReconnection) {
  6654. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6655. ASSERT_TRUE(svr.is_valid());
  6656. svr.set_keep_alive_timeout(1);
  6657. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6658. res.set_content("Hello World!", "text/plain");
  6659. });
  6660. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6661. auto se = detail::scope_exit([&] {
  6662. svr.stop();
  6663. listen_thread.join();
  6664. ASSERT_FALSE(svr.is_running());
  6665. });
  6666. svr.wait_until_ready();
  6667. SSLClient cli(HOST, PORT);
  6668. cli.enable_server_certificate_verification(false);
  6669. cli.set_keep_alive(true);
  6670. auto result = cli.Get("/hi");
  6671. ASSERT_TRUE(result);
  6672. EXPECT_EQ(StatusCode::OK_200, result->status);
  6673. result = cli.Get("/hi");
  6674. ASSERT_TRUE(result);
  6675. EXPECT_EQ(StatusCode::OK_200, result->status);
  6676. std::this_thread::sleep_for(std::chrono::seconds(2));
  6677. // Recoonect
  6678. result = cli.Get("/hi");
  6679. ASSERT_TRUE(result);
  6680. EXPECT_EQ(StatusCode::OK_200, result->status);
  6681. result = cli.Get("/hi");
  6682. ASSERT_TRUE(result);
  6683. EXPECT_EQ(StatusCode::OK_200, result->status);
  6684. }
  6685. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6686. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6687. ASSERT_TRUE(svr.is_valid());
  6688. svr.set_keep_alive_timeout(1);
  6689. std::string content = "reconnect";
  6690. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6691. res.set_content("Hello World!", "text/plain");
  6692. });
  6693. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6694. auto se = detail::scope_exit([&] {
  6695. svr.stop();
  6696. listen_thread.join();
  6697. ASSERT_FALSE(svr.is_running());
  6698. });
  6699. svr.wait_until_ready();
  6700. SSLClient cli(HOST, PORT);
  6701. cli.enable_server_certificate_verification(false);
  6702. cli.set_keep_alive(true);
  6703. auto result = cli.Post(
  6704. "/hi", content.size(),
  6705. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6706. sink.write(content.c_str(), content.size());
  6707. return true;
  6708. },
  6709. "text/plain");
  6710. ASSERT_TRUE(result);
  6711. EXPECT_EQ(200, result->status);
  6712. std::this_thread::sleep_for(std::chrono::seconds(2));
  6713. // Recoonect
  6714. result = cli.Post(
  6715. "/hi", content.size(),
  6716. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6717. sink.write(content.c_str(), content.size());
  6718. return true;
  6719. },
  6720. "text/plain");
  6721. ASSERT_TRUE(result);
  6722. EXPECT_EQ(200, result->status);
  6723. result = cli.Post(
  6724. "/hi", content.size(),
  6725. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6726. sink.write(content.c_str(), content.size());
  6727. return true;
  6728. },
  6729. "text/plain");
  6730. ASSERT_TRUE(result);
  6731. EXPECT_EQ(200, result->status);
  6732. }
  6733. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6734. using namespace httplib::tls;
  6735. {
  6736. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6737. ASSERT_TRUE(svr.is_valid());
  6738. svr.Get("/sni", [&](const Request &req, Response &res) {
  6739. std::string expected = req.sni();
  6740. EXPECT_EQ(expected, req.get_param_value("expected"));
  6741. res.set_content("ok", "text/plain");
  6742. });
  6743. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6744. auto se = detail::scope_exit([&] {
  6745. svr.stop();
  6746. listen_thread.join();
  6747. ASSERT_FALSE(svr.is_running());
  6748. });
  6749. svr.wait_until_ready();
  6750. {
  6751. SSLClient cli("localhost", PORT);
  6752. cli.enable_server_certificate_verification(false);
  6753. auto res = cli.Get("/sni?expected=localhost");
  6754. ASSERT_TRUE(res);
  6755. }
  6756. {
  6757. SSLClient cli("::1", PORT);
  6758. cli.enable_server_certificate_verification(false);
  6759. auto res = cli.Get("/sni?expected=");
  6760. // NOTE: This may fail if the server is listening on IPv4 only
  6761. // (e.g., when localhost resolves to 127.0.0.1 only)
  6762. if (res) {
  6763. EXPECT_EQ(StatusCode::OK_200, res->status);
  6764. } else {
  6765. EXPECT_EQ(Error::Connection, res.error());
  6766. }
  6767. }
  6768. }
  6769. }
  6770. #endif
  6771. TEST(ClientProblemDetectionTest, ContentProvider) {
  6772. Server svr;
  6773. size_t content_length = 1024 * 1024;
  6774. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6775. res.set_content_provider(
  6776. content_length, "text/plain",
  6777. [&](size_t offset, size_t length, DataSink &sink) {
  6778. auto out_len = std::min(length, static_cast<size_t>(1024));
  6779. std::string out(out_len, '@');
  6780. sink.write(out.data(), out_len);
  6781. return offset < 4096;
  6782. },
  6783. [](bool success) { ASSERT_FALSE(success); });
  6784. });
  6785. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6786. res.set_content_provider(
  6787. 0, "text/plain",
  6788. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6789. EXPECT_TRUE(false);
  6790. return true;
  6791. },
  6792. [](bool success) { ASSERT_FALSE(success); });
  6793. });
  6794. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6795. auto se = detail::scope_exit([&] {
  6796. svr.stop();
  6797. listen_thread.join();
  6798. ASSERT_FALSE(svr.is_running());
  6799. });
  6800. svr.wait_until_ready();
  6801. Client cli("localhost", PORT);
  6802. {
  6803. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6804. size_t /*data_length*/) { return false; });
  6805. ASSERT_FALSE(res);
  6806. }
  6807. {
  6808. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6809. size_t /*data_length*/) { return false; });
  6810. ASSERT_TRUE(res);
  6811. }
  6812. }
  6813. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6814. Server svr;
  6815. svr.set_error_handler([](Request const &, Response &res) -> void {
  6816. res.set_chunked_content_provider(
  6817. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6818. sink.os << "hello";
  6819. sink.os << "world";
  6820. sink.done();
  6821. return true;
  6822. });
  6823. });
  6824. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. svr.stop();
  6827. listen_thread.join();
  6828. ASSERT_FALSE(svr.is_running());
  6829. });
  6830. svr.wait_until_ready();
  6831. Client cli("localhost", PORT);
  6832. auto res = cli.Get("/");
  6833. ASSERT_TRUE(res);
  6834. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6835. EXPECT_EQ("helloworld", res->body);
  6836. }
  6837. TEST(LongPollingTest, ClientCloseDetection) {
  6838. Server svr;
  6839. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6840. res.set_chunked_content_provider(
  6841. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6842. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6843. sink.os << "hello";
  6844. auto count = 10;
  6845. while (count > 0 && sink.is_writable()) {
  6846. this_thread::sleep_for(chrono::milliseconds(10));
  6847. count--;
  6848. }
  6849. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6850. return true;
  6851. });
  6852. });
  6853. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6854. auto se = detail::scope_exit([&] {
  6855. svr.stop();
  6856. listen_thread.join();
  6857. ASSERT_FALSE(svr.is_running());
  6858. });
  6859. svr.wait_until_ready();
  6860. Client cli("localhost", PORT);
  6861. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6862. EXPECT_EQ("hello", string(data, data_length));
  6863. return false; // close the socket immediately.
  6864. });
  6865. ASSERT_FALSE(res);
  6866. }
  6867. TEST(GetWithParametersTest, GetWithParameters) {
  6868. Server svr;
  6869. svr.Get("/", [&](const Request &req, Response &) {
  6870. EXPECT_EQ("world", req.get_param_value("hello"));
  6871. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6872. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6873. });
  6874. svr.Get("/params", [&](const Request &req, Response &) {
  6875. EXPECT_EQ("world", req.get_param_value("hello"));
  6876. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6877. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6878. });
  6879. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6880. EXPECT_EQ("resource-id", req.matches[1]);
  6881. EXPECT_EQ("foo", req.get_param_value("param1"));
  6882. EXPECT_EQ("bar", req.get_param_value("param2"));
  6883. });
  6884. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6885. EXPECT_EQ("user-id", req.path_params.at("id"));
  6886. EXPECT_EQ("foo", req.get_param_value("param1"));
  6887. EXPECT_EQ("bar", req.get_param_value("param2"));
  6888. });
  6889. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6890. auto se = detail::scope_exit([&] {
  6891. svr.stop();
  6892. listen_thread.join();
  6893. ASSERT_FALSE(svr.is_running());
  6894. });
  6895. svr.wait_until_ready();
  6896. {
  6897. Client cli(HOST, PORT);
  6898. Params params;
  6899. params.emplace("hello", "world");
  6900. params.emplace("hello2", "world2");
  6901. params.emplace("hello3", "world3");
  6902. auto res = cli.Get("/", params, Headers{});
  6903. ASSERT_TRUE(res);
  6904. EXPECT_EQ(StatusCode::OK_200, res->status);
  6905. }
  6906. {
  6907. Client cli(HOST, PORT);
  6908. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6909. ASSERT_TRUE(res);
  6910. EXPECT_EQ(StatusCode::OK_200, res->status);
  6911. }
  6912. {
  6913. Client cli(HOST, PORT);
  6914. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6915. ASSERT_TRUE(res);
  6916. EXPECT_EQ(StatusCode::OK_200, res->status);
  6917. }
  6918. {
  6919. Client cli(HOST, PORT);
  6920. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6921. ASSERT_TRUE(res);
  6922. EXPECT_EQ(StatusCode::OK_200, res->status);
  6923. }
  6924. }
  6925. TEST(GetWithParametersTest, GetWithParameters2) {
  6926. Server svr;
  6927. svr.Get("/", [&](const Request &req, Response &res) {
  6928. auto text = req.get_param_value("hello");
  6929. res.set_content(text, "text/plain");
  6930. });
  6931. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6932. auto se = detail::scope_exit([&] {
  6933. svr.stop();
  6934. listen_thread.join();
  6935. ASSERT_FALSE(svr.is_running());
  6936. });
  6937. svr.wait_until_ready();
  6938. Client cli("localhost", PORT);
  6939. Params params;
  6940. params.emplace("hello", "world");
  6941. std::string body;
  6942. auto res = cli.Get("/", params, Headers{},
  6943. [&](const char *data, size_t data_length) {
  6944. body.append(data, data_length);
  6945. return true;
  6946. });
  6947. ASSERT_TRUE(res);
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. EXPECT_EQ("world", body);
  6950. }
  6951. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6952. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6953. auto host = "httpcan.org";
  6954. auto path = std::string{"/range/32"};
  6955. #else
  6956. auto host = "nghttp2.org";
  6957. auto path = std::string{"/httpbin/range/32"};
  6958. #endif
  6959. #ifdef CPPHTTPLIB_SSL_ENABLED
  6960. SSLClient cli(host);
  6961. #else
  6962. Client cli(host);
  6963. #endif
  6964. cli.set_default_headers({make_range_header({{1, 10}})});
  6965. cli.set_connection_timeout(5);
  6966. {
  6967. auto res = cli.Get(path);
  6968. ASSERT_TRUE(res);
  6969. EXPECT_EQ("bcdefghijk", res->body);
  6970. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6971. }
  6972. {
  6973. auto res = cli.Get(path);
  6974. ASSERT_TRUE(res);
  6975. EXPECT_EQ("bcdefghijk", res->body);
  6976. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6977. }
  6978. }
  6979. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6980. Server svr;
  6981. svr.set_default_headers({{"Hello", "World"}});
  6982. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6983. res.set_content("ok", "text/plain");
  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. auto res = cli.Get("/");
  6994. ASSERT_TRUE(res);
  6995. EXPECT_EQ(StatusCode::OK_200, res->status);
  6996. EXPECT_EQ("ok", res->body);
  6997. EXPECT_EQ("World", res->get_header_value("Hello"));
  6998. }
  6999. #ifdef CPPHTTPLIB_SSL_ENABLED
  7000. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7002. ASSERT_TRUE(svr.is_valid());
  7003. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7004. std::this_thread::sleep_for(std::chrono::seconds(2));
  7005. res.set_content("a", "text/plain");
  7006. });
  7007. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7008. res.set_content("b", "text/plain");
  7009. });
  7010. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7011. auto se = detail::scope_exit([&] {
  7012. svr.stop();
  7013. listen_thread.join();
  7014. ASSERT_FALSE(svr.is_running());
  7015. });
  7016. svr.wait_until_ready();
  7017. SSLClient cli("localhost", PORT);
  7018. cli.enable_server_certificate_verification(false);
  7019. cli.set_keep_alive(true);
  7020. cli.set_read_timeout(std::chrono::seconds(1));
  7021. auto resa = cli.Get("/a");
  7022. ASSERT_TRUE(!resa);
  7023. EXPECT_EQ(Error::Read, resa.error());
  7024. auto resb = cli.Get("/b");
  7025. ASSERT_TRUE(resb);
  7026. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7027. EXPECT_EQ("b", resb->body);
  7028. }
  7029. #endif
  7030. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7031. protected:
  7032. ServerTestWithAI_PASSIVE()
  7033. : cli_(HOST, PORT)
  7034. #ifdef CPPHTTPLIB_SSL_ENABLED
  7035. ,
  7036. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7037. #endif
  7038. {
  7039. #ifdef CPPHTTPLIB_SSL_ENABLED
  7040. cli_.enable_server_certificate_verification(false);
  7041. #endif
  7042. }
  7043. virtual void SetUp() {
  7044. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7045. res.set_content("Hello World!", "text/plain");
  7046. });
  7047. t_ = thread(
  7048. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7049. svr_.wait_until_ready();
  7050. }
  7051. virtual void TearDown() {
  7052. svr_.stop();
  7053. t_.join();
  7054. }
  7055. #ifdef CPPHTTPLIB_SSL_ENABLED
  7056. SSLClient cli_;
  7057. SSLServer svr_;
  7058. #else
  7059. Client cli_;
  7060. Server svr_;
  7061. #endif
  7062. thread t_;
  7063. };
  7064. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7065. auto res = cli_.Get("/hi");
  7066. ASSERT_TRUE(res);
  7067. EXPECT_EQ(StatusCode::OK_200, res->status);
  7068. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7069. EXPECT_EQ("Hello World!", res->body);
  7070. }
  7071. class ServerUpDownTest : public ::testing::Test {
  7072. protected:
  7073. ServerUpDownTest() : cli_(HOST, PORT) {}
  7074. virtual void SetUp() {
  7075. t_ = thread([&]() {
  7076. svr_.bind_to_any_port(HOST);
  7077. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7078. ASSERT_TRUE(svr_.listen_after_bind());
  7079. });
  7080. svr_.wait_until_ready();
  7081. }
  7082. virtual void TearDown() {
  7083. svr_.stop();
  7084. t_.join();
  7085. }
  7086. Client cli_;
  7087. Server svr_;
  7088. thread t_;
  7089. };
  7090. TEST_F(ServerUpDownTest, QuickStartStop) {
  7091. // Should not crash, especially when run with
  7092. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7093. }
  7094. class PayloadMaxLengthTest : public ::testing::Test {
  7095. protected:
  7096. PayloadMaxLengthTest()
  7097. : cli_(HOST, PORT)
  7098. #ifdef CPPHTTPLIB_SSL_ENABLED
  7099. ,
  7100. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7101. #endif
  7102. {
  7103. #ifdef CPPHTTPLIB_SSL_ENABLED
  7104. cli_.enable_server_certificate_verification(false);
  7105. #endif
  7106. }
  7107. virtual void SetUp() {
  7108. svr_.set_payload_max_length(8);
  7109. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7110. res.set_content("test", "text/plain");
  7111. });
  7112. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7113. svr_.wait_until_ready();
  7114. }
  7115. virtual void TearDown() {
  7116. svr_.stop();
  7117. t_.join();
  7118. }
  7119. #ifdef CPPHTTPLIB_SSL_ENABLED
  7120. SSLClient cli_;
  7121. SSLServer svr_;
  7122. #else
  7123. Client cli_;
  7124. Server svr_;
  7125. #endif
  7126. thread t_;
  7127. };
  7128. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7129. auto res = cli_.Post("/test", "123456789", "text/plain");
  7130. ASSERT_TRUE(res);
  7131. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7132. res = cli_.Post("/test", "12345678", "text/plain");
  7133. ASSERT_TRUE(res);
  7134. EXPECT_EQ(StatusCode::OK_200, res->status);
  7135. }
  7136. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7137. // Test chunked encoding with payload exceeding the 8-byte limit
  7138. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7139. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7140. ASSERT_TRUE(res);
  7141. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7142. }
  7143. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7144. // Test chunked encoding with payload within the 8-byte limit
  7145. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7146. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7147. ASSERT_TRUE(res);
  7148. EXPECT_EQ(StatusCode::OK_200, res->status);
  7149. }
  7150. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7151. // Test using send_request to send chunked data exceeding payload limit
  7152. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7153. "Host: " +
  7154. std::string(HOST) + ":" + std::to_string(PORT) +
  7155. "\r\n"
  7156. "Transfer-Encoding: chunked\r\n"
  7157. "Connection: close\r\n"
  7158. "\r\n"
  7159. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7160. "0123456789\r\n"
  7161. "0\r\n" // End chunk
  7162. "\r\n";
  7163. std::string response;
  7164. bool result = send_request(1, chunked_request, &response);
  7165. if (!result) {
  7166. // If send_request fails, it might be because the server closed the
  7167. // connection due to payload limit enforcement, which is acceptable
  7168. SUCCEED()
  7169. << "Server rejected oversized chunked request (connection closed)";
  7170. } else {
  7171. // If we got a response, check if it's an error response or connection was
  7172. // closed early Short response length indicates connection was closed due to
  7173. // payload limit
  7174. if (response.length() <= 10) {
  7175. SUCCEED() << "Server closed connection for oversized chunked request";
  7176. } else {
  7177. // Check for error status codes
  7178. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7179. response.find("Payload Too Large") != std::string::npos ||
  7180. response.find("400") != std::string::npos);
  7181. }
  7182. }
  7183. }
  7184. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7185. // Test request without Content-Length header exceeding payload limit
  7186. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7187. "Host: " +
  7188. std::string(HOST) + ":" +
  7189. std::to_string(PORT) +
  7190. "\r\n"
  7191. "Connection: close\r\n"
  7192. "\r\n";
  7193. // Add payload exceeding the 8-byte limit
  7194. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7195. request_without_content_length += large_payload;
  7196. std::string response;
  7197. bool result = send_request(1, request_without_content_length, &response);
  7198. if (!result) {
  7199. // If send_request fails, server likely closed connection due to payload
  7200. // limit
  7201. SUCCEED() << "Server rejected oversized request without Content-Length "
  7202. "(connection closed)";
  7203. } else {
  7204. // Check if server responded with error or closed connection early
  7205. if (response.length() <= 10) {
  7206. SUCCEED() << "Server closed connection for oversized request without "
  7207. "Content-Length";
  7208. } else {
  7209. // Check for error status codes
  7210. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7211. response.find("Payload Too Large") != std::string::npos ||
  7212. response.find("400") != std::string::npos);
  7213. }
  7214. }
  7215. }
  7216. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7217. // Test request without Content-Length header within payload limit
  7218. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7219. "Host: " +
  7220. std::string(HOST) + ":" +
  7221. std::to_string(PORT) +
  7222. "\r\n"
  7223. "Connection: close\r\n"
  7224. "\r\n";
  7225. // Add payload within the 8-byte limit
  7226. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7227. request_without_content_length += small_payload;
  7228. std::string response;
  7229. bool result = send_request(1, request_without_content_length, &response);
  7230. // For requests without Content-Length, the server may have different behavior
  7231. // The key is that it should not reject due to payload limit for small
  7232. // payloads
  7233. if (result) {
  7234. // Check for any HTTP response (success or error, but not connection closed)
  7235. if (response.length() > 10) {
  7236. SUCCEED()
  7237. << "Server processed request without Content-Length within limit";
  7238. } else {
  7239. // Short response might indicate connection closed, which is acceptable
  7240. SUCCEED() << "Server closed connection for request without "
  7241. "Content-Length (acceptable behavior)";
  7242. }
  7243. } else {
  7244. // Connection failure might be due to protocol requirements
  7245. SUCCEED() << "Connection issue with request without Content-Length "
  7246. "(environment-specific)";
  7247. }
  7248. }
  7249. class LargePayloadMaxLengthTest : public ::testing::Test {
  7250. protected:
  7251. LargePayloadMaxLengthTest()
  7252. : cli_(HOST, PORT)
  7253. #ifdef CPPHTTPLIB_SSL_ENABLED
  7254. ,
  7255. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7256. #endif
  7257. {
  7258. #ifdef CPPHTTPLIB_SSL_ENABLED
  7259. cli_.enable_server_certificate_verification(false);
  7260. #endif
  7261. }
  7262. virtual void SetUp() {
  7263. // Set 10MB payload limit
  7264. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7265. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7266. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7267. res.set_content("Large payload test", "text/plain");
  7268. });
  7269. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7270. svr_.wait_until_ready();
  7271. }
  7272. virtual void TearDown() {
  7273. svr_.stop();
  7274. t_.join();
  7275. }
  7276. #ifdef CPPHTTPLIB_SSL_ENABLED
  7277. SSLClient cli_;
  7278. SSLServer svr_;
  7279. #else
  7280. Client cli_;
  7281. Server svr_;
  7282. #endif
  7283. thread t_;
  7284. };
  7285. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7286. // Test chunked encoding with payload within 10MB limit
  7287. std::string medium_payload(5 * 1024 * 1024,
  7288. 'A'); // 5MB payload, within 10MB limit
  7289. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7290. ASSERT_TRUE(res);
  7291. EXPECT_EQ(StatusCode::OK_200, res->status);
  7292. }
  7293. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7294. // Test chunked encoding with payload exceeding 10MB limit
  7295. std::string large_payload(12 * 1024 * 1024,
  7296. 'B'); // 12MB payload, exceeds 10MB limit
  7297. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7298. // Server may either return 413 or close the connection
  7299. if (res) {
  7300. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7301. } else {
  7302. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7303. }
  7304. }
  7305. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7306. // Test request without Content-Length header within 10MB limit
  7307. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7308. "Host: " +
  7309. std::string(HOST) + ":" +
  7310. std::to_string(PORT) +
  7311. "\r\n"
  7312. "Connection: close\r\n"
  7313. "\r\n";
  7314. // Add 1MB payload (within 10MB limit)
  7315. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7316. request_without_content_length += medium_payload;
  7317. std::string response;
  7318. bool result = send_request(5, request_without_content_length, &response);
  7319. if (result) {
  7320. // Should get a proper HTTP response for payloads within limit
  7321. if (response.length() > 10) {
  7322. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7323. "10MB limit";
  7324. } else {
  7325. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7326. "Content-Length)";
  7327. }
  7328. } else {
  7329. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7330. }
  7331. }
  7332. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7333. // Test request without Content-Length header exceeding 10MB limit
  7334. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7335. "Host: " +
  7336. std::string(HOST) + ":" +
  7337. std::to_string(PORT) +
  7338. "\r\n"
  7339. "Connection: close\r\n"
  7340. "\r\n";
  7341. // Add 12MB payload (exceeds 10MB limit)
  7342. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7343. request_without_content_length += large_payload;
  7344. std::string response;
  7345. bool result = send_request(10, request_without_content_length, &response);
  7346. if (!result) {
  7347. // Server should close connection due to payload limit
  7348. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7349. "(connection closed)";
  7350. } else {
  7351. // Check for error response
  7352. if (response.length() <= 10) {
  7353. SUCCEED()
  7354. << "Server closed connection for 12MB request exceeding 10MB limit";
  7355. } else {
  7356. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7357. response.find("Payload Too Large") != std::string::npos ||
  7358. response.find("400") != std::string::npos);
  7359. }
  7360. }
  7361. }
  7362. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7363. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7364. // path.
  7365. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7366. Server svr;
  7367. const size_t LIMIT = 64 * 1024; // 64KB
  7368. svr.set_payload_max_length(LIMIT);
  7369. size_t total = 0;
  7370. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7371. const ContentReader &content_reader) {
  7372. content_reader([&](const char * /*data*/, size_t len) {
  7373. total += len;
  7374. return true;
  7375. });
  7376. res.status = 200;
  7377. res.set_content("stream_ok", "text/plain");
  7378. });
  7379. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7380. auto se = detail::scope_exit([&] {
  7381. svr.stop();
  7382. thread.join();
  7383. ASSERT_FALSE(svr.is_running());
  7384. });
  7385. svr.wait_until_ready();
  7386. // Prepare 256KB raw data and gzip-compress it
  7387. std::string raw(256 * 1024, 'A');
  7388. std::string gz;
  7389. {
  7390. z_stream zs{};
  7391. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7392. Z_DEFAULT_STRATEGY);
  7393. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7394. zs.avail_in = static_cast<uInt>(raw.size());
  7395. char outbuf[4096];
  7396. int ret;
  7397. do {
  7398. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7399. zs.avail_out = sizeof(outbuf);
  7400. ret = deflate(&zs, Z_FINISH);
  7401. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7402. } while (ret != Z_STREAM_END);
  7403. deflateEnd(&zs);
  7404. }
  7405. Client cli(HOST, PORT);
  7406. cli.set_connection_timeout(std::chrono::seconds(5));
  7407. Headers headers = {{"Content-Encoding", "gzip"}};
  7408. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7409. "application/octet-stream");
  7410. ASSERT_TRUE(res);
  7411. // Server must reject oversized decompressed payloads with 413.
  7412. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7413. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7414. EXPECT_LE(total, LIMIT);
  7415. }
  7416. #endif
  7417. // Regression test for DoS vulnerability: a malicious server sending a response
  7418. // without Content-Length header must not cause unbounded memory consumption on
  7419. // the client side. The client should stop reading after a reasonable limit,
  7420. // similar to the server-side set_payload_max_length protection.
  7421. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7422. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7423. #ifndef _WIN32
  7424. signal(SIGPIPE, SIG_IGN);
  7425. #endif
  7426. auto server_thread = std::thread([] {
  7427. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7428. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7429. default_socket_options(srv);
  7430. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7431. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7432. sockaddr_in addr{};
  7433. addr.sin_family = AF_INET;
  7434. addr.sin_port = htons(PORT + 2);
  7435. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7436. int opt = 1;
  7437. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7438. #ifdef _WIN32
  7439. reinterpret_cast<const char *>(&opt),
  7440. #else
  7441. &opt,
  7442. #endif
  7443. sizeof(opt));
  7444. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7445. ::listen(srv, 1);
  7446. sockaddr_in cli_addr{};
  7447. socklen_t cli_len = sizeof(cli_addr);
  7448. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7449. if (cli != INVALID_SOCKET) {
  7450. char buf[4096];
  7451. ::recv(cli, buf, sizeof(buf), 0);
  7452. // Malicious response: no Content-Length, no chunked encoding
  7453. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7454. "Connection: close\r\n"
  7455. "\r\n";
  7456. ::send(cli,
  7457. #ifdef _WIN32
  7458. static_cast<const char *>(response_header.c_str()),
  7459. static_cast<int>(response_header.size()),
  7460. #else
  7461. response_header.c_str(), response_header.size(),
  7462. #endif
  7463. 0);
  7464. // Send 10MB of data
  7465. std::string chunk(64 * 1024, 'A');
  7466. size_t total_sent = 0;
  7467. while (total_sent < MALICIOUS_DATA_SIZE) {
  7468. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7469. auto sent = ::send(cli,
  7470. #ifdef _WIN32
  7471. static_cast<const char *>(chunk.c_str()),
  7472. static_cast<int>(to_send),
  7473. #else
  7474. chunk.c_str(), to_send,
  7475. #endif
  7476. 0);
  7477. if (sent <= 0) break;
  7478. total_sent += static_cast<size_t>(sent);
  7479. }
  7480. detail::close_socket(cli);
  7481. }
  7482. detail::close_socket(srv);
  7483. });
  7484. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7485. size_t total_read = 0;
  7486. {
  7487. Client cli("127.0.0.1", PORT + 2);
  7488. cli.set_read_timeout(5, 0);
  7489. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7490. auto stream = cli.open_stream("GET", "/malicious");
  7491. ASSERT_TRUE(stream.is_valid());
  7492. char buffer[64 * 1024];
  7493. ssize_t n;
  7494. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7495. total_read += static_cast<size_t>(n);
  7496. }
  7497. } // StreamHandle and Client destroyed here, closing the socket
  7498. server_thread.join();
  7499. // With set_payload_max_length, the client must stop reading before consuming
  7500. // all 10MB. The read loop should be cut off at or near the configured limit.
  7501. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7502. << "Client read " << total_read << " bytes, exceeding the configured "
  7503. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7504. }
  7505. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7506. // the entire response body without truncation.
  7507. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7508. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7509. #ifndef _WIN32
  7510. signal(SIGPIPE, SIG_IGN);
  7511. #endif
  7512. auto server_thread = std::thread([] {
  7513. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7514. default_socket_options(srv);
  7515. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7516. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7517. sockaddr_in addr{};
  7518. addr.sin_family = AF_INET;
  7519. addr.sin_port = htons(PORT + 2);
  7520. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7521. int opt = 1;
  7522. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7523. #ifdef _WIN32
  7524. reinterpret_cast<const char *>(&opt),
  7525. #else
  7526. &opt,
  7527. #endif
  7528. sizeof(opt));
  7529. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7530. ::listen(srv, 1);
  7531. sockaddr_in cli_addr{};
  7532. socklen_t cli_len = sizeof(cli_addr);
  7533. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7534. if (cli != INVALID_SOCKET) {
  7535. char buf[4096];
  7536. ::recv(cli, buf, sizeof(buf), 0);
  7537. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7538. "Connection: close\r\n"
  7539. "\r\n";
  7540. ::send(cli,
  7541. #ifdef _WIN32
  7542. static_cast<const char *>(response_header.c_str()),
  7543. static_cast<int>(response_header.size()),
  7544. #else
  7545. response_header.c_str(), response_header.size(),
  7546. #endif
  7547. 0);
  7548. std::string chunk(64 * 1024, 'A');
  7549. size_t total_sent = 0;
  7550. while (total_sent < DATA_SIZE) {
  7551. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7552. auto sent = ::send(cli,
  7553. #ifdef _WIN32
  7554. static_cast<const char *>(chunk.c_str()),
  7555. static_cast<int>(to_send),
  7556. #else
  7557. chunk.c_str(), to_send,
  7558. #endif
  7559. 0);
  7560. if (sent <= 0) break;
  7561. total_sent += static_cast<size_t>(sent);
  7562. }
  7563. #ifdef _WIN32
  7564. ::shutdown(cli, SD_SEND);
  7565. #else
  7566. ::shutdown(cli, SHUT_WR);
  7567. #endif
  7568. // Drain until the client closes its end, ensuring all data is delivered
  7569. char drain[1024];
  7570. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7571. detail::close_socket(cli);
  7572. }
  7573. detail::close_socket(srv);
  7574. });
  7575. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7576. size_t total_read = 0;
  7577. {
  7578. Client cli("127.0.0.1", PORT + 2);
  7579. cli.set_read_timeout(5, 0);
  7580. cli.set_payload_max_length(0); // 0 means no limit
  7581. auto stream = cli.open_stream("GET", "/data");
  7582. ASSERT_TRUE(stream.is_valid());
  7583. char buffer[64 * 1024];
  7584. ssize_t n;
  7585. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7586. total_read += static_cast<size_t>(n);
  7587. }
  7588. }
  7589. server_thread.join();
  7590. EXPECT_EQ(total_read, DATA_SIZE)
  7591. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7592. << " bytes without truncation, but only read " << total_read << " bytes.";
  7593. }
  7594. // Verify that content_receiver bypasses the default payload_max_length,
  7595. // allowing streaming downloads larger than 100MB without requiring an explicit
  7596. // set_payload_max_length call.
  7597. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7598. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7599. #ifndef _WIN32
  7600. signal(SIGPIPE, SIG_IGN);
  7601. #endif
  7602. auto server_thread = std::thread([] {
  7603. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7604. default_socket_options(srv);
  7605. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7606. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7607. sockaddr_in addr{};
  7608. addr.sin_family = AF_INET;
  7609. addr.sin_port = htons(PORT + 2);
  7610. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7611. int opt = 1;
  7612. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7613. #ifdef _WIN32
  7614. reinterpret_cast<const char *>(&opt),
  7615. #else
  7616. &opt,
  7617. #endif
  7618. sizeof(opt));
  7619. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7620. ::listen(srv, 1);
  7621. sockaddr_in cli_addr{};
  7622. socklen_t cli_len = sizeof(cli_addr);
  7623. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7624. if (cli != INVALID_SOCKET) {
  7625. char buf[4096];
  7626. ::recv(cli, buf, sizeof(buf), 0);
  7627. // Response with Content-Length larger than default 100MB limit
  7628. auto content_length = std::to_string(DATA_SIZE);
  7629. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7630. "Content-Length: " +
  7631. content_length +
  7632. "\r\n"
  7633. "Connection: close\r\n"
  7634. "\r\n";
  7635. ::send(cli,
  7636. #ifdef _WIN32
  7637. static_cast<const char *>(response_header.c_str()),
  7638. static_cast<int>(response_header.size()),
  7639. #else
  7640. response_header.c_str(), response_header.size(),
  7641. #endif
  7642. 0);
  7643. std::string chunk(64 * 1024, 'A');
  7644. size_t total_sent = 0;
  7645. while (total_sent < DATA_SIZE) {
  7646. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7647. auto sent = ::send(cli,
  7648. #ifdef _WIN32
  7649. static_cast<const char *>(chunk.c_str()),
  7650. static_cast<int>(to_send),
  7651. #else
  7652. chunk.c_str(), to_send,
  7653. #endif
  7654. 0);
  7655. if (sent <= 0) break;
  7656. total_sent += static_cast<size_t>(sent);
  7657. }
  7658. detail::close_socket(cli);
  7659. }
  7660. detail::close_socket(srv);
  7661. });
  7662. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7663. size_t total_received = 0;
  7664. {
  7665. Client cli("127.0.0.1", PORT + 2);
  7666. cli.set_read_timeout(10, 0);
  7667. // Do NOT call set_payload_max_length — use the default 100MB limit
  7668. auto res =
  7669. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7670. total_received += data_length;
  7671. return true;
  7672. });
  7673. ASSERT_TRUE(res);
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. }
  7676. server_thread.join();
  7677. EXPECT_EQ(total_received, DATA_SIZE)
  7678. << "With content_receiver, the client should read all " << DATA_SIZE
  7679. << " bytes despite the default 100MB payload_max_length, but only read "
  7680. << total_received << " bytes.";
  7681. }
  7682. // Verify that an explicit set_payload_max_length smaller than the response is
  7683. // enforced even when a content_receiver is used.
  7684. TEST(ClientVulnerabilityTest,
  7685. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7686. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7687. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7688. #ifndef _WIN32
  7689. signal(SIGPIPE, SIG_IGN);
  7690. #endif
  7691. auto server_thread = std::thread([] {
  7692. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7693. default_socket_options(srv);
  7694. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7695. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7696. sockaddr_in addr{};
  7697. addr.sin_family = AF_INET;
  7698. addr.sin_port = htons(PORT + 2);
  7699. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7700. int opt = 1;
  7701. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7702. #ifdef _WIN32
  7703. reinterpret_cast<const char *>(&opt),
  7704. #else
  7705. &opt,
  7706. #endif
  7707. sizeof(opt));
  7708. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7709. ::listen(srv, 1);
  7710. sockaddr_in cli_addr{};
  7711. socklen_t cli_len = sizeof(cli_addr);
  7712. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7713. if (cli != INVALID_SOCKET) {
  7714. char buf[4096];
  7715. ::recv(cli, buf, sizeof(buf), 0);
  7716. auto content_length = std::to_string(DATA_SIZE);
  7717. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7718. "Content-Length: " +
  7719. content_length +
  7720. "\r\n"
  7721. "Connection: close\r\n"
  7722. "\r\n";
  7723. ::send(cli,
  7724. #ifdef _WIN32
  7725. static_cast<const char *>(response_header.c_str()),
  7726. static_cast<int>(response_header.size()),
  7727. #else
  7728. response_header.c_str(), response_header.size(),
  7729. #endif
  7730. 0);
  7731. std::string chunk(64 * 1024, 'A');
  7732. size_t total_sent = 0;
  7733. while (total_sent < DATA_SIZE) {
  7734. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7735. auto sent = ::send(cli,
  7736. #ifdef _WIN32
  7737. static_cast<const char *>(chunk.c_str()),
  7738. static_cast<int>(to_send),
  7739. #else
  7740. chunk.c_str(), to_send,
  7741. #endif
  7742. 0);
  7743. if (sent <= 0) break;
  7744. total_sent += static_cast<size_t>(sent);
  7745. }
  7746. detail::close_socket(cli);
  7747. }
  7748. detail::close_socket(srv);
  7749. });
  7750. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7751. size_t total_received = 0;
  7752. {
  7753. Client cli("127.0.0.1", PORT + 2);
  7754. cli.set_read_timeout(10, 0);
  7755. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7756. auto res =
  7757. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7758. total_received += data_length;
  7759. return true;
  7760. });
  7761. // Should fail because 200MB exceeds the explicit 150MB limit
  7762. EXPECT_FALSE(res);
  7763. }
  7764. server_thread.join();
  7765. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7766. << "Client with content_receiver should respect the explicit "
  7767. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7768. << total_received << " bytes.";
  7769. }
  7770. // Verify that an explicit set_payload_max_length larger than the response
  7771. // allows the content_receiver to read all data successfully.
  7772. TEST(ClientVulnerabilityTest,
  7773. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7774. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7775. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7776. #ifndef _WIN32
  7777. signal(SIGPIPE, SIG_IGN);
  7778. #endif
  7779. auto server_thread = std::thread([] {
  7780. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7781. default_socket_options(srv);
  7782. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7783. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7784. sockaddr_in addr{};
  7785. addr.sin_family = AF_INET;
  7786. addr.sin_port = htons(PORT + 2);
  7787. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7788. int opt = 1;
  7789. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7790. #ifdef _WIN32
  7791. reinterpret_cast<const char *>(&opt),
  7792. #else
  7793. &opt,
  7794. #endif
  7795. sizeof(opt));
  7796. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7797. ::listen(srv, 1);
  7798. sockaddr_in cli_addr{};
  7799. socklen_t cli_len = sizeof(cli_addr);
  7800. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7801. if (cli != INVALID_SOCKET) {
  7802. char buf[4096];
  7803. ::recv(cli, buf, sizeof(buf), 0);
  7804. auto content_length = std::to_string(DATA_SIZE);
  7805. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7806. "Content-Length: " +
  7807. content_length +
  7808. "\r\n"
  7809. "Connection: close\r\n"
  7810. "\r\n";
  7811. ::send(cli,
  7812. #ifdef _WIN32
  7813. static_cast<const char *>(response_header.c_str()),
  7814. static_cast<int>(response_header.size()),
  7815. #else
  7816. response_header.c_str(), response_header.size(),
  7817. #endif
  7818. 0);
  7819. std::string chunk(64 * 1024, 'A');
  7820. size_t total_sent = 0;
  7821. while (total_sent < DATA_SIZE) {
  7822. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7823. auto sent = ::send(cli,
  7824. #ifdef _WIN32
  7825. static_cast<const char *>(chunk.c_str()),
  7826. static_cast<int>(to_send),
  7827. #else
  7828. chunk.c_str(), to_send,
  7829. #endif
  7830. 0);
  7831. if (sent <= 0) break;
  7832. total_sent += static_cast<size_t>(sent);
  7833. }
  7834. #ifdef _WIN32
  7835. ::shutdown(cli, SD_SEND);
  7836. #else
  7837. ::shutdown(cli, SHUT_WR);
  7838. #endif
  7839. char drain[1024];
  7840. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7841. detail::close_socket(cli);
  7842. }
  7843. detail::close_socket(srv);
  7844. });
  7845. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7846. size_t total_received = 0;
  7847. {
  7848. Client cli("127.0.0.1", PORT + 2);
  7849. cli.set_read_timeout(10, 0);
  7850. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7851. auto res =
  7852. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7853. total_received += data_length;
  7854. return true;
  7855. });
  7856. ASSERT_TRUE(res);
  7857. EXPECT_EQ(StatusCode::OK_200, res->status);
  7858. }
  7859. server_thread.join();
  7860. EXPECT_EQ(total_received, DATA_SIZE)
  7861. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7862. << " bytes (larger than " << DATA_SIZE
  7863. << " bytes response), content_receiver should read all data, but only "
  7864. "read "
  7865. << total_received << " bytes.";
  7866. }
  7867. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7868. // Regression test for "zip bomb" attack on the client side: a malicious server
  7869. // sends a small gzip-compressed response that decompresses to a huge payload.
  7870. // The client must enforce payload_max_length on the decompressed size.
  7871. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7872. constexpr size_t DECOMPRESSED_SIZE =
  7873. 10 * 1024 * 1024; // 10MB after decompression
  7874. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7875. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7876. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7877. std::string compressed;
  7878. {
  7879. httplib::detail::gzip_compressor compressor;
  7880. bool ok =
  7881. compressor.compress(uncompressed.data(), uncompressed.size(),
  7882. /*last=*/true, [&](const char *buf, size_t len) {
  7883. compressed.append(buf, len);
  7884. return true;
  7885. });
  7886. ASSERT_TRUE(ok);
  7887. }
  7888. // Sanity: compressed data should be much smaller than the decompressed size
  7889. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7890. #ifndef _WIN32
  7891. signal(SIGPIPE, SIG_IGN);
  7892. #endif
  7893. // Set up the listening socket in the main thread so the server is guaranteed
  7894. // to be ready before the client connects (eliminates race condition).
  7895. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7896. default_socket_options(srv);
  7897. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7898. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7899. sockaddr_in addr{};
  7900. addr.sin_family = AF_INET;
  7901. addr.sin_port = htons(PORT + 3);
  7902. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7903. int opt = 1;
  7904. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7905. #ifdef _WIN32
  7906. reinterpret_cast<const char *>(&opt),
  7907. #else
  7908. &opt,
  7909. #endif
  7910. sizeof(opt));
  7911. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7912. ASSERT_EQ(0, ::listen(srv, 1));
  7913. auto server_thread = std::thread([&compressed, srv] {
  7914. sockaddr_in cli_addr{};
  7915. socklen_t cli_len = sizeof(cli_addr);
  7916. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7917. if (cli != INVALID_SOCKET) {
  7918. // Read the full HTTP request (until \r\n\r\n)
  7919. char buf[4096];
  7920. size_t total = 0;
  7921. while (total < sizeof(buf)) {
  7922. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7923. if (n <= 0) break;
  7924. total += static_cast<size_t>(n);
  7925. // Check for end of headers
  7926. if (total >= 4) {
  7927. std::string req(buf, total);
  7928. if (req.find("\r\n\r\n") != std::string::npos) break;
  7929. }
  7930. }
  7931. // Malicious response: gzip-compressed body, no Content-Length
  7932. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7933. "Content-Encoding: gzip\r\n"
  7934. "Connection: close\r\n"
  7935. "\r\n";
  7936. ::send(cli,
  7937. #ifdef _WIN32
  7938. static_cast<const char *>(response_header.c_str()),
  7939. static_cast<int>(response_header.size()),
  7940. #else
  7941. response_header.c_str(), response_header.size(),
  7942. #endif
  7943. 0);
  7944. // Send the compressed payload (small on the wire, huge when decompressed)
  7945. size_t total_sent = 0;
  7946. while (total_sent < compressed.size()) {
  7947. auto to_send = std::min(compressed.size() - total_sent,
  7948. static_cast<size_t>(64 * 1024));
  7949. auto sent =
  7950. ::send(cli,
  7951. #ifdef _WIN32
  7952. static_cast<const char *>(compressed.c_str() + total_sent),
  7953. static_cast<int>(to_send),
  7954. #else
  7955. compressed.c_str() + total_sent, to_send,
  7956. #endif
  7957. 0);
  7958. if (sent <= 0) break;
  7959. total_sent += static_cast<size_t>(sent);
  7960. }
  7961. detail::close_socket(cli);
  7962. }
  7963. });
  7964. auto se = detail::scope_exit([&] {
  7965. detail::close_socket(srv);
  7966. server_thread.join();
  7967. });
  7968. size_t total_decompressed = 0;
  7969. {
  7970. Client cli("127.0.0.1", PORT + 3);
  7971. cli.set_read_timeout(5, 0);
  7972. cli.set_decompress(true);
  7973. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7974. auto stream = cli.open_stream("GET", "/zipbomb");
  7975. ASSERT_TRUE(stream.is_valid());
  7976. char buffer[64 * 1024];
  7977. ssize_t n;
  7978. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7979. total_decompressed += static_cast<size_t>(n);
  7980. }
  7981. }
  7982. // The decompressed size must be capped by payload_max_length. Without
  7983. // protection, the client would decompress the full 10MB from a tiny
  7984. // compressed payload, enabling a zip bomb DoS attack.
  7985. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7986. << "Client decompressed " << total_decompressed
  7987. << " bytes from a gzip response. The decompressed size should be "
  7988. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7989. }
  7990. #endif
  7991. TEST(HostAndPortPropertiesTest, NoSSL) {
  7992. httplib::Client cli("www.google.com", 1234);
  7993. ASSERT_EQ("www.google.com", cli.host());
  7994. ASSERT_EQ(1234, cli.port());
  7995. }
  7996. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7997. httplib::Client cli("www.google.com:1234");
  7998. ASSERT_EQ("www.google.com", cli.host());
  7999. ASSERT_EQ(1234, cli.port());
  8000. }
  8001. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8002. // Port number that overflows int — should not crash, client becomes invalid
  8003. httplib::Client cli("http://www.google.com:99999999999999999999");
  8004. ASSERT_FALSE(cli.is_valid());
  8005. }
  8006. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8007. // Port 99999 exceeds valid range (1-65535) — should not crash
  8008. httplib::Client cli("http://www.google.com:99999");
  8009. ASSERT_FALSE(cli.is_valid());
  8010. }
  8011. #ifdef CPPHTTPLIB_SSL_ENABLED
  8012. TEST(HostAndPortPropertiesTest, SSL) {
  8013. httplib::SSLClient cli("www.google.com");
  8014. ASSERT_EQ("www.google.com", cli.host());
  8015. ASSERT_EQ(443, cli.port());
  8016. }
  8017. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8018. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8019. std::string cert;
  8020. read_file(CA_CERT_FILE, cert);
  8021. httplib::SSLClient httplib_client("www.google.com");
  8022. // Load CA store first time
  8023. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8024. // Load CA store second time (update)
  8025. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8026. // Verify client is still valid and can make connections
  8027. httplib_client.enable_server_certificate_verification(true);
  8028. auto res = httplib_client.Get("/");
  8029. ASSERT_TRUE(res);
  8030. // Google may return 200 or 301 depending on various factors
  8031. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8032. res->status == StatusCode::MovedPermanently_301);
  8033. }
  8034. TEST(SSLClientTest, ServerNameIndication_Online) {
  8035. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8036. auto host = "httpcan.org";
  8037. auto path = std::string{"/get"};
  8038. #else
  8039. auto host = "nghttp2.org";
  8040. auto path = std::string{"/httpbin/get"};
  8041. #endif
  8042. SSLClient cli(host, 443);
  8043. auto res = cli.Get(path);
  8044. ASSERT_TRUE(res);
  8045. ASSERT_EQ(StatusCode::OK_200, res->status);
  8046. }
  8047. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8048. // Use a site that will cause SSL verification failure due to self-signed cert
  8049. SSLClient cli("self-signed.badssl.com", 443);
  8050. cli.enable_server_certificate_verification(true);
  8051. auto res = cli.Get("/");
  8052. ASSERT_TRUE(!res);
  8053. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8054. // Verify backend error is captured for SSLServerVerification
  8055. // This occurs when certificate verification fails
  8056. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8057. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8058. EXPECT_NE(0UL, res.ssl_backend_error());
  8059. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8060. // For OpenSSL, ssl_error is 0 for verification errors
  8061. EXPECT_EQ(0, res.ssl_error());
  8062. #if !defined(_WIN32) || \
  8063. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8064. // On non-Windows or when Windows Schannel is disabled, the error comes
  8065. // from OpenSSL's verification
  8066. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8067. res.ssl_backend_error());
  8068. #endif
  8069. #endif
  8070. }
  8071. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8072. // Use a site where hostname doesn't match the certificate
  8073. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8074. SSLClient cli("wrong.host.badssl.com", 443);
  8075. cli.enable_server_certificate_verification(true);
  8076. cli.enable_server_hostname_verification(true);
  8077. auto res = cli.Get("/");
  8078. ASSERT_TRUE(!res);
  8079. // The error type depends on when hostname verification occurs:
  8080. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8081. // - Mbed TLS: SSLServerVerification (during handshake)
  8082. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8083. res.error() == Error::SSLServerVerification);
  8084. // Verify backend error is captured for hostname verification failure
  8085. EXPECT_NE(0UL, res.ssl_backend_error());
  8086. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8087. // For OpenSSL, ssl_error is 0 for verification errors
  8088. EXPECT_EQ(0, res.ssl_error());
  8089. #if !defined(_WIN32) || \
  8090. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8091. // On non-Windows or when Windows Schannel is disabled, the error comes
  8092. // from OpenSSL's hostname verification
  8093. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8094. res.ssl_backend_error());
  8095. #endif
  8096. #endif
  8097. }
  8098. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8099. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8100. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8101. SSLClient cli("www.google.com", 443);
  8102. cli.enable_server_certificate_verification(true);
  8103. auto res = cli.Get("/");
  8104. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8105. }
  8106. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8107. SSLClient cli("www.google.com", 443);
  8108. cli.enable_server_certificate_verification(true);
  8109. cli.enable_windows_certificate_verification(false);
  8110. auto res = cli.Get("/");
  8111. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8112. }
  8113. #endif
  8114. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8115. Client cli("https://google.com");
  8116. auto res = cli.Get("/");
  8117. ASSERT_TRUE(res);
  8118. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8119. }
  8120. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8121. SSLClient cli("google.com");
  8122. cli.set_ca_cert_path(CA_CERT_FILE);
  8123. auto res = cli.Get("/");
  8124. ASSERT_TRUE(res);
  8125. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8126. }
  8127. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8128. SSLClient cli("google.com");
  8129. cli.enable_server_certificate_verification(true);
  8130. cli.set_ca_cert_path("hello");
  8131. auto res = cli.Get("/");
  8132. ASSERT_TRUE(!res);
  8133. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8134. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8135. // should be set
  8136. EXPECT_EQ(0, res.ssl_error());
  8137. // Verify backend error is captured for SSLLoadingCerts
  8138. // This error occurs when loading CA certificates fails
  8139. EXPECT_NE(0UL, res.ssl_backend_error());
  8140. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8141. // OpenSSL specific error codes:
  8142. // > openssl errstr 0x80000002
  8143. // error:80000002:system library::No such file or directory
  8144. // > openssl errstr 0xA000126
  8145. // error:0A000126:SSL routines::unexpected eof while reading
  8146. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8147. res.ssl_backend_error() == 0xA000126);
  8148. #endif
  8149. }
  8150. TEST(SSLClientTest, ServerCertificateVerification4) {
  8151. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8152. ASSERT_TRUE(svr.is_valid());
  8153. svr.Get("/test", [&](const Request &, Response &res) {
  8154. res.set_content("test", "text/plain");
  8155. svr.stop();
  8156. ASSERT_TRUE(true);
  8157. });
  8158. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8159. auto se = detail::scope_exit([&] {
  8160. t.join();
  8161. ASSERT_FALSE(svr.is_running());
  8162. });
  8163. svr.wait_until_ready();
  8164. SSLClient cli("127.0.0.1", PORT);
  8165. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8166. cli.enable_server_certificate_verification(true);
  8167. cli.set_connection_timeout(30);
  8168. auto res = cli.Get("/test");
  8169. ASSERT_TRUE(res);
  8170. ASSERT_EQ(StatusCode::OK_200, res->status);
  8171. }
  8172. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8173. std::string cert;
  8174. read_file(CA_CERT_FILE, cert);
  8175. SSLClient cli("google.com");
  8176. cli.load_ca_cert_store(cert.data(), cert.size());
  8177. const auto res = cli.Get("/");
  8178. ASSERT_TRUE(res);
  8179. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8180. }
  8181. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8182. // clang-format off
  8183. static constexpr char cert[] =
  8184. "GlobalSign Root CA\n"
  8185. "==================\n"
  8186. "-----BEGIN CERTIFICATE-----\n"
  8187. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8188. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8189. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8190. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8191. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8192. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8193. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8194. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8195. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8196. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8197. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8198. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8199. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8200. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8201. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8202. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8203. "-----END CERTIFICATE-----\n";
  8204. // clang-format on
  8205. SSLClient cli("google.com");
  8206. cli.load_ca_cert_store(cert, sizeof(cert));
  8207. const auto res = cli.Get("/");
  8208. ASSERT_TRUE(res);
  8209. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8210. }
  8211. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8212. SSLClient cli("www.youtube.com");
  8213. cli.set_ca_cert_path(CA_CERT_FILE);
  8214. cli.enable_server_certificate_verification(true);
  8215. cli.set_follow_location(true);
  8216. auto res = cli.Get("/");
  8217. ASSERT_TRUE(res);
  8218. ASSERT_EQ(StatusCode::OK_200, res->status);
  8219. }
  8220. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8221. SSLClient cli("wWw.YouTube.Com");
  8222. cli.set_ca_cert_path(CA_CERT_FILE);
  8223. cli.enable_server_certificate_verification(true);
  8224. cli.enable_server_hostname_verification(true);
  8225. cli.set_follow_location(true);
  8226. auto res = cli.Get("/");
  8227. ASSERT_TRUE(res);
  8228. ASSERT_EQ(StatusCode::OK_200, res->status);
  8229. }
  8230. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8231. SSLClient cli("gOoGlE.COm");
  8232. cli.enable_server_certificate_verification(true);
  8233. cli.enable_server_hostname_verification(true);
  8234. cli.set_follow_location(true);
  8235. auto res = cli.Get("/");
  8236. ASSERT_TRUE(res);
  8237. ASSERT_EQ(StatusCode::OK_200, res->status);
  8238. }
  8239. TEST(SSLClientTest, Issue2004_Online) {
  8240. Client client("https://google.com");
  8241. client.set_follow_location(true);
  8242. auto res = client.Get("/");
  8243. ASSERT_TRUE(res);
  8244. ASSERT_EQ(StatusCode::OK_200, res->status);
  8245. auto body = res->body;
  8246. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8247. }
  8248. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8249. // Create SSLClient with invalid cert/key to make is_valid() return false
  8250. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8251. "nonexistent_key.pem");
  8252. // is_valid() should be false due to cert loading failure
  8253. ASSERT_FALSE(cli.is_valid());
  8254. auto res = cli.Get("/");
  8255. ASSERT_FALSE(res);
  8256. EXPECT_EQ(Error::SSLConnection, res.error());
  8257. }
  8258. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8259. // Test for Issue #2251: SSL error not properly reported when client cert
  8260. // and key paths are swapped or mismatched
  8261. // This simulates the scenario where user accidentally swaps the cert and key
  8262. // files
  8263. // Using client cert file as private key and vice versa (completely wrong)
  8264. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8265. // Should fail validation due to cert/key mismatch
  8266. ASSERT_FALSE(cli.is_valid());
  8267. // Attempt to make a request should fail with proper error
  8268. auto res = cli.Get("/");
  8269. ASSERT_FALSE(res);
  8270. EXPECT_EQ(Error::SSLConnection, res.error());
  8271. // SSL error should be recorded in the Result object (this is the key fix for
  8272. // Issue #2251)
  8273. auto backend_error = res.ssl_backend_error();
  8274. EXPECT_NE(0u, backend_error);
  8275. }
  8276. // Tests cert/key mismatch detection at the TLS context level
  8277. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8278. // Test that using mismatched cert/key causes connection failure.
  8279. // We verify this at the SSLClient level rather than through internal
  8280. // TLS API functions.
  8281. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8282. cli.enable_server_certificate_verification(false);
  8283. cli.set_connection_timeout(2);
  8284. // The mismatch should cause a connection or handshake error
  8285. auto res = cli.Get("/test");
  8286. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8287. // Either way, the request should fail
  8288. EXPECT_FALSE(res);
  8289. }
  8290. #endif
  8291. #if 0
  8292. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8293. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8294. ASSERT_TRUE(cli != nullptr);
  8295. cli->set_address_family(AF_INET6);
  8296. cli->set_interface("en0");
  8297. auto res = cli->Get("/get");
  8298. ASSERT_TRUE(res);
  8299. ASSERT_EQ(StatusCode::OK_200, res->status);
  8300. }
  8301. #endif
  8302. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8303. #ifdef CPPHTTPLIB_SSL_ENABLED
  8304. void ClientCertPresent(
  8305. const std::string &client_cert_file,
  8306. const std::string &client_private_key_file,
  8307. const std::string &client_encrypted_private_key_pass = std::string()) {
  8308. using namespace httplib::tls;
  8309. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8310. CLIENT_CA_CERT_DIR);
  8311. ASSERT_TRUE(svr.is_valid());
  8312. svr.Get("/test", [&](const Request &req, Response &res) {
  8313. res.set_content("test", "text/plain");
  8314. auto cert = req.peer_cert();
  8315. ASSERT_TRUE(static_cast<bool>(cert));
  8316. std::string common_name = cert.subject_cn();
  8317. EXPECT_EQ("Common Name", common_name);
  8318. });
  8319. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8320. auto se = detail::scope_exit([&] {
  8321. svr.stop();
  8322. t.join();
  8323. ASSERT_FALSE(svr.is_running());
  8324. });
  8325. svr.wait_until_ready();
  8326. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8327. client_encrypted_private_key_pass);
  8328. cli.enable_server_certificate_verification(false);
  8329. cli.set_connection_timeout(30);
  8330. auto res = cli.Get("/test");
  8331. ASSERT_TRUE(res);
  8332. ASSERT_EQ(StatusCode::OK_200, res->status);
  8333. }
  8334. TEST(SSLClientServerTest, ClientCertPresent) {
  8335. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8336. }
  8337. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8338. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8339. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8340. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8341. }
  8342. // PEM memory-based constructor tests (works with all TLS backends)
  8343. void PemMemoryClientCertPresent(
  8344. const std::string &client_cert_file,
  8345. const std::string &client_private_key_file,
  8346. const std::string &client_encrypted_private_key_pass = std::string()) {
  8347. // Read PEM files into memory
  8348. std::string server_cert_pem, server_key_pem;
  8349. std::string client_ca_pem;
  8350. std::string client_cert_pem, client_key_pem;
  8351. read_file(SERVER_CERT_FILE, server_cert_pem);
  8352. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8353. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8354. read_file(client_cert_file, client_cert_pem);
  8355. read_file(client_private_key_file, client_key_pem);
  8356. // Create server with PEM memory
  8357. SSLServer::PemMemory server_pem = {
  8358. server_cert_pem.c_str(),
  8359. server_cert_pem.size(),
  8360. server_key_pem.c_str(),
  8361. server_key_pem.size(),
  8362. client_ca_pem.c_str(),
  8363. client_ca_pem.size(),
  8364. nullptr // no password for server key
  8365. };
  8366. SSLServer svr(server_pem);
  8367. ASSERT_TRUE(svr.is_valid());
  8368. svr.Get("/test", [&](const Request &, Response &res) {
  8369. res.set_content("test", "text/plain");
  8370. });
  8371. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8372. auto se = detail::scope_exit([&] {
  8373. svr.stop();
  8374. t.join();
  8375. ASSERT_FALSE(svr.is_running());
  8376. });
  8377. svr.wait_until_ready();
  8378. // Create client with PEM memory
  8379. const char *password = client_encrypted_private_key_pass.empty()
  8380. ? nullptr
  8381. : client_encrypted_private_key_pass.c_str();
  8382. SSLClient::PemMemory client_pem = {
  8383. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8384. client_key_pem.size(), password};
  8385. SSLClient cli(HOST, PORT, client_pem);
  8386. cli.enable_server_certificate_verification(false);
  8387. cli.set_connection_timeout(30);
  8388. auto res = cli.Get("/test");
  8389. ASSERT_TRUE(res);
  8390. ASSERT_EQ(StatusCode::OK_200, res->status);
  8391. }
  8392. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8393. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8394. }
  8395. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8396. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8397. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8398. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8399. }
  8400. TEST(SSLClientServerTest, ClientCertMissing) {
  8401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8402. CLIENT_CA_CERT_DIR);
  8403. ASSERT_TRUE(svr.is_valid());
  8404. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8405. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8406. auto se = detail::scope_exit([&] {
  8407. svr.stop();
  8408. t.join();
  8409. ASSERT_FALSE(svr.is_running());
  8410. });
  8411. svr.wait_until_ready();
  8412. SSLClient cli(HOST, PORT);
  8413. cli.set_connection_timeout(30);
  8414. auto res = cli.Get("/test");
  8415. ASSERT_TRUE(!res);
  8416. // When client cert is missing and server requires it, connection fails
  8417. // Error type depends on backend implementation
  8418. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8419. res.error() == Error::SSLConnection);
  8420. // Verify backend error is captured
  8421. // Note: This test may have different error codes depending on the exact
  8422. // verification failure
  8423. EXPECT_NE(0UL, res.ssl_backend_error());
  8424. }
  8425. TEST(SSLClientServerTest, TrustDirOptional) {
  8426. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8427. ASSERT_TRUE(svr.is_valid());
  8428. svr.Get("/test", [&](const Request &, Response &res) {
  8429. res.set_content("test", "text/plain");
  8430. });
  8431. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8432. auto se = detail::scope_exit([&] {
  8433. svr.stop();
  8434. t.join();
  8435. ASSERT_FALSE(svr.is_running());
  8436. });
  8437. svr.wait_until_ready();
  8438. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8439. cli.enable_server_certificate_verification(false);
  8440. cli.set_connection_timeout(30);
  8441. auto res = cli.Get("/test");
  8442. ASSERT_TRUE(res);
  8443. ASSERT_EQ(StatusCode::OK_200, res->status);
  8444. }
  8445. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8446. class NoListenSSLServer : public SSLServer {
  8447. public:
  8448. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8449. const char *client_ca_cert_file_path,
  8450. const char *client_ca_cert_dir_path = nullptr)
  8451. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8452. client_ca_cert_dir_path),
  8453. stop_(false) {}
  8454. std::atomic_bool stop_;
  8455. private:
  8456. bool process_and_close_socket(socket_t /*sock*/) override {
  8457. // Don't create SSL context
  8458. while (!stop_.load()) {
  8459. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8460. }
  8461. return true;
  8462. }
  8463. };
  8464. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8465. CLIENT_CA_CERT_FILE);
  8466. ASSERT_TRUE(svr.is_valid());
  8467. svr.Get("/test", [&](const Request &, Response &res) {
  8468. res.set_content("test", "text/plain");
  8469. });
  8470. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8471. auto se = detail::scope_exit([&] {
  8472. svr.stop_ = true;
  8473. svr.stop();
  8474. t.join();
  8475. ASSERT_FALSE(svr.is_running());
  8476. });
  8477. svr.wait_until_ready();
  8478. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8479. cli.enable_server_certificate_verification(false);
  8480. cli.set_connection_timeout(1);
  8481. auto res = cli.Get("/test");
  8482. ASSERT_TRUE(!res);
  8483. EXPECT_EQ(Error::SSLConnection, res.error());
  8484. // Timeout results in WantRead error code (maps to backend-specific value)
  8485. EXPECT_NE(0, res.ssl_error());
  8486. }
  8487. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8488. // Test SSLServer with client certificate verification using the standard
  8489. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8491. CLIENT_CA_CERT_DIR);
  8492. ASSERT_TRUE(svr.is_valid());
  8493. svr.Get("/test", [&](const Request &req, Response &res) {
  8494. res.set_content("test", "text/plain");
  8495. auto cert = req.peer_cert();
  8496. ASSERT_TRUE(static_cast<bool>(cert));
  8497. auto common_name = cert.subject_cn();
  8498. EXPECT_EQ("Common Name", common_name);
  8499. });
  8500. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8501. auto se = detail::scope_exit([&] {
  8502. svr.stop();
  8503. t.join();
  8504. ASSERT_FALSE(svr.is_running());
  8505. });
  8506. svr.wait_until_ready();
  8507. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8508. cli.enable_server_certificate_verification(false);
  8509. cli.set_connection_timeout(30);
  8510. auto res = cli.Get("/test");
  8511. ASSERT_TRUE(res);
  8512. ASSERT_EQ(StatusCode::OK_200, res->status);
  8513. }
  8514. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8515. // Verifies that wildcard matching and exact matching work consistently
  8516. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8517. using namespace httplib::tls;
  8518. // We need a running server to test against
  8519. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8520. ASSERT_TRUE(svr.is_valid());
  8521. svr.Get("/test", [](const Request &, Response &res) {
  8522. res.set_content("ok", "text/plain");
  8523. });
  8524. thread t([&]() { svr.listen(HOST, PORT); });
  8525. auto se = detail::scope_exit([&] {
  8526. svr.stop();
  8527. t.join();
  8528. });
  8529. svr.wait_until_ready();
  8530. bool verify_callback_called = false;
  8531. bool verify_result_wrong = false;
  8532. SSLClient cli(HOST, PORT);
  8533. cli.enable_server_certificate_verification(true);
  8534. cli.set_ca_cert_path(CA_CERT_FILE);
  8535. cli.set_connection_timeout(5);
  8536. // Note: Test certificate has CN="Common Name", not "localhost"
  8537. bool verify_result_cn = false;
  8538. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8539. verify_callback_called = true;
  8540. if (!ctx.cert) return false;
  8541. // Test 1: "Common Name" should match (our test server cert CN)
  8542. verify_result_cn = ctx.check_hostname("Common Name");
  8543. // Test 2: wrong hostname should not match
  8544. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8545. return true; // Accept for the purpose of this test
  8546. });
  8547. auto res = cli.Get("/test");
  8548. // The request may succeed or fail depending on cert configuration
  8549. // but the callback should have been called
  8550. ASSERT_TRUE(verify_callback_called)
  8551. << "Verify callback should have been called";
  8552. // CN="Common Name" should match our test certificate
  8553. EXPECT_TRUE(verify_result_cn)
  8554. << "verify_hostname should match 'Common Name' (certificate CN)";
  8555. // Wrong hostname should not match
  8556. EXPECT_FALSE(verify_result_wrong)
  8557. << "verify_hostname should not match 'wronghost.example.com'";
  8558. }
  8559. #endif
  8560. // mbedTLS-specific callback constructor test
  8561. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8562. #ifdef CPPHTTPLIB_SSL_ENABLED
  8563. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8564. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8565. ASSERT_TRUE(svr.is_valid());
  8566. // Set up a handler to verify client certificate is present
  8567. bool client_cert_verified = false;
  8568. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8569. // Verify that client certificate was provided
  8570. client_cert_verified = true;
  8571. res.set_content("success", "text/plain");
  8572. });
  8573. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8574. auto se = detail::scope_exit([&] {
  8575. svr.stop();
  8576. t.join();
  8577. ASSERT_FALSE(svr.is_running());
  8578. });
  8579. svr.wait_until_ready();
  8580. // Client with certificate
  8581. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8582. cli.enable_server_certificate_verification(false);
  8583. cli.set_connection_timeout(30);
  8584. auto res = cli.Get("/test");
  8585. ASSERT_TRUE(res);
  8586. ASSERT_EQ(StatusCode::OK_200, res->status);
  8587. ASSERT_TRUE(client_cert_verified);
  8588. EXPECT_EQ("success", res->body);
  8589. }
  8590. #endif
  8591. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8592. // backends
  8593. #ifdef CPPHTTPLIB_SSL_ENABLED
  8594. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8595. using namespace httplib::tls;
  8596. // Test that when client CA cert file is provided,
  8597. // the server properly requests and validates client certificates
  8598. // Create a server with client authentication
  8599. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8600. ASSERT_TRUE(svr.is_valid());
  8601. bool handler_called = false;
  8602. svr.Get("/test", [&](const Request &req, Response &res) {
  8603. handler_called = true;
  8604. // Verify that a client certificate was provided
  8605. auto cert = req.peer_cert();
  8606. ASSERT_TRUE(static_cast<bool>(cert));
  8607. // Get the issuer name
  8608. std::string issuer_str = cert.issuer_name();
  8609. ASSERT_FALSE(issuer_str.empty());
  8610. // The client certificate should be issued by our test CA
  8611. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8612. res.set_content("authenticated", "text/plain");
  8613. });
  8614. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8615. auto se = detail::scope_exit([&] {
  8616. svr.stop();
  8617. t.join();
  8618. ASSERT_FALSE(svr.is_running());
  8619. });
  8620. svr.wait_until_ready();
  8621. // Connect with a client certificate issued by the CA
  8622. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8623. cli.enable_server_certificate_verification(false);
  8624. cli.set_connection_timeout(30);
  8625. auto res = cli.Get("/test");
  8626. ASSERT_TRUE(res);
  8627. ASSERT_EQ(StatusCode::OK_200, res->status);
  8628. ASSERT_TRUE(handler_called);
  8629. EXPECT_EQ("authenticated", res->body);
  8630. }
  8631. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8632. using namespace httplib::tls;
  8633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8634. ASSERT_TRUE(svr.is_valid());
  8635. svr.Get("/test", [](const Request &, Response &res) {
  8636. res.set_content("ok", "text/plain");
  8637. });
  8638. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8639. auto se = detail::scope_exit([&] {
  8640. svr.stop();
  8641. t.join();
  8642. });
  8643. svr.wait_until_ready();
  8644. SSLClient cli(HOST, PORT);
  8645. cli.enable_server_certificate_verification(false);
  8646. cli.set_connection_timeout(30);
  8647. bool cert_checked = false;
  8648. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8649. if (ctx.cert) {
  8650. auto sans = ctx.sans();
  8651. // Test certificate may or may not have SANs - just verify the API
  8652. // works If SANs exist, verify the types are valid
  8653. for (const auto &san : sans) {
  8654. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8655. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8656. san.type == SanType::OTHER);
  8657. EXPECT_FALSE(san.value.empty());
  8658. }
  8659. cert_checked = true;
  8660. }
  8661. return true;
  8662. });
  8663. auto res = cli.Get("/test");
  8664. ASSERT_TRUE(res);
  8665. EXPECT_TRUE(cert_checked);
  8666. }
  8667. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8668. using namespace httplib::tls;
  8669. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8670. ASSERT_TRUE(svr.is_valid());
  8671. svr.Get("/test", [](const Request &, Response &res) {
  8672. res.set_content("ok", "text/plain");
  8673. });
  8674. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8675. auto se = detail::scope_exit([&] {
  8676. svr.stop();
  8677. t.join();
  8678. });
  8679. svr.wait_until_ready();
  8680. SSLClient cli(HOST, PORT);
  8681. cli.enable_server_certificate_verification(false);
  8682. cli.set_connection_timeout(30);
  8683. bool validity_checked = false;
  8684. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8685. if (ctx.cert) {
  8686. time_t not_before = 0, not_after = 0;
  8687. bool result = ctx.validity(not_before, not_after);
  8688. EXPECT_TRUE(result);
  8689. // Verify that not_before < now < not_after for a valid cert
  8690. time_t now = time(nullptr);
  8691. EXPECT_LT(not_before, now);
  8692. EXPECT_GT(not_after, now);
  8693. validity_checked = true;
  8694. }
  8695. return true;
  8696. });
  8697. auto res = cli.Get("/test");
  8698. ASSERT_TRUE(res);
  8699. EXPECT_TRUE(validity_checked);
  8700. }
  8701. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8702. using namespace httplib::tls;
  8703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8704. ASSERT_TRUE(svr.is_valid());
  8705. svr.Get("/test", [](const Request &, Response &res) {
  8706. res.set_content("ok", "text/plain");
  8707. });
  8708. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8709. auto se = detail::scope_exit([&] {
  8710. svr.stop();
  8711. t.join();
  8712. });
  8713. svr.wait_until_ready();
  8714. SSLClient cli(HOST, PORT);
  8715. cli.enable_server_certificate_verification(false);
  8716. cli.set_connection_timeout(30);
  8717. bool serial_checked = false;
  8718. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8719. if (ctx.cert) {
  8720. std::string serial = ctx.serial();
  8721. EXPECT_FALSE(serial.empty());
  8722. // Serial should be a hex string
  8723. for (char c : serial) {
  8724. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8725. (c >= 'a' && c <= 'f'));
  8726. }
  8727. serial_checked = true;
  8728. }
  8729. return true;
  8730. });
  8731. auto res = cli.Get("/test");
  8732. ASSERT_TRUE(res);
  8733. EXPECT_TRUE(serial_checked);
  8734. }
  8735. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8736. // Test 1: Valid CA file - no error should be recorded
  8737. {
  8738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8739. CLIENT_CA_CERT_FILE);
  8740. ASSERT_TRUE(svr.is_valid());
  8741. // With valid setup, last_ssl_error should be 0
  8742. EXPECT_EQ(0, svr.ssl_last_error());
  8743. }
  8744. // Test 2: Invalid CA file content
  8745. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8746. {
  8747. // Create a temporary file with completely invalid content
  8748. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8749. {
  8750. std::ofstream ofs(temp_invalid_ca);
  8751. ofs << "This is not a certificate file at all\n";
  8752. ofs << "Just plain text content\n";
  8753. }
  8754. // Create server with invalid CA file
  8755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8756. // Clean up temporary file
  8757. std::remove(temp_invalid_ca);
  8758. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8759. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8760. // Note: SSL_CTX_load_verify_locations typically fails first,
  8761. // but our error handling code path is still exercised
  8762. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8763. }
  8764. }
  8765. TEST(VerifyCallbackTest, VerifyContextFields) {
  8766. using namespace httplib::tls;
  8767. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8768. ASSERT_TRUE(svr.is_valid());
  8769. svr.Get("/test", [](const Request &, Response &res) {
  8770. res.set_content("ok", "text/plain");
  8771. });
  8772. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8773. auto se = detail::scope_exit([&] {
  8774. svr.stop();
  8775. t.join();
  8776. });
  8777. svr.wait_until_ready();
  8778. SSLClient cli(HOST, PORT);
  8779. cli.enable_server_certificate_verification(false);
  8780. cli.set_connection_timeout(30);
  8781. int callback_count = 0;
  8782. bool saw_leaf_cert = false;
  8783. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8784. if (ctx.cert) {
  8785. callback_count++;
  8786. // We should see at least one certificate (the leaf)
  8787. std::string cn = ctx.subject_cn();
  8788. if (!cn.empty()) { saw_leaf_cert = true; }
  8789. // Verify context fields are populated
  8790. EXPECT_NE(ctx.session, nullptr);
  8791. EXPECT_GE(ctx.depth, 0);
  8792. }
  8793. return true;
  8794. });
  8795. auto res = cli.Get("/test");
  8796. ASSERT_TRUE(res);
  8797. EXPECT_GT(callback_count, 0);
  8798. EXPECT_TRUE(saw_leaf_cert);
  8799. }
  8800. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8801. using httplib::tls::TlsError;
  8802. // Test that verify_error_to_string returns empty for success
  8803. std::string success_str = TlsError::verify_error_to_string(0);
  8804. EXPECT_TRUE(success_str.empty());
  8805. // Test that verify_error_to_string returns non-empty for error codes
  8806. // Using a common error code (certificate expired)
  8807. std::string error_str =
  8808. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8809. EXPECT_FALSE(error_str.empty());
  8810. }
  8811. TEST(SessionVerifierTest, CertificateAccepted) {
  8812. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8813. ASSERT_TRUE(svr.is_valid());
  8814. svr.Get("/test", [](const Request &, Response &res) {
  8815. res.set_content("ok", "text/plain");
  8816. });
  8817. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8818. auto se = detail::scope_exit([&] {
  8819. svr.stop();
  8820. t.join();
  8821. });
  8822. svr.wait_until_ready();
  8823. SSLClient cli(HOST, PORT);
  8824. cli.enable_server_certificate_verification(false);
  8825. cli.set_connection_timeout(30);
  8826. bool callback_called = false;
  8827. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8828. EXPECT_NE(session, nullptr);
  8829. callback_called = true;
  8830. return SSLVerifierResponse::CertificateAccepted;
  8831. });
  8832. auto res = cli.Get("/test");
  8833. ASSERT_TRUE(res);
  8834. EXPECT_EQ(200, res->status);
  8835. EXPECT_TRUE(callback_called);
  8836. }
  8837. TEST(SessionVerifierTest, CertificateRejected) {
  8838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8839. ASSERT_TRUE(svr.is_valid());
  8840. svr.Get("/test", [](const Request &, Response &res) {
  8841. res.set_content("ok", "text/plain");
  8842. });
  8843. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8844. auto se = detail::scope_exit([&] {
  8845. svr.stop();
  8846. t.join();
  8847. });
  8848. svr.wait_until_ready();
  8849. SSLClient cli(HOST, PORT);
  8850. cli.enable_server_certificate_verification(false);
  8851. cli.set_connection_timeout(30);
  8852. bool callback_called = false;
  8853. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8854. EXPECT_NE(session, nullptr);
  8855. callback_called = true;
  8856. return SSLVerifierResponse::CertificateRejected;
  8857. });
  8858. auto res = cli.Get("/test");
  8859. EXPECT_FALSE(res);
  8860. EXPECT_TRUE(callback_called);
  8861. }
  8862. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8863. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8864. ASSERT_TRUE(svr.is_valid());
  8865. svr.Get("/test", [](const Request &, Response &res) {
  8866. res.set_content("ok", "text/plain");
  8867. });
  8868. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8869. auto se = detail::scope_exit([&] {
  8870. svr.stop();
  8871. t.join();
  8872. });
  8873. svr.wait_until_ready();
  8874. // NoDecisionMade with verification disabled should succeed (no default check)
  8875. SSLClient cli(HOST, PORT);
  8876. cli.enable_server_certificate_verification(false);
  8877. cli.set_connection_timeout(30);
  8878. bool callback_called = false;
  8879. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8880. EXPECT_NE(session, nullptr);
  8881. callback_called = true;
  8882. return SSLVerifierResponse::NoDecisionMade;
  8883. });
  8884. auto res = cli.Get("/test");
  8885. ASSERT_TRUE(res);
  8886. EXPECT_EQ(200, res->status);
  8887. EXPECT_TRUE(callback_called);
  8888. }
  8889. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8891. ASSERT_TRUE(svr.is_valid());
  8892. svr.Get("/test", [](const Request &, Response &res) {
  8893. res.set_content("ok", "text/plain");
  8894. });
  8895. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8896. auto se = detail::scope_exit([&] {
  8897. svr.stop();
  8898. t.join();
  8899. });
  8900. svr.wait_until_ready();
  8901. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8902. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8903. // so we only check that the request fails, not whether the callback was
  8904. // called.
  8905. SSLClient cli(HOST, PORT);
  8906. cli.enable_server_certificate_verification(true);
  8907. cli.set_connection_timeout(30);
  8908. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8909. EXPECT_NE(session, nullptr);
  8910. return SSLVerifierResponse::NoDecisionMade;
  8911. });
  8912. auto res = cli.Get("/test");
  8913. EXPECT_FALSE(res);
  8914. }
  8915. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8916. // Test SSL server using PemMemory constructor with client CA certificates
  8917. // Read PEM files
  8918. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8919. read_file(SERVER_CERT_FILE, server_cert_pem);
  8920. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8921. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8922. // Create SSLServer with PemMemory constructor including client CA
  8923. SSLServer::PemMemory server_pem = {
  8924. server_cert_pem.c_str(),
  8925. server_cert_pem.size(),
  8926. server_key_pem.c_str(),
  8927. server_key_pem.size(),
  8928. client_ca_pem.c_str(),
  8929. client_ca_pem.size(),
  8930. nullptr // no password for server key
  8931. };
  8932. SSLServer svr(server_pem);
  8933. ASSERT_TRUE(svr.is_valid());
  8934. // No SSL error should be recorded for valid setup
  8935. EXPECT_EQ(0, svr.ssl_last_error());
  8936. // Set up server endpoints
  8937. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8938. res.set_content("ok", "text/plain");
  8939. });
  8940. // Start server in a thread
  8941. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8942. svr.wait_until_ready();
  8943. // Connect with client certificate (using constructor with paths)
  8944. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8945. cli.enable_server_certificate_verification(false);
  8946. auto res = cli.Get("/test-pem-ca");
  8947. ASSERT_TRUE(res);
  8948. EXPECT_EQ(200, res->status);
  8949. EXPECT_EQ("ok", res->body);
  8950. svr.stop();
  8951. server_thread.join();
  8952. }
  8953. #endif
  8954. #ifdef _WIN32
  8955. TEST(CleanupTest, WSACleanup) {
  8956. int ret = WSACleanup();
  8957. ASSERT_EQ(0, ret);
  8958. }
  8959. #endif
  8960. #ifndef CPPHTTPLIB_SSL_ENABLED
  8961. TEST(NoSSLSupport, SimpleInterface) {
  8962. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8963. }
  8964. #endif
  8965. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8966. TEST(InvalidScheme, SimpleInterface) {
  8967. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8968. }
  8969. #endif
  8970. TEST(NoScheme, SimpleInterface) {
  8971. Client cli("yahoo.com:80");
  8972. ASSERT_TRUE(cli.is_valid());
  8973. }
  8974. TEST(SendAPI, SimpleInterface_Online) {
  8975. Client cli("http://yahoo.com");
  8976. Request req;
  8977. req.method = "GET";
  8978. req.path = "/";
  8979. auto res = cli.send(req);
  8980. ASSERT_TRUE(res);
  8981. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8982. }
  8983. TEST(SendAPI, WithParamsInRequest) {
  8984. Server svr;
  8985. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8986. EXPECT_TRUE(req.has_param("test"));
  8987. EXPECT_EQ("test_value", req.get_param_value("test"));
  8988. });
  8989. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8990. auto se = detail::scope_exit([&] {
  8991. svr.stop();
  8992. t.join();
  8993. ASSERT_FALSE(svr.is_running());
  8994. });
  8995. svr.wait_until_ready();
  8996. Client cli(HOST, PORT);
  8997. {
  8998. Request req;
  8999. req.method = "GET";
  9000. req.path = "/";
  9001. req.params.emplace("test", "test_value");
  9002. auto res = cli.send(req);
  9003. ASSERT_TRUE(res);
  9004. }
  9005. {
  9006. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9007. ASSERT_TRUE(res);
  9008. }
  9009. }
  9010. TEST(ClientImplMethods, GetSocketTest) {
  9011. httplib::Server svr;
  9012. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9013. res.status = StatusCode::OK_200;
  9014. });
  9015. auto port = svr.bind_to_any_port("127.0.0.1");
  9016. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9017. auto se = detail::scope_exit([&] {
  9018. svr.stop();
  9019. thread.join();
  9020. ASSERT_FALSE(svr.is_running());
  9021. });
  9022. svr.wait_until_ready();
  9023. {
  9024. httplib::Client cli("127.0.0.1", port);
  9025. cli.set_keep_alive(true);
  9026. // Use the behavior of cpp-httplib of opening the connection
  9027. // only when the first request happens. If that changes,
  9028. // this test would be obsolete.
  9029. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9030. // This also implicitly tests the server. But other tests would fail much
  9031. // earlier than this one to be considered.
  9032. auto res = cli.Get("/");
  9033. ASSERT_TRUE(res);
  9034. EXPECT_EQ(StatusCode::OK_200, res->status);
  9035. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9036. }
  9037. }
  9038. #ifdef CPPHTTPLIB_SSL_ENABLED
  9039. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9040. Client cli("http://yahoo.com");
  9041. auto res = cli.Get("/");
  9042. ASSERT_TRUE(res);
  9043. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9044. cli.set_follow_location(true);
  9045. res = cli.Get("/");
  9046. ASSERT_TRUE(res);
  9047. EXPECT_EQ(StatusCode::OK_200, res->status);
  9048. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9049. }
  9050. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9051. Client cli("https://yahoo.com");
  9052. auto res = cli.Get("/");
  9053. ASSERT_TRUE(res);
  9054. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9055. cli.set_follow_location(true);
  9056. res = cli.Get("/");
  9057. ASSERT_TRUE(res);
  9058. EXPECT_EQ(StatusCode::OK_200, res->status);
  9059. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9060. }
  9061. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9062. Client cli("https://yahoo.com");
  9063. auto res = cli.Get("/");
  9064. ASSERT_TRUE(res);
  9065. ASSERT_FALSE(!res);
  9066. ASSERT_TRUE(res);
  9067. ASSERT_FALSE(res == nullptr);
  9068. ASSERT_TRUE(res != nullptr);
  9069. EXPECT_EQ(Error::Success, res.error());
  9070. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9071. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9072. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9073. cli.set_follow_location(true);
  9074. res = cli.Get("/");
  9075. ASSERT_TRUE(res);
  9076. EXPECT_EQ(Error::Success, res.error());
  9077. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9078. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9079. EXPECT_EQ(StatusCode::OK_200, res->status);
  9080. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9081. }
  9082. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9083. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9084. Client cli("https://cdnjs.cloudflare.com");
  9085. auto res =
  9086. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9087. ASSERT_TRUE(res);
  9088. EXPECT_EQ(StatusCode::OK_200, res->status);
  9089. EXPECT_EQ(287630U, res->body.size());
  9090. EXPECT_EQ("application/javascript; charset=utf-8",
  9091. res->get_header_value("Content-Type"));
  9092. }
  9093. #endif
  9094. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9095. #undef REDIR_HOST // Silence compiler warning
  9096. #define REDIR_HOST "https://httpbingo.org"
  9097. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9098. Client cli(REDIR_HOST);
  9099. cli.set_follow_location(true);
  9100. auto res =
  9101. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9102. ASSERT_TRUE(res);
  9103. EXPECT_EQ(StatusCode::OK_200, res->status);
  9104. }
  9105. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9106. Client cli(REDIR_HOST);
  9107. cli.set_follow_location(true);
  9108. Params params;
  9109. params.emplace("url", "http://example.com");
  9110. params.emplace("status_code", "302");
  9111. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9112. ASSERT_TRUE(res);
  9113. EXPECT_EQ(StatusCode::OK_200, res->status);
  9114. }
  9115. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9116. Client cli(REDIR_HOST);
  9117. cli.set_follow_location(true);
  9118. Params params;
  9119. params.emplace("url", "http://example.com");
  9120. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9121. ASSERT_TRUE(res);
  9122. EXPECT_EQ(StatusCode::OK_200, res->status);
  9123. }
  9124. TEST(HttpToHttpsRedirectTest, CertFile) {
  9125. auto ssl_port = PORT + 1;
  9126. Server svr;
  9127. ASSERT_TRUE(svr.is_valid());
  9128. svr.Get("/index", [&](const Request &, Response &res) {
  9129. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9130. "/index");
  9131. svr.stop();
  9132. });
  9133. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9134. ASSERT_TRUE(ssl_svr.is_valid());
  9135. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9136. res.set_content("test", "text/plain");
  9137. ssl_svr.stop();
  9138. });
  9139. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9140. thread t2 =
  9141. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9142. auto se = detail::scope_exit([&] {
  9143. t2.join();
  9144. t.join();
  9145. ASSERT_FALSE(svr.is_running());
  9146. });
  9147. svr.wait_until_ready();
  9148. ssl_svr.wait_until_ready();
  9149. Client cli("127.0.0.1", PORT);
  9150. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9151. cli.enable_server_certificate_verification(true);
  9152. cli.set_follow_location(true);
  9153. cli.set_connection_timeout(30);
  9154. auto res = cli.Get("/index");
  9155. ASSERT_TRUE(res);
  9156. ASSERT_EQ(StatusCode::OK_200, res->status);
  9157. }
  9158. TEST(SSLClientRedirectTest, CertFile) {
  9159. auto ssl_port = PORT + 1;
  9160. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9161. ASSERT_TRUE(ssl_svr1.is_valid());
  9162. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9163. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9164. "/index");
  9165. ssl_svr1.stop();
  9166. });
  9167. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9168. ASSERT_TRUE(ssl_svr2.is_valid());
  9169. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9170. res.set_content("test", "text/plain");
  9171. ssl_svr2.stop();
  9172. });
  9173. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9174. thread t2 =
  9175. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9176. auto se = detail::scope_exit([&] {
  9177. t2.join();
  9178. t.join();
  9179. ASSERT_FALSE(ssl_svr1.is_running());
  9180. });
  9181. ssl_svr1.wait_until_ready();
  9182. ssl_svr2.wait_until_ready();
  9183. SSLClient cli("127.0.0.1", PORT);
  9184. std::string cert;
  9185. read_file(SERVER_CERT2_FILE, cert);
  9186. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9187. cli.enable_server_certificate_verification(true);
  9188. cli.set_follow_location(true);
  9189. cli.set_connection_timeout(30);
  9190. auto res = cli.Get("/index");
  9191. ASSERT_TRUE(res);
  9192. ASSERT_EQ(StatusCode::OK_200, res->status);
  9193. }
  9194. #endif
  9195. #ifdef CPPHTTPLIB_SSL_ENABLED
  9196. // Test that set_ca_cert_store() skips system certs (consistent with
  9197. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9198. // should be trusted - system certs should NOT be loaded.
  9199. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9200. // Load a specific cert that is NOT a system CA cert
  9201. std::string cert;
  9202. read_file(SERVER_CERT2_FILE, cert);
  9203. SSLClient cli("google.com");
  9204. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9205. cli.enable_server_certificate_verification(true);
  9206. // This should FAIL because:
  9207. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9208. // 2. System certs should NOT be loaded when custom store is set
  9209. // If system certs WERE loaded, this would succeed
  9210. auto res = cli.Get("/");
  9211. ASSERT_FALSE(res);
  9212. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9213. }
  9214. TEST(MultipartFormDataTest, LargeData) {
  9215. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9216. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9217. const ContentReader &content_reader) {
  9218. if (req.is_multipart_form_data()) {
  9219. std::vector<FormData> items;
  9220. content_reader(
  9221. [&](const FormData &file) {
  9222. items.push_back(file);
  9223. return true;
  9224. },
  9225. [&](const char *data, size_t data_length) {
  9226. items.back().content.append(data, data_length);
  9227. return true;
  9228. });
  9229. EXPECT_TRUE(std::string(items[0].name) == "document");
  9230. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9231. EXPECT_TRUE(items[0].filename == "2MB_data");
  9232. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9233. EXPECT_TRUE(items[1].name == "hello");
  9234. EXPECT_TRUE(items[1].content == "world");
  9235. EXPECT_TRUE(items[1].filename == "");
  9236. EXPECT_TRUE(items[1].content_type == "");
  9237. } else {
  9238. std::string body;
  9239. content_reader([&](const char *data, size_t data_length) {
  9240. body.append(data, data_length);
  9241. return true;
  9242. });
  9243. }
  9244. });
  9245. auto port = svr.bind_to_any_port(HOST);
  9246. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9247. auto se = detail::scope_exit([&] {
  9248. svr.stop();
  9249. t.join();
  9250. ASSERT_FALSE(svr.is_running());
  9251. });
  9252. svr.wait_until_ready();
  9253. {
  9254. std::string data(1024 * 1024 * 2, '.');
  9255. std::stringstream buffer;
  9256. buffer << data;
  9257. SSLClient cli(HOST, port);
  9258. cli.enable_server_certificate_verification(false);
  9259. UploadFormDataItems items{
  9260. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9261. {"hello", "world", "", ""},
  9262. };
  9263. auto res = cli.Post("/post", items);
  9264. ASSERT_TRUE(res);
  9265. ASSERT_EQ(StatusCode::OK_200, res->status);
  9266. }
  9267. }
  9268. TEST(MultipartFormDataTest, DataProviderItems) {
  9269. std::random_device seed_gen;
  9270. std::mt19937 random(seed_gen());
  9271. std::string rand1;
  9272. rand1.resize(1000);
  9273. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9274. std::string rand2;
  9275. rand2.resize(3000);
  9276. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9277. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9278. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9279. const ContentReader &content_reader) {
  9280. ASSERT_FALSE(req.is_multipart_form_data());
  9281. std::string body;
  9282. content_reader([&](const char *data, size_t data_length) {
  9283. body.append(data, data_length);
  9284. return true;
  9285. });
  9286. EXPECT_EQ(body, "");
  9287. });
  9288. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9289. const ContentReader &content_reader) {
  9290. ASSERT_TRUE(req.is_multipart_form_data());
  9291. std::vector<FormData> items;
  9292. content_reader(
  9293. [&](const FormData &file) {
  9294. items.push_back(file);
  9295. return true;
  9296. },
  9297. [&](const char *data, size_t data_length) {
  9298. items.back().content.append(data, data_length);
  9299. return true;
  9300. });
  9301. ASSERT_TRUE(items.size() == 2);
  9302. EXPECT_EQ(std::string(items[0].name), "name1");
  9303. EXPECT_EQ(items[0].content, "Testing123");
  9304. EXPECT_EQ(items[0].filename, "filename1");
  9305. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9306. EXPECT_EQ(items[1].name, "name2");
  9307. EXPECT_EQ(items[1].content, "Testing456");
  9308. EXPECT_EQ(items[1].filename, "");
  9309. EXPECT_EQ(items[1].content_type, "");
  9310. });
  9311. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9312. const ContentReader &content_reader) {
  9313. ASSERT_TRUE(req.is_multipart_form_data());
  9314. std::vector<FormData> items;
  9315. content_reader(
  9316. [&](const FormData &file) {
  9317. items.push_back(file);
  9318. return true;
  9319. },
  9320. [&](const char *data, size_t data_length) {
  9321. items.back().content.append(data, data_length);
  9322. return true;
  9323. });
  9324. ASSERT_TRUE(items.size() == 2);
  9325. EXPECT_EQ(items[0].name, "name3");
  9326. EXPECT_EQ(items[0].content, rand1);
  9327. EXPECT_EQ(items[0].filename, "filename3");
  9328. EXPECT_EQ(items[0].content_type, "");
  9329. EXPECT_EQ(items[1].name, "name4");
  9330. EXPECT_EQ(items[1].content, rand2);
  9331. EXPECT_EQ(items[1].filename, "filename4");
  9332. EXPECT_EQ(items[1].content_type, "");
  9333. });
  9334. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9335. const ContentReader &content_reader) {
  9336. ASSERT_TRUE(req.is_multipart_form_data());
  9337. std::vector<FormData> items;
  9338. content_reader(
  9339. [&](const FormData &file) {
  9340. items.push_back(file);
  9341. return true;
  9342. },
  9343. [&](const char *data, size_t data_length) {
  9344. items.back().content.append(data, data_length);
  9345. return true;
  9346. });
  9347. ASSERT_TRUE(items.size() == 4);
  9348. EXPECT_EQ(std::string(items[0].name), "name1");
  9349. EXPECT_EQ(items[0].content, "Testing123");
  9350. EXPECT_EQ(items[0].filename, "filename1");
  9351. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9352. EXPECT_EQ(items[1].name, "name2");
  9353. EXPECT_EQ(items[1].content, "Testing456");
  9354. EXPECT_EQ(items[1].filename, "");
  9355. EXPECT_EQ(items[1].content_type, "");
  9356. EXPECT_EQ(items[2].name, "name3");
  9357. EXPECT_EQ(items[2].content, rand1);
  9358. EXPECT_EQ(items[2].filename, "filename3");
  9359. EXPECT_EQ(items[2].content_type, "");
  9360. EXPECT_EQ(items[3].name, "name4");
  9361. EXPECT_EQ(items[3].content, rand2);
  9362. EXPECT_EQ(items[3].filename, "filename4");
  9363. EXPECT_EQ(items[3].content_type, "");
  9364. });
  9365. auto port = svr.bind_to_any_port("localhost");
  9366. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9367. auto se = detail::scope_exit([&] {
  9368. svr.stop();
  9369. t.join();
  9370. ASSERT_FALSE(svr.is_running());
  9371. });
  9372. svr.wait_until_ready();
  9373. {
  9374. SSLClient cli("localhost", port);
  9375. cli.enable_server_certificate_verification(false);
  9376. UploadFormDataItems items{
  9377. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9378. {"name2", "Testing456", "", ""}, // not a file
  9379. };
  9380. {
  9381. auto res = cli.Post("/post-none", {}, {}, {});
  9382. ASSERT_TRUE(res);
  9383. ASSERT_EQ(StatusCode::OK_200, res->status);
  9384. }
  9385. FormDataProviderItems providers;
  9386. {
  9387. auto res =
  9388. cli.Post("/post-items", {}, items, providers); // empty providers
  9389. ASSERT_TRUE(res);
  9390. ASSERT_EQ(StatusCode::OK_200, res->status);
  9391. }
  9392. providers.push_back({"name3",
  9393. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9394. // test the offset is given correctly at each step
  9395. if (!offset)
  9396. sink.os.write(rand1.data(), 30);
  9397. else if (offset == 30)
  9398. sink.os.write(rand1.data() + 30, 300);
  9399. else if (offset == 330)
  9400. sink.os.write(rand1.data() + 330, 670);
  9401. else if (offset == rand1.size())
  9402. sink.done();
  9403. return true;
  9404. },
  9405. "filename3",
  9406. {}});
  9407. providers.push_back({"name4",
  9408. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9409. // test the offset is given correctly at each step
  9410. if (!offset)
  9411. sink.os.write(rand2.data(), 2000);
  9412. else if (offset == 2000)
  9413. sink.os.write(rand2.data() + 2000, 1);
  9414. else if (offset == 2001)
  9415. sink.os.write(rand2.data() + 2001, 999);
  9416. else if (offset == rand2.size())
  9417. sink.done();
  9418. return true;
  9419. },
  9420. "filename4",
  9421. {}});
  9422. {
  9423. auto res = cli.Post("/post-providers", {}, {}, providers);
  9424. ASSERT_TRUE(res);
  9425. ASSERT_EQ(StatusCode::OK_200, res->status);
  9426. }
  9427. {
  9428. auto res = cli.Post("/post-both", {}, items, providers);
  9429. ASSERT_TRUE(res);
  9430. ASSERT_EQ(StatusCode::OK_200, res->status);
  9431. }
  9432. }
  9433. }
  9434. TEST(MultipartFormDataTest, BadHeader) {
  9435. Server svr;
  9436. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9437. res.set_content("ok", "text/plain");
  9438. });
  9439. thread t = thread([&] { svr.listen(HOST, PORT); });
  9440. auto se = detail::scope_exit([&] {
  9441. svr.stop();
  9442. t.join();
  9443. ASSERT_FALSE(svr.is_running());
  9444. });
  9445. svr.wait_until_ready();
  9446. const std::string body =
  9447. "This is the preamble. It is to be ignored, though it\r\n"
  9448. "is a handy place for composition agents to include an\r\n"
  9449. "explanatory note to non-MIME conformant readers.\r\n"
  9450. "\r\n"
  9451. "\r\n"
  9452. "--simple boundary\r\n"
  9453. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9454. ": BAD...\r\n"
  9455. "\r\n"
  9456. "value1\r\n"
  9457. "--simple boundary\r\n"
  9458. "Content-Disposition: form-data; name=\"field2\"; "
  9459. "filename=\"example.txt\"\r\n"
  9460. "\r\n"
  9461. "value2\r\n"
  9462. "--simple boundary--\r\n"
  9463. "This is the epilogue. It is also to be ignored.\r\n";
  9464. std::string content_type =
  9465. R"(multipart/form-data; boundary="simple boundary")";
  9466. Client cli(HOST, PORT);
  9467. auto res = cli.Post("/post", body, content_type.c_str());
  9468. ASSERT_TRUE(res);
  9469. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9470. }
  9471. TEST(MultipartFormDataTest, WithPreamble) {
  9472. Server svr;
  9473. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9474. res.set_content("ok", "text/plain");
  9475. });
  9476. thread t = thread([&] { svr.listen(HOST, PORT); });
  9477. auto se = detail::scope_exit([&] {
  9478. svr.stop();
  9479. t.join();
  9480. ASSERT_FALSE(svr.is_running());
  9481. });
  9482. svr.wait_until_ready();
  9483. const std::string body =
  9484. "This is the preamble. It is to be ignored, though it\r\n"
  9485. "is a handy place for composition agents to include an\r\n"
  9486. "explanatory note to non-MIME conformant readers.\r\n"
  9487. "\r\n"
  9488. "\r\n"
  9489. "--simple boundary\r\n"
  9490. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9491. "\r\n"
  9492. "value1\r\n"
  9493. "--simple boundary\r\n"
  9494. "Content-Disposition: form-data; name=\"field2\"; "
  9495. "filename=\"example.txt\"\r\n"
  9496. "\r\n"
  9497. "value2\r\n"
  9498. "--simple boundary--\r\n"
  9499. "This is the epilogue. It is also to be ignored.\r\n";
  9500. std::string content_type =
  9501. R"(multipart/form-data; boundary="simple boundary")";
  9502. Client cli(HOST, PORT);
  9503. auto res = cli.Post("/post", body, content_type.c_str());
  9504. ASSERT_TRUE(res);
  9505. EXPECT_EQ(StatusCode::OK_200, res->status);
  9506. }
  9507. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9508. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9509. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9510. const ContentReader &content_reader) {
  9511. if (req.is_multipart_form_data()) {
  9512. std::vector<FormData> items;
  9513. content_reader(
  9514. [&](const FormData &file) {
  9515. items.push_back(file);
  9516. return true;
  9517. },
  9518. [&](const char *data, size_t data_length) {
  9519. items.back().content.append(data, data_length);
  9520. return true;
  9521. });
  9522. EXPECT_TRUE(std::string(items[0].name) == "document");
  9523. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9524. EXPECT_TRUE(items[0].filename == "2MB_data");
  9525. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9526. EXPECT_TRUE(items[1].name == "hello");
  9527. EXPECT_TRUE(items[1].content == "world");
  9528. EXPECT_TRUE(items[1].filename == "");
  9529. EXPECT_TRUE(items[1].content_type == "");
  9530. } else {
  9531. std::string body;
  9532. content_reader([&](const char *data, size_t data_length) {
  9533. body.append(data, data_length);
  9534. return true;
  9535. });
  9536. }
  9537. });
  9538. auto port = svr.bind_to_any_port("localhost");
  9539. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9540. auto se = detail::scope_exit([&] {
  9541. svr.stop();
  9542. t.join();
  9543. ASSERT_FALSE(svr.is_running());
  9544. });
  9545. svr.wait_until_ready();
  9546. {
  9547. std::string data(1024 * 1024 * 2, '.');
  9548. std::stringstream buffer;
  9549. buffer << data;
  9550. SSLClient cli("localhost", port);
  9551. cli.enable_server_certificate_verification(false);
  9552. UploadFormDataItems items{
  9553. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9554. {"hello", "world", "", ""},
  9555. };
  9556. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9557. ASSERT_TRUE(res);
  9558. ASSERT_EQ(StatusCode::OK_200, res->status);
  9559. }
  9560. }
  9561. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9562. std::string data(1024 * 1024 * 2, '&');
  9563. std::stringstream buffer;
  9564. buffer << data;
  9565. Client cli("https://localhost:8080");
  9566. UploadFormDataItems items{
  9567. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9568. {"hello", "world", "", ""},
  9569. };
  9570. for (const char &c : " \t\r\n") {
  9571. auto res =
  9572. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9573. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9574. ASSERT_FALSE(res);
  9575. }
  9576. }
  9577. TEST(MultipartFormDataTest, PutFormData) {
  9578. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9579. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9580. const ContentReader &content_reader) {
  9581. if (req.is_multipart_form_data()) {
  9582. std::vector<FormData> items;
  9583. content_reader(
  9584. [&](const FormData &file) {
  9585. items.push_back(file);
  9586. return true;
  9587. },
  9588. [&](const char *data, size_t data_length) {
  9589. items.back().content.append(data, data_length);
  9590. return true;
  9591. });
  9592. EXPECT_TRUE(std::string(items[0].name) == "document");
  9593. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9594. EXPECT_TRUE(items[0].filename == "2MB_data");
  9595. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9596. EXPECT_TRUE(items[1].name == "hello");
  9597. EXPECT_TRUE(items[1].content == "world");
  9598. EXPECT_TRUE(items[1].filename == "");
  9599. EXPECT_TRUE(items[1].content_type == "");
  9600. } else {
  9601. std::string body;
  9602. content_reader([&](const char *data, size_t data_length) {
  9603. body.append(data, data_length);
  9604. return true;
  9605. });
  9606. }
  9607. });
  9608. auto port = svr.bind_to_any_port("localhost");
  9609. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9610. auto se = detail::scope_exit([&] {
  9611. svr.stop();
  9612. t.join();
  9613. ASSERT_FALSE(svr.is_running());
  9614. });
  9615. svr.wait_until_ready();
  9616. {
  9617. std::string data(1024 * 1024 * 2, '&');
  9618. std::stringstream buffer;
  9619. buffer << data;
  9620. SSLClient cli("localhost", port);
  9621. cli.enable_server_certificate_verification(false);
  9622. UploadFormDataItems items{
  9623. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9624. {"hello", "world", "", ""},
  9625. };
  9626. auto res = cli.Put("/put", items);
  9627. ASSERT_TRUE(res);
  9628. ASSERT_EQ(StatusCode::OK_200, res->status);
  9629. }
  9630. }
  9631. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9633. svr.Put("/put_customboundary",
  9634. [&](const Request &req, const Response & /*res*/,
  9635. const ContentReader &content_reader) {
  9636. if (req.is_multipart_form_data()) {
  9637. std::vector<FormData> items;
  9638. content_reader(
  9639. [&](const FormData &file) {
  9640. items.push_back(file);
  9641. return true;
  9642. },
  9643. [&](const char *data, size_t data_length) {
  9644. items.back().content.append(data, data_length);
  9645. return true;
  9646. });
  9647. EXPECT_TRUE(std::string(items[0].name) == "document");
  9648. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9649. EXPECT_TRUE(items[0].filename == "2MB_data");
  9650. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9651. EXPECT_TRUE(items[1].name == "hello");
  9652. EXPECT_TRUE(items[1].content == "world");
  9653. EXPECT_TRUE(items[1].filename == "");
  9654. EXPECT_TRUE(items[1].content_type == "");
  9655. } else {
  9656. std::string body;
  9657. content_reader([&](const char *data, size_t data_length) {
  9658. body.append(data, data_length);
  9659. return true;
  9660. });
  9661. }
  9662. });
  9663. auto port = svr.bind_to_any_port("localhost");
  9664. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9665. auto se = detail::scope_exit([&] {
  9666. svr.stop();
  9667. t.join();
  9668. ASSERT_FALSE(svr.is_running());
  9669. });
  9670. svr.wait_until_ready();
  9671. {
  9672. std::string data(1024 * 1024 * 2, '&');
  9673. std::stringstream buffer;
  9674. buffer << data;
  9675. SSLClient cli("localhost", port);
  9676. cli.enable_server_certificate_verification(false);
  9677. UploadFormDataItems items{
  9678. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9679. {"hello", "world", "", ""},
  9680. };
  9681. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9682. ASSERT_TRUE(res);
  9683. ASSERT_EQ(StatusCode::OK_200, res->status);
  9684. }
  9685. }
  9686. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9687. std::string data(1024 * 1024 * 2, '&');
  9688. std::stringstream buffer;
  9689. buffer << data;
  9690. Client cli("https://localhost:8080");
  9691. cli.enable_server_certificate_verification(false);
  9692. UploadFormDataItems items{
  9693. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9694. {"hello", "world", "", ""},
  9695. };
  9696. for (const char &c : " \t\r\n") {
  9697. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9698. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9699. ASSERT_FALSE(res);
  9700. }
  9701. }
  9702. TEST(MultipartFormDataTest, AlternateFilename) {
  9703. auto handled = false;
  9704. Server svr;
  9705. svr.Post("/test", [&](const Request &req, Response &res) {
  9706. ASSERT_EQ(2u, req.form.files.size());
  9707. ASSERT_EQ(1u, req.form.fields.size());
  9708. // Test files
  9709. const auto &file1 = req.form.get_file("file1");
  9710. ASSERT_EQ("file1", file1.name);
  9711. ASSERT_EQ("A.txt", file1.filename);
  9712. ASSERT_EQ("text/plain", file1.content_type);
  9713. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9714. const auto &file2 = req.form.get_file("file2");
  9715. ASSERT_EQ("file2", file2.name);
  9716. ASSERT_EQ("a.html", file2.filename);
  9717. ASSERT_EQ("text/html", file2.content_type);
  9718. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9719. file2.content);
  9720. // Test text field
  9721. const auto &text = req.form.get_field("text");
  9722. ASSERT_EQ("text default", text);
  9723. res.set_content("ok", "text/plain");
  9724. handled = true;
  9725. });
  9726. thread t = thread([&] { svr.listen(HOST, PORT); });
  9727. auto se = detail::scope_exit([&] {
  9728. svr.stop();
  9729. t.join();
  9730. ASSERT_FALSE(svr.is_running());
  9731. ASSERT_TRUE(handled);
  9732. });
  9733. svr.wait_until_ready();
  9734. auto req = "POST /test HTTP/1.1\r\n"
  9735. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9736. "Content-Length: 399\r\n"
  9737. "\r\n"
  9738. "----------\r\n"
  9739. "Content-Disposition: form-data; name=\"text\"\r\n"
  9740. "\r\n"
  9741. "text default\r\n"
  9742. "----------\r\n"
  9743. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9744. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9745. "Content-Type: text/plain\r\n"
  9746. "\r\n"
  9747. "Content of a.txt.\r\n"
  9748. "\r\n"
  9749. "----------\r\n"
  9750. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9751. "\"a.html\"\r\n"
  9752. "Content-Type: text/html\r\n"
  9753. "\r\n"
  9754. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9755. "\r\n"
  9756. "------------\r\n";
  9757. ASSERT_TRUE(send_request(1, req));
  9758. }
  9759. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9760. auto handled = false;
  9761. Server svr;
  9762. svr.Post("/test", [&](const Request &req, Response &res) {
  9763. // Case-insensitive "utf-8''" prefix with a long value
  9764. const auto &file = req.form.get_file("file1");
  9765. ASSERT_EQ("file1", file.name);
  9766. // 8000 chars exercises both the Content-Disposition parser and the
  9767. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9768. // Prior to the fix, std::regex_match on this header would cause O(N)
  9769. // stack recursion in libstdc++, leading to SIGSEGV.
  9770. std::string expected_filename(8000, 'A');
  9771. ASSERT_EQ(expected_filename, file.filename);
  9772. res.set_content("ok", "text/plain");
  9773. handled = true;
  9774. });
  9775. thread t = thread([&] { svr.listen(HOST, PORT); });
  9776. auto se = detail::scope_exit([&] {
  9777. svr.stop();
  9778. t.join();
  9779. ASSERT_FALSE(svr.is_running());
  9780. ASSERT_TRUE(handled);
  9781. });
  9782. svr.wait_until_ready();
  9783. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9784. // Regression test for GHSA-qq6v-r583-3h69
  9785. std::string long_filename(8000, 'A');
  9786. std::string body = "----------\r\n"
  9787. "Content-Disposition: form-data; name=\"file1\"; "
  9788. "filename*=\"Utf-8''" +
  9789. long_filename +
  9790. "\"\r\n"
  9791. "\r\n"
  9792. "hello\r\n"
  9793. "------------\r\n";
  9794. auto req = "POST /test HTTP/1.1\r\n"
  9795. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9796. "Content-Length: " +
  9797. std::to_string(body.size()) + "\r\n\r\n" + body;
  9798. ASSERT_TRUE(send_request(1, req));
  9799. }
  9800. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9801. auto handled = false;
  9802. Server svr;
  9803. svr.Post("/test", [&](const Request &req, Response &) {
  9804. ASSERT_EQ(2u, req.form.fields.size());
  9805. const auto &text1 = req.form.get_field("text1");
  9806. ASSERT_EQ("text1", text1);
  9807. const auto &text2 = req.form.get_field("text2");
  9808. ASSERT_EQ("text2", text2);
  9809. handled = true;
  9810. });
  9811. thread t = thread([&] { svr.listen(HOST, PORT); });
  9812. auto se = detail::scope_exit([&] {
  9813. svr.stop();
  9814. t.join();
  9815. ASSERT_FALSE(svr.is_running());
  9816. ASSERT_TRUE(handled);
  9817. });
  9818. svr.wait_until_ready();
  9819. auto req = "POST /test HTTP/1.1\r\n"
  9820. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9821. "Content-Length: 146\r\n"
  9822. "\r\n----------\r\n"
  9823. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9824. "\r\n"
  9825. "text1"
  9826. "\r\n----------\r\n"
  9827. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9828. "\r\n"
  9829. "text2"
  9830. "\r\n------------";
  9831. std::string response;
  9832. ASSERT_TRUE(send_request(1, req, &response));
  9833. ASSERT_EQ("200", response.substr(9, 3));
  9834. }
  9835. TEST(MultipartFormDataTest, ContentLength) {
  9836. auto handled = false;
  9837. Server svr;
  9838. svr.Post("/test", [&](const Request &req, Response &) {
  9839. ASSERT_EQ(2u, req.form.fields.size());
  9840. const auto &text1 = req.form.get_field("text1");
  9841. ASSERT_EQ("text1", text1);
  9842. const auto &text2 = req.form.get_field("text2");
  9843. ASSERT_EQ("text2", text2);
  9844. handled = true;
  9845. });
  9846. thread t = thread([&] { svr.listen(HOST, PORT); });
  9847. auto se = detail::scope_exit([&] {
  9848. svr.stop();
  9849. t.join();
  9850. ASSERT_FALSE(svr.is_running());
  9851. ASSERT_TRUE(handled);
  9852. });
  9853. svr.wait_until_ready();
  9854. auto req = "POST /test HTTP/1.1\r\n"
  9855. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9856. "Content-Length: 167\r\n"
  9857. "\r\n----------\r\n"
  9858. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9859. "Content-Length: 5\r\n"
  9860. "\r\n"
  9861. "text1"
  9862. "\r\n----------\r\n"
  9863. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9864. "\r\n"
  9865. "text2"
  9866. "\r\n------------\r\n";
  9867. std::string response;
  9868. ASSERT_TRUE(send_request(1, req, &response));
  9869. ASSERT_EQ("200", response.substr(9, 3));
  9870. }
  9871. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9872. auto handled = false;
  9873. Server svr;
  9874. svr.Post("/test", [&](const Request &req, Response &) {
  9875. ASSERT_EQ(2u, req.form.fields.size());
  9876. const auto &text1 = req.form.get_field("text1");
  9877. ASSERT_EQ("text1", text1);
  9878. // TODO: Add header access for text fields if needed
  9879. const auto &text2 = req.form.get_field("text2");
  9880. ASSERT_EQ("text2", text2);
  9881. // TODO: Header access for text fields needs to be implemented
  9882. // auto &headers = it->second.headers;
  9883. // ASSERT_EQ(3U, headers.size());
  9884. // auto custom_header = headers.find("x-whatever");
  9885. // ASSERT_TRUE(custom_header != headers.end());
  9886. // ASSERT_NE("customvalue", custom_header->second);
  9887. // ASSERT_EQ("CustomValue", custom_header->second);
  9888. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9889. handled = true;
  9890. });
  9891. thread t = thread([&] { svr.listen(HOST, PORT); });
  9892. auto se = detail::scope_exit([&] {
  9893. svr.stop();
  9894. t.join();
  9895. ASSERT_FALSE(svr.is_running());
  9896. ASSERT_TRUE(handled);
  9897. });
  9898. svr.wait_until_ready();
  9899. auto req = "POST /test HTTP/1.1\r\n"
  9900. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9901. "Content-Length: 232\r\n"
  9902. "\r\n----------\r\n"
  9903. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9904. "Content-Length: 5\r\n"
  9905. "X-Test: 1\r\n"
  9906. "\r\n"
  9907. "text1"
  9908. "\r\n----------\r\n"
  9909. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9910. "Content-Type: text/plain\r\n"
  9911. "X-Whatever: CustomValue\r\n"
  9912. "\r\n"
  9913. "text2"
  9914. "\r\n------------\r\n"
  9915. "That should be disregarded. Not even read";
  9916. std::string response;
  9917. ASSERT_TRUE(send_request(1, req, &response));
  9918. ASSERT_EQ("200", response.substr(9, 3));
  9919. }
  9920. TEST(MultipartFormDataTest, LargeHeader) {
  9921. auto handled = false;
  9922. Server svr;
  9923. svr.Post("/test", [&](const Request &req, Response &) {
  9924. ASSERT_EQ(1u, req.form.fields.size());
  9925. const auto &text = req.form.get_field("name1");
  9926. ASSERT_EQ("text1", text);
  9927. handled = true;
  9928. });
  9929. thread t = thread([&] { svr.listen(HOST, PORT); });
  9930. auto se = detail::scope_exit([&] {
  9931. svr.stop();
  9932. t.join();
  9933. ASSERT_FALSE(svr.is_running());
  9934. ASSERT_TRUE(handled);
  9935. });
  9936. svr.wait_until_ready();
  9937. auto boundary = std::string("cpp-httplib-multipart-data");
  9938. std::string content = "--" + boundary +
  9939. "\r\n"
  9940. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9941. "\r\n"
  9942. "text1\r\n"
  9943. "--" +
  9944. boundary + "--\r\n";
  9945. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9946. "Content-Type: multipart/form-data;boundary=" +
  9947. boundary +
  9948. "\r\n"
  9949. "Content-Length: " +
  9950. std::to_string(content.size()) +
  9951. "\r\n"
  9952. "Dummy-Header: ";
  9953. std::string header_suffix = "\r\n"
  9954. "\r\n";
  9955. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9956. size_t header_dummy_size =
  9957. read_buff_size -
  9958. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9959. auto header_dummy = std::string(header_dummy_size, '@');
  9960. auto req = header_prefix + header_dummy + header_suffix + content;
  9961. std::string response;
  9962. ASSERT_TRUE(send_request(1, req, &response));
  9963. ASSERT_EQ("200", response.substr(9, 3));
  9964. }
  9965. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  9966. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  9967. // (not chunked Transfer-Encoding) after the streaming refactor.
  9968. auto handled = false;
  9969. Server svr;
  9970. svr.Post("/upload", [&](const Request &req, Response &res) {
  9971. auto cl_it = req.headers.find("Content-Length");
  9972. EXPECT_TRUE(cl_it != req.headers.end());
  9973. auto te_it = req.headers.find("Transfer-Encoding");
  9974. EXPECT_TRUE(te_it == req.headers.end());
  9975. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  9976. res.set_content("ok", "text/plain");
  9977. handled = true;
  9978. });
  9979. auto port = svr.bind_to_any_port(HOST);
  9980. auto t = thread([&] { svr.listen_after_bind(); });
  9981. auto se = detail::scope_exit([&] {
  9982. svr.stop();
  9983. t.join();
  9984. ASSERT_FALSE(svr.is_running());
  9985. ASSERT_TRUE(handled);
  9986. });
  9987. svr.wait_until_ready();
  9988. UploadFormDataItems items = {
  9989. {"field1", "hello", "", "text/plain"},
  9990. {"file1", "world", "test.txt", "application/octet-stream"},
  9991. };
  9992. Client cli(HOST, port);
  9993. auto res = cli.Post("/upload", {}, items);
  9994. ASSERT_TRUE(res);
  9995. EXPECT_EQ(StatusCode::OK_200, res->status);
  9996. }
  9997. TEST(MultipartFormDataTest, MakeFileProvider) {
  9998. // Verify make_file_provider sends a file's contents correctly.
  9999. const std::string file_content(4096, 'Z');
  10000. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10001. {
  10002. std::ofstream ofs(tmp_path, std::ios::binary);
  10003. ofs.write(file_content.data(),
  10004. static_cast<std::streamsize>(file_content.size()));
  10005. }
  10006. auto handled = false;
  10007. Server svr;
  10008. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10009. const ContentReader &content_reader) {
  10010. ASSERT_TRUE(req.is_multipart_form_data());
  10011. std::vector<FormData> items;
  10012. content_reader(
  10013. [&](const FormData &file) {
  10014. items.push_back(file);
  10015. return true;
  10016. },
  10017. [&](const char *data, size_t data_length) {
  10018. items.back().content.append(data, data_length);
  10019. return true;
  10020. });
  10021. ASSERT_EQ(1u, items.size());
  10022. EXPECT_EQ("myfile", items[0].name);
  10023. EXPECT_EQ("data.bin", items[0].filename);
  10024. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10025. EXPECT_EQ(file_content, items[0].content);
  10026. handled = true;
  10027. });
  10028. auto port = svr.bind_to_any_port(HOST);
  10029. auto t = thread([&] { svr.listen_after_bind(); });
  10030. auto se = detail::scope_exit([&] {
  10031. svr.stop();
  10032. t.join();
  10033. ASSERT_FALSE(svr.is_running());
  10034. ASSERT_TRUE(handled);
  10035. std::remove(tmp_path.c_str());
  10036. });
  10037. svr.wait_until_ready();
  10038. FormDataProviderItems providers;
  10039. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10040. "application/octet-stream"));
  10041. Client cli(HOST, port);
  10042. auto res = cli.Post("/upload", {}, {}, providers);
  10043. ASSERT_TRUE(res);
  10044. EXPECT_EQ(StatusCode::OK_200, res->status);
  10045. }
  10046. TEST(MakeFileBodyTest, Basic) {
  10047. const std::string file_content(4096, 'Z');
  10048. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10049. {
  10050. std::ofstream ofs(tmp_path, std::ios::binary);
  10051. ofs.write(file_content.data(),
  10052. static_cast<std::streamsize>(file_content.size()));
  10053. }
  10054. auto handled = false;
  10055. Server svr;
  10056. svr.Post("/upload", [&](const Request &req, Response &res) {
  10057. EXPECT_EQ(file_content, req.body);
  10058. handled = true;
  10059. res.status = StatusCode::OK_200;
  10060. });
  10061. auto port = svr.bind_to_any_port(HOST);
  10062. auto t = thread([&] { svr.listen_after_bind(); });
  10063. auto se = detail::scope_exit([&] {
  10064. svr.stop();
  10065. t.join();
  10066. ASSERT_FALSE(svr.is_running());
  10067. ASSERT_TRUE(handled);
  10068. std::remove(tmp_path.c_str());
  10069. });
  10070. svr.wait_until_ready();
  10071. auto fb = make_file_body(tmp_path);
  10072. ASSERT_GT(fb.first, 0u);
  10073. Client cli(HOST, port);
  10074. auto res =
  10075. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10076. ASSERT_TRUE(res);
  10077. EXPECT_EQ(StatusCode::OK_200, res->status);
  10078. }
  10079. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10080. static constexpr unsigned int number_of_tasks{1000000};
  10081. std::atomic_uint count{0};
  10082. std::unique_ptr<TaskQueue> task_queue{
  10083. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10084. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10085. auto queued = task_queue->enqueue(
  10086. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10087. EXPECT_TRUE(queued);
  10088. }
  10089. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10090. task_queue->shutdown();
  10091. #else
  10092. EXPECT_NO_THROW(task_queue->shutdown());
  10093. #endif
  10094. EXPECT_EQ(number_of_tasks, count.load());
  10095. }
  10096. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10097. static constexpr unsigned int number_of_tasks{1000000};
  10098. static constexpr unsigned int qlimit{2};
  10099. unsigned int queued_count{0};
  10100. std::atomic_uint count{0};
  10101. std::unique_ptr<TaskQueue> task_queue{
  10102. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10103. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10104. if (task_queue->enqueue(
  10105. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10106. queued_count++;
  10107. }
  10108. }
  10109. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10110. task_queue->shutdown();
  10111. #else
  10112. EXPECT_NO_THROW(task_queue->shutdown());
  10113. #endif
  10114. EXPECT_EQ(queued_count, count.load());
  10115. EXPECT_TRUE(queued_count <= number_of_tasks);
  10116. EXPECT_TRUE(queued_count >= qlimit);
  10117. }
  10118. TEST(TaskQueueTest, MaxQueuedRequests) {
  10119. static constexpr unsigned int qlimit{3};
  10120. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10121. std::condition_variable sem_cv;
  10122. std::mutex sem_mtx;
  10123. int credits = 0;
  10124. bool queued;
  10125. /* Fill up the queue with tasks that will block until we give them credits to
  10126. * complete. */
  10127. for (unsigned int n = 0; n <= qlimit;) {
  10128. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10129. std::unique_lock<std::mutex> lock(sem_mtx);
  10130. while (credits <= 0) {
  10131. sem_cv.wait(lock);
  10132. }
  10133. /* Consume the credit and signal the test code if they are all gone. */
  10134. if (--credits == 0) { sem_cv.notify_one(); }
  10135. });
  10136. if (n < qlimit) {
  10137. /* The first qlimit enqueues must succeed. */
  10138. EXPECT_TRUE(queued);
  10139. } else {
  10140. /* The last one will succeed only when the worker thread
  10141. * starts and dequeues the first blocking task. Although
  10142. * not necessary for the correctness of this test, we sleep for
  10143. * a short while to avoid busy waiting. */
  10144. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10145. }
  10146. if (queued) { n++; }
  10147. }
  10148. /* Further enqueues must fail since the queue is full. */
  10149. for (auto i = 0; i < 4; i++) {
  10150. queued = task_queue->enqueue([] {});
  10151. EXPECT_FALSE(queued);
  10152. }
  10153. /* Give the credits to allow the previous tasks to complete. */
  10154. {
  10155. std::unique_lock<std::mutex> lock(sem_mtx);
  10156. credits += qlimit + 1;
  10157. }
  10158. sem_cv.notify_all();
  10159. /* Wait for all the credits to be consumed. */
  10160. {
  10161. std::unique_lock<std::mutex> lock(sem_mtx);
  10162. while (credits > 0) {
  10163. sem_cv.wait(lock);
  10164. }
  10165. }
  10166. /* Check that we are able again to enqueue at least qlimit tasks. */
  10167. for (unsigned int i = 0; i < qlimit; i++) {
  10168. queued = task_queue->enqueue([] {});
  10169. EXPECT_TRUE(queued);
  10170. }
  10171. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10172. task_queue->shutdown();
  10173. #else
  10174. EXPECT_NO_THROW(task_queue->shutdown());
  10175. #endif
  10176. }
  10177. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10178. Server svr;
  10179. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10180. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10181. });
  10182. svr.Get("/hello", [](const Request &req, Response &res) {
  10183. res.set_content(req.get_param_value("key"), "text/plain");
  10184. });
  10185. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10186. auto se = detail::scope_exit([&] {
  10187. svr.stop();
  10188. thread.join();
  10189. ASSERT_FALSE(svr.is_running());
  10190. });
  10191. svr.wait_until_ready();
  10192. {
  10193. Client cli(HOST, PORT);
  10194. cli.set_follow_location(true);
  10195. auto res = cli.Get("/");
  10196. ASSERT_TRUE(res);
  10197. EXPECT_EQ(StatusCode::OK_200, res->status);
  10198. EXPECT_EQ("val&key2=val2", res->body);
  10199. }
  10200. }
  10201. #endif
  10202. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10203. Server svr;
  10204. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10205. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10206. });
  10207. svr.Get("/hello", [](const Request &req, Response &res) {
  10208. res.set_content(req.get_param_value("key"), "text/plain");
  10209. });
  10210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10211. auto se = detail::scope_exit([&] {
  10212. svr.stop();
  10213. thread.join();
  10214. ASSERT_FALSE(svr.is_running());
  10215. });
  10216. svr.wait_until_ready();
  10217. {
  10218. Client cli(HOST, PORT);
  10219. cli.set_follow_location(true);
  10220. auto res = cli.Get("/");
  10221. ASSERT_TRUE(res);
  10222. EXPECT_EQ(StatusCode::OK_200, res->status);
  10223. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10224. }
  10225. }
  10226. #ifdef CPPHTTPLIB_SSL_ENABLED
  10227. TEST(RedirectTest, Issue2185_Online) {
  10228. SSLClient client("github.com");
  10229. client.set_follow_location(true);
  10230. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10231. "Coollab-Windows.zip");
  10232. ASSERT_TRUE(res);
  10233. EXPECT_EQ(StatusCode::OK_200, res->status);
  10234. EXPECT_EQ(9920427U, res->body.size());
  10235. }
  10236. #endif
  10237. TEST(VulnerabilityTest, CRLFInjection) {
  10238. Server svr;
  10239. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10240. res.set_content("Hello 1", "text/plain");
  10241. });
  10242. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10243. res.set_content("Hello 2", "text/plain");
  10244. });
  10245. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10246. res.set_content("Hello 3", "text/plain");
  10247. });
  10248. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10249. res.set_content("Hello 4", "text/plain");
  10250. });
  10251. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10252. for (const auto &x : req.headers) {
  10253. auto key = x.first;
  10254. EXPECT_STRNE("evil", key.c_str());
  10255. }
  10256. });
  10257. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10258. auto se = detail::scope_exit([&] {
  10259. svr.stop();
  10260. thread.join();
  10261. ASSERT_FALSE(svr.is_running());
  10262. });
  10263. svr.wait_until_ready();
  10264. {
  10265. Client cli(HOST, PORT);
  10266. cli.Post("/test1", "A=B",
  10267. "application/x-www-form-urlencoded\r\nevil: hello1");
  10268. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10269. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10270. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10271. }
  10272. }
  10273. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10274. auto server_thread = std::thread([] {
  10275. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10276. default_socket_options(srv);
  10277. sockaddr_in addr{};
  10278. addr.sin_family = AF_INET;
  10279. addr.sin_port = htons(PORT + 1);
  10280. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10281. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10282. ::listen(srv, 1);
  10283. sockaddr_in cli_addr{};
  10284. socklen_t cli_len = sizeof(cli_addr);
  10285. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10286. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10287. std::string buf_all;
  10288. char buf[2048];
  10289. ssize_t n;
  10290. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10291. buf_all.append(buf, static_cast<size_t>(n));
  10292. size_t pos;
  10293. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10294. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10295. auto e = request_block.find("\r\n");
  10296. if (e != std::string::npos) {
  10297. auto request_line = request_block.substr(0, e);
  10298. std::string msg =
  10299. "CRLF injection detected in request line: '" + request_line + "'";
  10300. EXPECT_FALSE(true) << msg;
  10301. }
  10302. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10303. ::send(cli,
  10304. #ifdef _WIN32
  10305. static_cast<const char *>(resp.c_str()),
  10306. static_cast<int>(resp.size()),
  10307. #else
  10308. resp.c_str(), resp.size(),
  10309. #endif
  10310. 0);
  10311. buf_all.erase(0, pos + 4);
  10312. }
  10313. }
  10314. detail::close_socket(cli);
  10315. detail::close_socket(srv);
  10316. });
  10317. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10318. auto cli = Client("127.0.0.1", PORT + 1);
  10319. auto headers = Headers{
  10320. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10321. {"Connection", "keep-alive"}};
  10322. auto res = cli.Get("/hi", headers);
  10323. EXPECT_FALSE(res);
  10324. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10325. server_thread.join();
  10326. }
  10327. TEST(PathParamsTest, StaticMatch) {
  10328. const auto pattern = "/users/all";
  10329. detail::PathParamsMatcher matcher(pattern);
  10330. Request request;
  10331. request.path = "/users/all";
  10332. ASSERT_TRUE(matcher.match(request));
  10333. std::unordered_map<std::string, std::string> expected_params = {};
  10334. EXPECT_EQ(request.path_params, expected_params);
  10335. }
  10336. TEST(PathParamsTest, StaticMismatch) {
  10337. const auto pattern = "/users/all";
  10338. detail::PathParamsMatcher matcher(pattern);
  10339. Request request;
  10340. request.path = "/users/1";
  10341. ASSERT_FALSE(matcher.match(request));
  10342. }
  10343. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10344. const auto pattern = "/users/:id/subscriptions";
  10345. detail::PathParamsMatcher matcher(pattern);
  10346. Request request;
  10347. request.path = "/users/42/subscriptions";
  10348. ASSERT_TRUE(matcher.match(request));
  10349. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10350. EXPECT_EQ(request.path_params, expected_params);
  10351. }
  10352. TEST(PathParamsTest, SingleParamInTheEnd) {
  10353. const auto pattern = "/users/:id";
  10354. detail::PathParamsMatcher matcher(pattern);
  10355. Request request;
  10356. request.path = "/users/24";
  10357. ASSERT_TRUE(matcher.match(request));
  10358. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10359. EXPECT_EQ(request.path_params, expected_params);
  10360. }
  10361. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10362. const auto pattern = "/users/:id/";
  10363. detail::PathParamsMatcher matcher(pattern);
  10364. Request request;
  10365. request.path = "/users/42/";
  10366. ASSERT_TRUE(matcher.match(request));
  10367. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10368. EXPECT_EQ(request.path_params, expected_params);
  10369. }
  10370. TEST(PathParamsTest, EmptyParam) {
  10371. const auto pattern = "/users/:id/";
  10372. detail::PathParamsMatcher matcher(pattern);
  10373. Request request;
  10374. request.path = "/users//";
  10375. ASSERT_TRUE(matcher.match(request));
  10376. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10377. EXPECT_EQ(request.path_params, expected_params);
  10378. }
  10379. TEST(PathParamsTest, FragmentMismatch) {
  10380. const auto pattern = "/users/:id/";
  10381. detail::PathParamsMatcher matcher(pattern);
  10382. Request request;
  10383. request.path = "/admins/24/";
  10384. ASSERT_FALSE(matcher.match(request));
  10385. }
  10386. TEST(PathParamsTest, ExtraFragments) {
  10387. const auto pattern = "/users/:id";
  10388. detail::PathParamsMatcher matcher(pattern);
  10389. Request request;
  10390. request.path = "/users/42/subscriptions";
  10391. ASSERT_FALSE(matcher.match(request));
  10392. }
  10393. TEST(PathParamsTest, MissingTrailingParam) {
  10394. const auto pattern = "/users/:id";
  10395. detail::PathParamsMatcher matcher(pattern);
  10396. Request request;
  10397. request.path = "/users";
  10398. ASSERT_FALSE(matcher.match(request));
  10399. }
  10400. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10401. const auto pattern = "/users/:id/subscriptions";
  10402. detail::PathParamsMatcher matcher(pattern);
  10403. Request request;
  10404. request.path = "/users/subscriptions";
  10405. ASSERT_FALSE(matcher.match(request));
  10406. }
  10407. TEST(PathParamsTest, MultipleParams) {
  10408. const auto pattern = "/users/:userid/subscriptions/:subid";
  10409. detail::PathParamsMatcher matcher(pattern);
  10410. Request request;
  10411. request.path = "/users/42/subscriptions/2";
  10412. ASSERT_TRUE(matcher.match(request));
  10413. std::unordered_map<std::string, std::string> expected_params = {
  10414. {"userid", "42"}, {"subid", "2"}};
  10415. EXPECT_EQ(request.path_params, expected_params);
  10416. }
  10417. TEST(PathParamsTest, SequenceOfParams) {
  10418. const auto pattern = "/values/:x/:y/:z";
  10419. detail::PathParamsMatcher matcher(pattern);
  10420. Request request;
  10421. request.path = "/values/1/2/3";
  10422. ASSERT_TRUE(matcher.match(request));
  10423. std::unordered_map<std::string, std::string> expected_params = {
  10424. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10425. EXPECT_EQ(request.path_params, expected_params);
  10426. }
  10427. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10428. const auto pattern = "/prefix:suffix";
  10429. detail::PathParamsMatcher matcher(pattern);
  10430. Request request;
  10431. request.path = "/prefix:suffix";
  10432. ASSERT_TRUE(matcher.match(request));
  10433. const std::unordered_map<std::string, std::string> expected_params = {};
  10434. EXPECT_EQ(request.path_params, expected_params);
  10435. }
  10436. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10437. // If ipv6 regex working, regex match codepath is taken.
  10438. // else port will default to 80 in Client impl
  10439. int clientImplMagicPort = 80;
  10440. int port = 4321;
  10441. // above ports must be different to avoid false negative
  10442. EXPECT_NE(clientImplMagicPort, port);
  10443. std::string ipV6TestURL = "http://[ff06::c3]";
  10444. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10445. CLIENT_PRIVATE_KEY_FILE);
  10446. EXPECT_EQ(cli.port(), port);
  10447. }
  10448. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10449. auto file_path = "./www/dir/index.html";
  10450. auto dir_path = "./www/dir";
  10451. detail::FileStat stat_file(file_path);
  10452. EXPECT_TRUE(stat_file.is_file());
  10453. EXPECT_FALSE(stat_file.is_dir());
  10454. detail::FileStat stat_dir(dir_path);
  10455. EXPECT_FALSE(stat_dir.is_file());
  10456. EXPECT_TRUE(stat_dir.is_dir());
  10457. }
  10458. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10459. // IPv4 with default HTTP port (80)
  10460. EXPECT_EQ("example.com",
  10461. detail::make_host_and_port_string("example.com", 80, false));
  10462. // IPv4 with default HTTPS port (443)
  10463. EXPECT_EQ("example.com",
  10464. detail::make_host_and_port_string("example.com", 443, true));
  10465. // IPv4 with non-default HTTP port
  10466. EXPECT_EQ("example.com:8080",
  10467. detail::make_host_and_port_string("example.com", 8080, false));
  10468. // IPv4 with non-default HTTPS port
  10469. EXPECT_EQ("example.com:8443",
  10470. detail::make_host_and_port_string("example.com", 8443, true));
  10471. // IPv6 with default HTTP port (80)
  10472. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10473. // IPv6 with default HTTPS port (443)
  10474. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10475. // IPv6 with non-default HTTP port
  10476. EXPECT_EQ("[::1]:8080",
  10477. detail::make_host_and_port_string("::1", 8080, false));
  10478. // IPv6 with non-default HTTPS port
  10479. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10480. // IPv6 full address with default port
  10481. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10482. detail::make_host_and_port_string(
  10483. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10484. // IPv6 full address with non-default port
  10485. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10486. detail::make_host_and_port_string(
  10487. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10488. // IPv6 localhost with non-default port
  10489. EXPECT_EQ("[::1]:3000",
  10490. detail::make_host_and_port_string("::1", 3000, false));
  10491. // IPv6 with zone ID (link-local address) with default port
  10492. EXPECT_EQ("[fe80::1%eth0]",
  10493. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10494. // IPv6 with zone ID (link-local address) with non-default port
  10495. EXPECT_EQ("[fe80::1%eth0]:8080",
  10496. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10497. // Edge case: Port 443 with is_ssl=false (should add port)
  10498. EXPECT_EQ("example.com:443",
  10499. detail::make_host_and_port_string("example.com", 443, false));
  10500. // Edge case: Port 80 with is_ssl=true (should add port)
  10501. EXPECT_EQ("example.com:80",
  10502. detail::make_host_and_port_string("example.com", 80, true));
  10503. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10504. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10505. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10506. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10507. // Security fix: Already bracketed IPv6 should not get double brackets
  10508. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10509. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10510. EXPECT_EQ("[::1]:8080",
  10511. detail::make_host_and_port_string("[::1]", 8080, false));
  10512. EXPECT_EQ("[2001:db8::1]:8080",
  10513. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10514. EXPECT_EQ("[fe80::1%eth0]",
  10515. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10516. EXPECT_EQ("[fe80::1%eth0]:8080",
  10517. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10518. // Edge case: Empty host (should return as-is)
  10519. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10520. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10521. // This is a known limitation but shouldn't crash
  10522. EXPECT_EQ("[host:name]",
  10523. detail::make_host_and_port_string("host:name", 80, false));
  10524. // Port number edge cases (no validation, but should not crash)
  10525. EXPECT_EQ("example.com:0",
  10526. detail::make_host_and_port_string("example.com", 0, false));
  10527. EXPECT_EQ("example.com:-1",
  10528. detail::make_host_and_port_string("example.com", -1, false));
  10529. EXPECT_EQ("example.com:65535",
  10530. detail::make_host_and_port_string("example.com", 65535, false));
  10531. EXPECT_EQ("example.com:65536",
  10532. detail::make_host_and_port_string("example.com", 65536, false));
  10533. }
  10534. #ifdef CPPHTTPLIB_SSL_ENABLED
  10535. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10536. httplib::SSLClient cli("roblox.com", 443);
  10537. cli.set_follow_location(true);
  10538. auto res = cli.Get("/");
  10539. ASSERT_TRUE(res);
  10540. EXPECT_EQ(StatusCode::OK_200, res->status);
  10541. }
  10542. #endif
  10543. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10544. Server svr;
  10545. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10546. EXPECT_EQ(res.status, 400);
  10547. });
  10548. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10549. auto se = detail::scope_exit([&] {
  10550. svr.stop();
  10551. thread.join();
  10552. ASSERT_FALSE(svr.is_running());
  10553. });
  10554. svr.wait_until_ready();
  10555. Client cli(HOST, PORT);
  10556. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10557. }
  10558. TEST(InvalidHeaderCharsTest, is_field_name) {
  10559. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10560. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10561. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10562. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10563. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10564. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10565. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10566. EXPECT_FALSE(detail::fields::is_field_name(""));
  10567. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10568. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10569. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10570. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10571. }
  10572. TEST(InvalidHeaderCharsTest, is_field_value) {
  10573. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10574. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10575. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10576. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10577. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10578. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10579. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10580. EXPECT_TRUE(detail::fields::is_field_value(""));
  10581. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10582. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10583. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10584. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10585. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10586. }
  10587. TEST(InvalidHeaderCharsTest, OnServer) {
  10588. Server svr;
  10589. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10590. std::string header = "Not Set";
  10591. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10592. res.set_header(header, "value");
  10593. res.set_content("Page Content Page Content", "text/plain");
  10594. });
  10595. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10596. std::string header = "Not Set";
  10597. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10598. res.set_header("X-Test", header);
  10599. res.set_content("Page Content Page Content", "text/plain");
  10600. });
  10601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10602. auto se = detail::scope_exit([&] {
  10603. svr.stop();
  10604. thread.join();
  10605. ASSERT_FALSE(svr.is_running());
  10606. });
  10607. svr.wait_until_ready();
  10608. Client cli(HOST, PORT);
  10609. {
  10610. auto res = cli.Get(
  10611. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10612. ASSERT_TRUE(res);
  10613. EXPECT_EQ("Page Content Page Content", res->body);
  10614. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10615. }
  10616. {
  10617. auto res = cli.Get(
  10618. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10619. ASSERT_TRUE(res);
  10620. EXPECT_EQ("Page Content Page Content", res->body);
  10621. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10622. }
  10623. }
  10624. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10625. auto handled = false;
  10626. Server svr;
  10627. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10628. thread t = thread([&] { svr.listen(HOST, PORT); });
  10629. auto se = detail::scope_exit([&] {
  10630. svr.stop();
  10631. t.join();
  10632. ASSERT_FALSE(svr.is_running());
  10633. ASSERT_FALSE(handled);
  10634. });
  10635. svr.wait_until_ready();
  10636. auto req = "POST /test HTTP/1.1\r\n"
  10637. "Content-Length: x\r\n"
  10638. "\r\n";
  10639. std::string response;
  10640. ASSERT_TRUE(send_request(1, req, &response));
  10641. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10642. response.substr(0, response.find("\r\n")));
  10643. }
  10644. #ifndef _WIN32
  10645. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10646. static constexpr char reject[] = "Unauthorized";
  10647. static constexpr char accept[] = "Upload accepted";
  10648. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10649. Server svr;
  10650. svr.set_expect_100_continue_handler(
  10651. [](const Request & /*req*/, Response &res) {
  10652. res.status = StatusCode::Unauthorized_401;
  10653. res.set_content(reject, "text/plain");
  10654. return res.status;
  10655. });
  10656. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10657. res.set_content(accept, "text/plain");
  10658. });
  10659. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10660. auto se = detail::scope_exit([&] {
  10661. svr.stop();
  10662. thread.join();
  10663. ASSERT_FALSE(svr.is_running());
  10664. });
  10665. svr.wait_until_ready();
  10666. {
  10667. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10668. curl_easy_init(), &curl_easy_cleanup};
  10669. ASSERT_NE(curl, nullptr);
  10670. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10671. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10672. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10673. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10674. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10675. &curl_slist_free_all};
  10676. ASSERT_NE(list, nullptr);
  10677. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10678. struct read_data {
  10679. size_t read_size;
  10680. size_t total_size;
  10681. } data = {0, total_size};
  10682. using read_callback_t =
  10683. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10684. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10685. void *userdata) -> size_t {
  10686. read_data *data = (read_data *)userdata;
  10687. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10688. std::fill_n(ptr, size * nmemb, 'A');
  10689. data->read_size += size * nmemb;
  10690. return size * nmemb;
  10691. };
  10692. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10693. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10694. std::vector<char> buffer;
  10695. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10696. using write_callback_t =
  10697. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10698. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10699. void *userdata) -> size_t {
  10700. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10701. buffer->reserve(buffer->size() + size * nmemb + 1);
  10702. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10703. return size * nmemb;
  10704. };
  10705. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10706. {
  10707. const auto res = curl_easy_perform(curl.get());
  10708. ASSERT_EQ(res, CURLE_OK);
  10709. }
  10710. {
  10711. auto response_code = long{};
  10712. const auto res =
  10713. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10714. ASSERT_EQ(res, CURLE_OK);
  10715. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10716. }
  10717. {
  10718. auto dl = curl_off_t{};
  10719. const auto res =
  10720. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10721. ASSERT_EQ(res, CURLE_OK);
  10722. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10723. }
  10724. {
  10725. buffer.push_back('\0');
  10726. ASSERT_STRCASEEQ(buffer.data(), reject);
  10727. }
  10728. }
  10729. }
  10730. #endif
  10731. template <typename S, typename C>
  10732. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10733. svr.Get("/stream", [&](const Request &, Response &res) {
  10734. auto data = new std::string("01234567890123456789");
  10735. res.set_content_provider(
  10736. data->size(), "text/plain",
  10737. [&, data](size_t offset, size_t length, DataSink &sink) {
  10738. const size_t DATA_CHUNK_SIZE = 4;
  10739. const auto &d = *data;
  10740. std::this_thread::sleep_for(std::chrono::seconds(1));
  10741. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10742. return true;
  10743. },
  10744. [data](bool success) {
  10745. EXPECT_FALSE(success);
  10746. delete data;
  10747. });
  10748. });
  10749. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10750. auto i = new size_t(0);
  10751. res.set_content_provider(
  10752. "text/plain",
  10753. [i](size_t, DataSink &sink) {
  10754. if (*i < 5) {
  10755. std::this_thread::sleep_for(std::chrono::seconds(1));
  10756. sink.write("abcd", 4);
  10757. (*i)++;
  10758. } else {
  10759. sink.done();
  10760. }
  10761. return true;
  10762. },
  10763. [i](bool success) {
  10764. EXPECT_FALSE(success);
  10765. delete i;
  10766. });
  10767. });
  10768. svr.Get("/chunked", [&](const Request &, Response &res) {
  10769. auto i = new size_t(0);
  10770. res.set_chunked_content_provider(
  10771. "text/plain",
  10772. [i](size_t, DataSink &sink) {
  10773. if (*i < 5) {
  10774. std::this_thread::sleep_for(std::chrono::seconds(1));
  10775. sink.os << "abcd";
  10776. (*i)++;
  10777. } else {
  10778. sink.done();
  10779. }
  10780. return true;
  10781. },
  10782. [i](bool success) {
  10783. EXPECT_FALSE(success);
  10784. delete i;
  10785. });
  10786. });
  10787. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10788. auto se = detail::scope_exit([&] {
  10789. svr.stop();
  10790. listen_thread.join();
  10791. ASSERT_FALSE(svr.is_running());
  10792. });
  10793. svr.wait_until_ready();
  10794. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10795. {
  10796. auto start = std::chrono::steady_clock::now();
  10797. auto res = cli.Get("/stream");
  10798. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10799. std::chrono::steady_clock::now() - start)
  10800. .count();
  10801. ASSERT_FALSE(res);
  10802. EXPECT_EQ(Error::Read, res.error());
  10803. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10804. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10805. }
  10806. {
  10807. auto start = std::chrono::steady_clock::now();
  10808. auto res = cli.Get("/stream_without_length");
  10809. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10810. std::chrono::steady_clock::now() - start)
  10811. .count();
  10812. ASSERT_FALSE(res);
  10813. EXPECT_EQ(Error::Read, res.error());
  10814. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10815. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10816. }
  10817. {
  10818. auto start = std::chrono::steady_clock::now();
  10819. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10820. EXPECT_EQ("abcd", string(data, data_length));
  10821. return true;
  10822. });
  10823. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10824. std::chrono::steady_clock::now() - start)
  10825. .count();
  10826. ASSERT_FALSE(res);
  10827. EXPECT_EQ(Error::Read, res.error());
  10828. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10829. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10830. }
  10831. }
  10832. TEST(MaxTimeoutTest, ContentStream) {
  10833. time_t timeout = 2000;
  10834. time_t threshold = 200;
  10835. Server svr;
  10836. Client cli("localhost", PORT);
  10837. max_timeout_test(svr, cli, timeout, threshold);
  10838. }
  10839. #ifdef CPPHTTPLIB_SSL_ENABLED
  10840. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10841. time_t timeout = 2000;
  10842. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10844. SSLClient cli("localhost", PORT);
  10845. cli.enable_server_certificate_verification(false);
  10846. max_timeout_test(svr, cli, timeout, threshold);
  10847. }
  10848. #endif
  10849. class EventDispatcher {
  10850. public:
  10851. EventDispatcher() {}
  10852. bool wait_event(DataSink *sink) {
  10853. unique_lock<mutex> lk(m_);
  10854. int id = id_;
  10855. // Wait with timeout to prevent hanging if client disconnects
  10856. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10857. [&] { return cid_ == id; })) {
  10858. return false; // Timeout occurred
  10859. }
  10860. sink->write(message_.data(), message_.size());
  10861. return true;
  10862. }
  10863. void send_event(const string &message) {
  10864. lock_guard<mutex> lk(m_);
  10865. cid_ = id_++;
  10866. message_ = message;
  10867. cv_.notify_all();
  10868. }
  10869. private:
  10870. mutex m_;
  10871. condition_variable cv_;
  10872. atomic_int id_{0};
  10873. atomic_int cid_{-1};
  10874. string message_;
  10875. };
  10876. TEST(ClientInThreadTest, Issue2068) {
  10877. EventDispatcher ed;
  10878. Server svr;
  10879. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10880. res.set_chunked_content_provider("text/event-stream",
  10881. [&](size_t /*offset*/, DataSink &sink) {
  10882. return ed.wait_event(&sink);
  10883. });
  10884. });
  10885. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10886. svr.wait_until_ready();
  10887. thread event_thread([&] {
  10888. int id = 0;
  10889. while (svr.is_running()) {
  10890. this_thread::sleep_for(chrono::milliseconds(500));
  10891. std::stringstream ss;
  10892. ss << "data: " << id << "\n\n";
  10893. ed.send_event(ss.str());
  10894. id++;
  10895. }
  10896. });
  10897. auto se = detail::scope_exit([&] {
  10898. svr.stop();
  10899. listen_thread.join();
  10900. event_thread.join();
  10901. ASSERT_FALSE(svr.is_running());
  10902. });
  10903. {
  10904. auto client = detail::make_unique<Client>(HOST, PORT);
  10905. client->set_read_timeout(std::chrono::minutes(10));
  10906. std::atomic<bool> stop{false};
  10907. std::thread t([&] {
  10908. client->Get("/event1",
  10909. [&](const char *, size_t) -> bool { return !stop; });
  10910. });
  10911. std::this_thread::sleep_for(std::chrono::seconds(2));
  10912. stop = true;
  10913. client->stop();
  10914. t.join();
  10915. // Reset client after thread has finished
  10916. client.reset();
  10917. }
  10918. }
  10919. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10920. auto handled = false;
  10921. Server svr;
  10922. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10923. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10924. auto se = detail::scope_exit([&] {
  10925. svr.stop();
  10926. t.join();
  10927. ASSERT_FALSE(svr.is_running());
  10928. ASSERT_FALSE(handled);
  10929. });
  10930. svr.wait_until_ready();
  10931. // Two Content-Length headers with different values — must be rejected
  10932. auto req = "POST /test HTTP/1.1\r\n"
  10933. "Content-Length: 5\r\n"
  10934. "Content-Length: 10\r\n"
  10935. "\r\n"
  10936. "hello";
  10937. std::string response;
  10938. ASSERT_TRUE(send_request(1, req, &response));
  10939. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10940. response.substr(0, response.find("\r\n")));
  10941. }
  10942. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10943. auto handled = false;
  10944. Server svr;
  10945. svr.Post("/test", [&](const Request &, Response &res) {
  10946. handled = true;
  10947. res.set_content("ok", "text/plain");
  10948. });
  10949. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10950. auto se = detail::scope_exit([&] {
  10951. svr.stop();
  10952. t.join();
  10953. ASSERT_FALSE(svr.is_running());
  10954. ASSERT_TRUE(handled);
  10955. });
  10956. svr.wait_until_ready();
  10957. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  10958. auto req = "POST /test HTTP/1.1\r\n"
  10959. "Content-Length: 5\r\n"
  10960. "Content-Length: 5\r\n"
  10961. "\r\n"
  10962. "hello";
  10963. std::string response;
  10964. ASSERT_TRUE(send_request(1, req, &response));
  10965. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  10966. }
  10967. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10968. Server svr;
  10969. svr.Get("/", [](const Request &req, Response &res) {
  10970. EXPECT_EQ(2U, req.trailers.size());
  10971. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10972. // Denied
  10973. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10974. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10975. // Accepted
  10976. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10977. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10978. EXPECT_TRUE(req.has_trailer("X-World"));
  10979. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10980. res.set_content("ok", "text/plain");
  10981. });
  10982. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10983. auto se = detail::scope_exit([&] {
  10984. svr.stop();
  10985. t.join();
  10986. ASSERT_FALSE(svr.is_running());
  10987. });
  10988. svr.wait_until_ready();
  10989. const std::string req = "GET / HTTP/1.1\r\n"
  10990. "Transfer-Encoding: chunked\r\n"
  10991. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10992. "\r\n"
  10993. "0\r\n"
  10994. "Content-Length: 10\r\n"
  10995. "Host: internal.local\r\n"
  10996. "Content-Type: malicious/content\r\n"
  10997. "Cookie: any\r\n"
  10998. "Set-Cookie: any\r\n"
  10999. "X-Forwarded-For: attacker.com\r\n"
  11000. "X-Real-Ip: 1.1.1.1\r\n"
  11001. "X-Hello: hello\r\n"
  11002. "X-World: world\r\n"
  11003. "\r\n";
  11004. std::string res;
  11005. ASSERT_TRUE(send_request(1, req, &res));
  11006. }
  11007. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11008. Server svr;
  11009. std::string observed_remote_addr;
  11010. std::string observed_xff;
  11011. svr.Get("/ip", [&](const Request &req, Response &res) {
  11012. observed_remote_addr = req.remote_addr;
  11013. observed_xff = req.get_header_value("X-Forwarded-For");
  11014. res.set_content("ok", "text/plain");
  11015. });
  11016. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11017. auto se = detail::scope_exit([&] {
  11018. svr.stop();
  11019. t.join();
  11020. ASSERT_FALSE(svr.is_running());
  11021. });
  11022. svr.wait_until_ready();
  11023. Client cli(HOST, PORT);
  11024. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11025. ASSERT_TRUE(res);
  11026. EXPECT_EQ(StatusCode::OK_200, res->status);
  11027. EXPECT_EQ(observed_xff, "203.0.113.66");
  11028. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11029. observed_remote_addr == "127.0.0.1");
  11030. }
  11031. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11032. Server svr;
  11033. svr.set_trusted_proxies({"203.0.113.66"});
  11034. std::string observed_remote_addr;
  11035. std::string observed_xff;
  11036. svr.Get("/ip", [&](const Request &req, Response &res) {
  11037. observed_remote_addr = req.remote_addr;
  11038. observed_xff = req.get_header_value("X-Forwarded-For");
  11039. res.set_content("ok", "text/plain");
  11040. });
  11041. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11042. auto se = detail::scope_exit([&] {
  11043. svr.stop();
  11044. t.join();
  11045. ASSERT_FALSE(svr.is_running());
  11046. });
  11047. svr.wait_until_ready();
  11048. Client cli(HOST, PORT);
  11049. auto res = cli.Get("/ip");
  11050. ASSERT_TRUE(res);
  11051. EXPECT_EQ(StatusCode::OK_200, res->status);
  11052. EXPECT_EQ(observed_xff, "");
  11053. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11054. observed_remote_addr == "127.0.0.1");
  11055. }
  11056. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11057. Server svr;
  11058. svr.set_trusted_proxies({"203.0.113.66"});
  11059. std::string observed_remote_addr;
  11060. std::string observed_xff;
  11061. svr.Get("/ip", [&](const Request &req, Response &res) {
  11062. observed_remote_addr = req.remote_addr;
  11063. observed_xff = req.get_header_value("X-Forwarded-For");
  11064. res.set_content("ok", "text/plain");
  11065. });
  11066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11067. auto se = detail::scope_exit([&] {
  11068. svr.stop();
  11069. t.join();
  11070. ASSERT_FALSE(svr.is_running());
  11071. });
  11072. svr.wait_until_ready();
  11073. Client cli(HOST, PORT);
  11074. auto res =
  11075. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11076. ASSERT_TRUE(res);
  11077. EXPECT_EQ(StatusCode::OK_200, res->status);
  11078. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11079. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11080. }
  11081. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11082. Server svr;
  11083. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11084. std::string observed_remote_addr;
  11085. std::string observed_xff;
  11086. svr.Get("/ip", [&](const Request &req, Response &res) {
  11087. observed_remote_addr = req.remote_addr;
  11088. observed_xff = req.get_header_value("X-Forwarded-For");
  11089. res.set_content("ok", "text/plain");
  11090. });
  11091. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11092. auto se = detail::scope_exit([&] {
  11093. svr.stop();
  11094. t.join();
  11095. ASSERT_FALSE(svr.is_running());
  11096. });
  11097. svr.wait_until_ready();
  11098. Client cli(HOST, PORT);
  11099. auto res = cli.Get(
  11100. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11101. ASSERT_TRUE(res);
  11102. EXPECT_EQ(StatusCode::OK_200, res->status);
  11103. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11104. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11105. }
  11106. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11107. Server svr;
  11108. svr.set_trusted_proxies({"192.0.2.45"});
  11109. std::string observed_remote_addr;
  11110. std::string observed_xff;
  11111. svr.Get("/ip", [&](const Request &req, Response &res) {
  11112. observed_remote_addr = req.remote_addr;
  11113. observed_xff = req.get_header_value("X-Forwarded-For");
  11114. res.set_content("ok", "text/plain");
  11115. });
  11116. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11117. auto se = detail::scope_exit([&] {
  11118. svr.stop();
  11119. t.join();
  11120. ASSERT_FALSE(svr.is_running());
  11121. });
  11122. svr.wait_until_ready();
  11123. Client cli(HOST, PORT);
  11124. auto res =
  11125. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11126. ASSERT_TRUE(res);
  11127. EXPECT_EQ(StatusCode::OK_200, res->status);
  11128. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11129. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11130. }
  11131. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11132. Server svr;
  11133. svr.set_trusted_proxies({"192.0.2.45"});
  11134. std::string observed_remote_addr;
  11135. std::string observed_xff;
  11136. svr.Get("/ip", [&](const Request &req, Response &res) {
  11137. observed_remote_addr = req.remote_addr;
  11138. observed_xff = req.get_header_value("X-Forwarded-For");
  11139. res.set_content("ok", "text/plain");
  11140. });
  11141. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11142. auto se = detail::scope_exit([&] {
  11143. svr.stop();
  11144. t.join();
  11145. ASSERT_FALSE(svr.is_running());
  11146. });
  11147. svr.wait_until_ready();
  11148. Client cli(HOST, PORT);
  11149. auto res = cli.Get(
  11150. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11151. ASSERT_TRUE(res);
  11152. EXPECT_EQ(StatusCode::OK_200, res->status);
  11153. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11154. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11155. }
  11156. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11157. Server svr;
  11158. svr.set_trusted_proxies({"192.0.2.45"});
  11159. std::string observed_remote_addr;
  11160. std::string observed_xff;
  11161. svr.Get("/ip", [&](const Request &req, Response &res) {
  11162. observed_remote_addr = req.remote_addr;
  11163. observed_xff = req.get_header_value("X-Forwarded-For");
  11164. res.set_content("ok", "text/plain");
  11165. });
  11166. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11167. auto se = detail::scope_exit([&] {
  11168. svr.stop();
  11169. t.join();
  11170. ASSERT_FALSE(svr.is_running());
  11171. });
  11172. svr.wait_until_ready();
  11173. std::string raw_req =
  11174. "GET /ip HTTP/1.1\r\n"
  11175. "Host: localhost\r\n"
  11176. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11177. "Connection: close\r\n"
  11178. "\r\n";
  11179. std::string out;
  11180. ASSERT_TRUE(send_request(5, raw_req, &out));
  11181. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11182. // Header parser trims surrounding whitespace of the header value
  11183. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11184. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11185. }
  11186. #ifndef _WIN32
  11187. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11188. Server svr;
  11189. svr.Post("/post", [&](const Request &req, Response &res) {
  11190. res.set_content(req.body, "text/plain");
  11191. });
  11192. svr.Put("/put", [&](const Request &req, Response &res) {
  11193. res.set_content(req.body, "text/plain");
  11194. });
  11195. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11196. res.set_content(req.body, "text/plain");
  11197. });
  11198. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11199. res.set_content(req.body, "text/plain");
  11200. });
  11201. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11202. auto se = detail::scope_exit([&] {
  11203. svr.stop();
  11204. t.join();
  11205. ASSERT_FALSE(svr.is_running());
  11206. });
  11207. svr.wait_until_ready();
  11208. std::string resp;
  11209. // POST without Content-Length
  11210. ASSERT_TRUE(send_request(5,
  11211. "POST /post HTTP/1.1\r\n"
  11212. "Host: localhost\r\n"
  11213. "Connection: close\r\n"
  11214. "\r\n",
  11215. &resp));
  11216. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11217. // PUT without Content-Length
  11218. resp.clear();
  11219. ASSERT_TRUE(send_request(5,
  11220. "PUT /put HTTP/1.1\r\n"
  11221. "Host: localhost\r\n"
  11222. "Connection: close\r\n"
  11223. "\r\n",
  11224. &resp));
  11225. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11226. // PATCH without Content-Length
  11227. resp.clear();
  11228. ASSERT_TRUE(send_request(5,
  11229. "PATCH /patch HTTP/1.1\r\n"
  11230. "Host: localhost\r\n"
  11231. "Connection: close\r\n"
  11232. "\r\n",
  11233. &resp));
  11234. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11235. // DELETE without Content-Length
  11236. resp.clear();
  11237. ASSERT_TRUE(send_request(5,
  11238. "DELETE /delete HTTP/1.1\r\n"
  11239. "Host: localhost\r\n"
  11240. "Connection: close\r\n"
  11241. "\r\n",
  11242. &resp));
  11243. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11244. }
  11245. #endif
  11246. //==============================================================================
  11247. // open_stream() Tests
  11248. //==============================================================================
  11249. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11250. std::string result;
  11251. char buf[8192];
  11252. ssize_t n;
  11253. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11254. result.append(buf, static_cast<size_t>(n));
  11255. }
  11256. return result;
  11257. }
  11258. // Mock stream for unit tests
  11259. class MockStream : public Stream {
  11260. public:
  11261. std::string data;
  11262. size_t pos = 0;
  11263. ssize_t error_after = -1; // -1 = no error
  11264. explicit MockStream(const std::string &d, ssize_t err = -1)
  11265. : data(d), error_after(err) {}
  11266. bool is_readable() const override { return true; }
  11267. bool wait_readable() const override { return true; }
  11268. bool wait_writable() const override { return true; }
  11269. ssize_t read(char *ptr, size_t size) override {
  11270. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11271. if (pos >= data.size()) return 0;
  11272. size_t limit =
  11273. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11274. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11275. std::memcpy(ptr, data.data() + pos, to_read);
  11276. pos += to_read;
  11277. return static_cast<ssize_t>(to_read);
  11278. }
  11279. ssize_t write(const char *, size_t) override { return -1; }
  11280. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11281. ip = "127.0.0.1";
  11282. port = 0;
  11283. }
  11284. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11285. ip = "127.0.0.1";
  11286. port = 0;
  11287. }
  11288. socket_t socket() const override { return INVALID_SOCKET; }
  11289. time_t duration() const override { return 0; }
  11290. };
  11291. TEST(StreamHandleTest, Basic) {
  11292. ClientImpl::StreamHandle handle;
  11293. EXPECT_FALSE(handle.is_valid());
  11294. handle.response = detail::make_unique<Response>();
  11295. handle.error = Error::Connection;
  11296. EXPECT_FALSE(handle.is_valid());
  11297. handle.error = Error::Success;
  11298. EXPECT_TRUE(handle.is_valid());
  11299. }
  11300. TEST(BodyReaderTest, Basic) {
  11301. MockStream stream("Hello, World!");
  11302. detail::BodyReader reader;
  11303. reader.stream = &stream;
  11304. reader.content_length = 13;
  11305. char buf[32];
  11306. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11307. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11308. EXPECT_TRUE(reader.eof);
  11309. }
  11310. TEST(BodyReaderTest, NoStream) {
  11311. detail::BodyReader reader;
  11312. char buf[32];
  11313. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11314. EXPECT_EQ(Error::Connection, reader.last_error);
  11315. }
  11316. TEST(BodyReaderTest, Error) {
  11317. MockStream stream("Hello, World!", 5);
  11318. detail::BodyReader reader;
  11319. reader.stream = &stream;
  11320. reader.content_length = 13;
  11321. char buf[32];
  11322. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11323. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11324. EXPECT_EQ(Error::Read, reader.last_error);
  11325. }
  11326. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11327. // Mock-based StreamHandle tests relying on private internals are removed.
  11328. class OpenStreamTest : public ::testing::Test {
  11329. protected:
  11330. void SetUp() override {
  11331. svr_.Get("/hello", [](const Request &, Response &res) {
  11332. res.set_content("Hello World!", "text/plain");
  11333. });
  11334. svr_.Get("/large", [](const Request &, Response &res) {
  11335. res.set_content(std::string(10000, 'X'), "text/plain");
  11336. });
  11337. svr_.Get("/chunked", [](const Request &, Response &res) {
  11338. res.set_chunked_content_provider("text/plain",
  11339. [](size_t offset, DataSink &sink) {
  11340. if (offset < 15) {
  11341. sink.write("chunk", 5);
  11342. return true;
  11343. }
  11344. sink.done();
  11345. return true;
  11346. });
  11347. });
  11348. svr_.Get("/compressible", [](const Request &, Response &res) {
  11349. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11350. DataSink &sink) {
  11351. if (offset < 100 * 1024) {
  11352. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11353. sink.write(chunk.data(), chunk.size());
  11354. return true;
  11355. }
  11356. sink.done();
  11357. return true;
  11358. });
  11359. });
  11360. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11361. [](const Request & /*req*/, Response &res) {
  11362. auto i = new int(0);
  11363. res.set_header("Trailer", "Content-Length, X-Allowed");
  11364. res.set_chunked_content_provider(
  11365. "text/plain",
  11366. [i](size_t /*offset*/, DataSink &sink) {
  11367. switch (*i) {
  11368. case 0: sink.os << "123"; break;
  11369. case 1: sink.os << "456"; break;
  11370. case 2: sink.os << "789"; break;
  11371. case 3: {
  11372. sink.done_with_trailer(
  11373. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11374. } break;
  11375. }
  11376. (*i)++;
  11377. return true;
  11378. },
  11379. [i](bool success) {
  11380. EXPECT_TRUE(success);
  11381. delete i;
  11382. });
  11383. });
  11384. // Echo headers endpoint for header-related tests
  11385. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11386. std::string body;
  11387. for (const auto &h : req.headers) {
  11388. body.append(h.first);
  11389. body.push_back(':');
  11390. body.append(h.second);
  11391. body.push_back('\n');
  11392. }
  11393. res.set_content(body, "text/plain");
  11394. });
  11395. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11396. std::string body;
  11397. for (const auto &h : req.headers) {
  11398. body.append(h.first);
  11399. body.push_back(':');
  11400. body.append(h.second);
  11401. body.push_back('\n');
  11402. }
  11403. res.set_content(body, "text/plain");
  11404. });
  11405. port_ = svr_.bind_to_any_port("127.0.0.1");
  11406. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11407. svr_.wait_until_ready();
  11408. }
  11409. void TearDown() override {
  11410. svr_.stop();
  11411. if (thread_.joinable()) thread_.join();
  11412. }
  11413. Server svr_;
  11414. std::thread thread_;
  11415. int port_ = 0;
  11416. };
  11417. TEST_F(OpenStreamTest, Basic) {
  11418. Client cli("127.0.0.1", port_);
  11419. auto handle = cli.open_stream("GET", "/hello");
  11420. EXPECT_TRUE(handle.is_valid());
  11421. EXPECT_EQ("Hello World!", read_all(handle));
  11422. }
  11423. TEST_F(OpenStreamTest, SmallBuffer) {
  11424. Client cli("127.0.0.1", port_);
  11425. auto handle = cli.open_stream("GET", "/hello");
  11426. std::string result;
  11427. char buf[4];
  11428. ssize_t n;
  11429. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11430. result.append(buf, static_cast<size_t>(n));
  11431. EXPECT_EQ("Hello World!", result);
  11432. }
  11433. TEST_F(OpenStreamTest, DefaultHeaders) {
  11434. Client cli("127.0.0.1", port_);
  11435. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11436. {
  11437. auto handle = cli.open_stream("GET", "/echo-headers");
  11438. ASSERT_TRUE(handle.is_valid());
  11439. auto body = read_all(handle);
  11440. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11441. std::string::npos);
  11442. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11443. std::string::npos);
  11444. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11445. }
  11446. // open_stream POST with body and no explicit content_type should NOT add
  11447. // text/plain Content-Type (behavior differs from non-streaming path), but
  11448. // should include Content-Length
  11449. {
  11450. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11451. ASSERT_TRUE(handle.is_valid());
  11452. auto body = read_all(handle);
  11453. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11454. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11455. }
  11456. // open_stream POST with explicit Content-Type should preserve it
  11457. {
  11458. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11459. {{"Content-Type", "application/custom"}},
  11460. "{}", "application/custom");
  11461. ASSERT_TRUE(handle.is_valid());
  11462. auto body = read_all(handle);
  11463. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11464. }
  11465. // User-specified User-Agent must not be overwritten for stream API
  11466. {
  11467. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11468. {{"User-Agent", "MyAgent/1.2"}});
  11469. ASSERT_TRUE(handle.is_valid());
  11470. auto body = read_all(handle);
  11471. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11472. }
  11473. }
  11474. TEST_F(OpenStreamTest, Large) {
  11475. Client cli("127.0.0.1", port_);
  11476. auto handle = cli.open_stream("GET", "/large");
  11477. EXPECT_EQ(10000u, read_all(handle).size());
  11478. }
  11479. TEST_F(OpenStreamTest, ConnectionError) {
  11480. Client cli("127.0.0.1", 9999);
  11481. auto handle = cli.open_stream("GET", "/hello");
  11482. EXPECT_FALSE(handle.is_valid());
  11483. }
  11484. TEST_F(OpenStreamTest, Chunked) {
  11485. Client cli("127.0.0.1", port_);
  11486. auto handle = cli.open_stream("GET", "/chunked");
  11487. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11488. "Transfer-Encoding") == "chunked");
  11489. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11490. }
  11491. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11492. Client cli("127.0.0.1", port_);
  11493. auto handle =
  11494. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11495. ASSERT_TRUE(handle.is_valid());
  11496. // Consume body to allow trailers to be received/parsed
  11497. auto body = read_all(handle);
  11498. // Explicitly parse trailers (ensure trailers are available for assertion)
  11499. handle.parse_trailers_if_needed();
  11500. EXPECT_EQ(std::string("123456789"), body);
  11501. // The response should include a Trailer header declaring both names
  11502. ASSERT_TRUE(handle.response);
  11503. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11504. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11505. handle.response->get_header_value("Trailer"));
  11506. // Prohibited trailer must not be present
  11507. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11508. // Allowed trailer should be present
  11509. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11510. EXPECT_EQ(std::string("yes"),
  11511. handle.response->get_trailer_value("X-Allowed"));
  11512. // Verify trailers are NOT present as regular headers
  11513. EXPECT_EQ(std::string(""),
  11514. handle.response->get_header_value("Content-Length"));
  11515. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11516. }
  11517. static std::thread serve_single_response(std::promise<int> &port_promise,
  11518. const std::string &response) {
  11519. return std::thread([&port_promise, response] {
  11520. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11521. default_socket_options(srv);
  11522. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11523. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11524. sockaddr_in addr{};
  11525. addr.sin_family = AF_INET;
  11526. addr.sin_port = htons(0); // Let OS assign a free port
  11527. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11528. int opt = 1;
  11529. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11530. #ifdef _WIN32
  11531. reinterpret_cast<const char *>(&opt),
  11532. #else
  11533. &opt,
  11534. #endif
  11535. sizeof(opt));
  11536. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11537. ::listen(srv, 1) != 0) {
  11538. port_promise.set_value(-1);
  11539. detail::close_socket(srv);
  11540. return;
  11541. }
  11542. socklen_t addr_len = sizeof(addr);
  11543. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11544. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11545. sockaddr_in cli_addr{};
  11546. socklen_t cli_len = sizeof(cli_addr);
  11547. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11548. if (cli != INVALID_SOCKET) {
  11549. char buf[4096];
  11550. ::recv(cli, buf, sizeof(buf), 0);
  11551. ::send(cli,
  11552. #ifdef _WIN32
  11553. static_cast<const char *>(response.c_str()),
  11554. static_cast<int>(response.size()),
  11555. #else
  11556. response.c_str(), response.size(),
  11557. #endif
  11558. 0);
  11559. detail::close_socket(cli);
  11560. }
  11561. detail::close_socket(srv);
  11562. });
  11563. }
  11564. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11565. #ifndef _WIN32
  11566. signal(SIGPIPE, SIG_IGN);
  11567. #endif
  11568. std::promise<int> port_promise;
  11569. auto port_future = port_promise.get_future();
  11570. auto server_thread =
  11571. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11572. "Content-Type: text/plain\r\n"
  11573. "Content-Length: not-a-number\r\n"
  11574. "Connection: close\r\n"
  11575. "\r\n"
  11576. "hello");
  11577. auto port = port_future.get();
  11578. ASSERT_GT(port, 0);
  11579. Client cli("127.0.0.1", port);
  11580. auto handle = cli.open_stream("GET", "/");
  11581. EXPECT_FALSE(handle.is_valid());
  11582. server_thread.join();
  11583. }
  11584. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11585. #ifndef _WIN32
  11586. signal(SIGPIPE, SIG_IGN);
  11587. #endif
  11588. std::promise<int> port_promise;
  11589. auto port_future = port_promise.get_future();
  11590. auto server_thread = serve_single_response(
  11591. port_promise, "HTTP/1.1 200 OK\r\n"
  11592. "Content-Type: text/plain\r\n"
  11593. "Content-Length: 99999999999999999999999999\r\n"
  11594. "Connection: close\r\n"
  11595. "\r\n"
  11596. "hello");
  11597. auto port = port_future.get();
  11598. ASSERT_GT(port, 0);
  11599. // Before the fix, std::stoull would throw std::out_of_range here and
  11600. // crash the process. After the fix, strtoull silently clamps to
  11601. // ULLONG_MAX so the stream opens without crashing. The important thing
  11602. // is that the process does NOT terminate.
  11603. Client cli("127.0.0.1", port);
  11604. auto handle = cli.open_stream("GET", "/");
  11605. EXPECT_TRUE(handle.is_valid());
  11606. server_thread.join();
  11607. }
  11608. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11609. TEST_F(OpenStreamTest, Gzip) {
  11610. Client cli("127.0.0.1", port_);
  11611. auto handle = cli.open_stream("GET", "/compressible", {},
  11612. {{"Accept-Encoding", "gzip"}});
  11613. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11614. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11615. }
  11616. #endif
  11617. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11618. TEST_F(OpenStreamTest, Brotli) {
  11619. Client cli("127.0.0.1", port_);
  11620. auto handle =
  11621. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11622. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11623. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11624. }
  11625. #endif
  11626. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11627. TEST_F(OpenStreamTest, Zstd) {
  11628. Client cli("127.0.0.1", port_);
  11629. auto handle = cli.open_stream("GET", "/compressible", {},
  11630. {{"Accept-Encoding", "zstd"}});
  11631. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11632. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11633. }
  11634. #endif
  11635. #ifdef CPPHTTPLIB_SSL_ENABLED
  11636. class SSLOpenStreamTest : public ::testing::Test {
  11637. protected:
  11638. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11639. void SetUp() override {
  11640. svr_.Get("/hello", [](const Request &, Response &res) {
  11641. res.set_content("Hello SSL World!", "text/plain");
  11642. });
  11643. svr_.Get("/chunked", [](const Request &, Response &res) {
  11644. res.set_chunked_content_provider("text/plain",
  11645. [](size_t offset, DataSink &sink) {
  11646. if (offset < 15) {
  11647. sink.write("chunk", 5);
  11648. return true;
  11649. }
  11650. sink.done();
  11651. return true;
  11652. });
  11653. });
  11654. svr_.Post("/echo", [](const Request &req, Response &res) {
  11655. res.set_content(req.body, req.get_header_value("Content-Type"));
  11656. });
  11657. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11658. std::string body = req.body;
  11659. res.set_chunked_content_provider(
  11660. "text/plain", [body](size_t offset, DataSink &sink) {
  11661. if (offset < body.size()) {
  11662. sink.write(body.data() + offset, body.size() - offset);
  11663. }
  11664. sink.done();
  11665. return true;
  11666. });
  11667. });
  11668. port_ = svr_.bind_to_any_port("127.0.0.1");
  11669. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11670. svr_.wait_until_ready();
  11671. }
  11672. void TearDown() override {
  11673. svr_.stop();
  11674. if (thread_.joinable()) thread_.join();
  11675. }
  11676. SSLServer svr_;
  11677. std::thread thread_;
  11678. int port_ = 0;
  11679. };
  11680. TEST_F(SSLOpenStreamTest, Basic) {
  11681. SSLClient cli("127.0.0.1", port_);
  11682. cli.enable_server_certificate_verification(false);
  11683. auto handle = cli.open_stream("GET", "/hello");
  11684. ASSERT_TRUE(handle.is_valid());
  11685. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11686. }
  11687. TEST_F(SSLOpenStreamTest, Chunked) {
  11688. SSLClient cli("127.0.0.1", port_);
  11689. cli.enable_server_certificate_verification(false);
  11690. auto handle = cli.open_stream("GET", "/chunked");
  11691. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11692. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11693. "Transfer-Encoding") == "chunked");
  11694. auto body = read_all(handle);
  11695. EXPECT_EQ("chunkchunkchunk", body);
  11696. }
  11697. TEST_F(SSLOpenStreamTest, Post) {
  11698. SSLClient cli("127.0.0.1", port_);
  11699. cli.enable_server_certificate_verification(false);
  11700. auto handle =
  11701. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11702. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11703. EXPECT_EQ(200, handle.response->status);
  11704. auto body = read_all(handle);
  11705. EXPECT_EQ("Hello SSL POST", body);
  11706. }
  11707. TEST_F(SSLOpenStreamTest, PostChunked) {
  11708. SSLClient cli("127.0.0.1", port_);
  11709. cli.enable_server_certificate_verification(false);
  11710. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11711. "Chunked SSL Data", "text/plain");
  11712. ASSERT_TRUE(handle.is_valid());
  11713. EXPECT_EQ(200, handle.response->status);
  11714. auto body = read_all(handle);
  11715. EXPECT_EQ("Chunked SSL Data", body);
  11716. }
  11717. #endif // CPPHTTPLIB_SSL_ENABLED
  11718. //==============================================================================
  11719. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11720. // results for various scenarios.
  11721. //==============================================================================
  11722. TEST(ParityTest, GetVsOpenStream) {
  11723. Server svr;
  11724. const std::string path = "/parity";
  11725. const std::string content = "Parity test content: hello world";
  11726. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11727. res.set_content(content, "text/plain");
  11728. });
  11729. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11730. auto se = detail::scope_exit([&] {
  11731. svr.stop();
  11732. t.join();
  11733. ASSERT_FALSE(svr.is_running());
  11734. });
  11735. svr.wait_until_ready();
  11736. Client cli(HOST, PORT);
  11737. // Non-stream path
  11738. auto r1 = cli.Get(path);
  11739. ASSERT_TRUE(r1);
  11740. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11741. // Stream path
  11742. auto h = cli.open_stream("GET", path);
  11743. ASSERT_TRUE(h.is_valid());
  11744. EXPECT_EQ(r1->body, read_all(h));
  11745. }
  11746. // Helper to compress data with provided compressor type T
  11747. template <typename Compressor>
  11748. static std::string compress_payload_for_parity(const std::string &in) {
  11749. std::string out;
  11750. Compressor compressor;
  11751. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11752. [&](const char *data, size_t n) {
  11753. out.append(data, n);
  11754. return true;
  11755. });
  11756. EXPECT_TRUE(ok);
  11757. return out;
  11758. }
  11759. // Helper function for compression parity tests
  11760. template <typename Compressor>
  11761. static void test_compression_parity(const std::string &original,
  11762. const std::string &path,
  11763. const std::string &encoding) {
  11764. const std::string compressed =
  11765. compress_payload_for_parity<Compressor>(original);
  11766. Server svr;
  11767. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11768. res.set_content(compressed, "application/octet-stream");
  11769. res.set_header("Content-Encoding", encoding);
  11770. });
  11771. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11772. auto se = detail::scope_exit([&] {
  11773. svr.stop();
  11774. t.join();
  11775. ASSERT_FALSE(svr.is_running());
  11776. });
  11777. svr.wait_until_ready();
  11778. Client cli(HOST, PORT);
  11779. // Non-streaming
  11780. {
  11781. auto res = cli.Get(path);
  11782. ASSERT_TRUE(res);
  11783. EXPECT_EQ(StatusCode::OK_200, res->status);
  11784. EXPECT_EQ(original, res->body);
  11785. }
  11786. // Streaming
  11787. {
  11788. auto h = cli.open_stream("GET", path);
  11789. ASSERT_TRUE(h.is_valid());
  11790. EXPECT_EQ(original, read_all(h));
  11791. }
  11792. }
  11793. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11794. TEST(ParityTest, Gzip) {
  11795. test_compression_parity<detail::gzip_compressor>(
  11796. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11797. }
  11798. #endif
  11799. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11800. TEST(ParityTest, Brotli) {
  11801. test_compression_parity<detail::brotli_compressor>(
  11802. "Hello, brotli parity test payload", "/parity-br", "br");
  11803. }
  11804. #endif
  11805. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11806. TEST(ParityTest, Zstd) {
  11807. test_compression_parity<detail::zstd_compressor>(
  11808. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11809. }
  11810. #endif
  11811. //==============================================================================
  11812. // New Stream API Tests
  11813. //==============================================================================
  11814. inline std::string read_body(httplib::stream::Result &result) {
  11815. std::string body;
  11816. while (result.next()) {
  11817. body.append(result.data(), result.size());
  11818. }
  11819. return body;
  11820. }
  11821. TEST(ClientConnectionTest, Basic) {
  11822. httplib::ClientConnection conn;
  11823. EXPECT_FALSE(conn.is_open());
  11824. conn.sock = 1;
  11825. EXPECT_TRUE(conn.is_open());
  11826. httplib::ClientConnection conn2(std::move(conn));
  11827. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11828. conn2.sock = INVALID_SOCKET;
  11829. }
  11830. // Unified test server for all stream::* tests
  11831. class StreamApiTest : public ::testing::Test {
  11832. protected:
  11833. void SetUp() override {
  11834. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11835. res.set_content("Hello World!", "text/plain");
  11836. });
  11837. svr_.Get("/echo-params",
  11838. [](const httplib::Request &req, httplib::Response &res) {
  11839. std::string r;
  11840. for (const auto &p : req.params) {
  11841. if (!r.empty()) r += "&";
  11842. r += p.first + "=" + p.second;
  11843. }
  11844. res.set_content(r, "text/plain");
  11845. });
  11846. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11847. res.set_content(req.body, req.get_header_value("Content-Type"));
  11848. });
  11849. svr_.Post("/echo-headers",
  11850. [](const httplib::Request &req, httplib::Response &res) {
  11851. std::string r;
  11852. for (const auto &h : req.headers)
  11853. r += h.first + ": " + h.second + "\n";
  11854. res.set_content(r, "text/plain");
  11855. });
  11856. svr_.Post("/echo-params",
  11857. [](const httplib::Request &req, httplib::Response &res) {
  11858. std::string r = "params:";
  11859. for (const auto &p : req.params)
  11860. r += p.first + "=" + p.second + ";";
  11861. res.set_content(r + " body:" + req.body, "text/plain");
  11862. });
  11863. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11864. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11865. });
  11866. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11867. res.set_content("PUT:" + req.body, "text/plain");
  11868. });
  11869. svr_.Patch("/echo",
  11870. [](const httplib::Request &req, httplib::Response &res) {
  11871. res.set_content("PATCH:" + req.body, "text/plain");
  11872. });
  11873. svr_.Delete(
  11874. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11875. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11876. "text/plain");
  11877. });
  11878. svr_.Get("/head-test",
  11879. [](const httplib::Request &, httplib::Response &res) {
  11880. res.set_content("body for HEAD", "text/plain");
  11881. });
  11882. svr_.Options("/options",
  11883. [](const httplib::Request &, httplib::Response &res) {
  11884. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11885. });
  11886. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11887. svr_.wait_until_ready();
  11888. }
  11889. void TearDown() override {
  11890. svr_.stop();
  11891. if (thread_.joinable()) thread_.join();
  11892. }
  11893. httplib::Server svr_;
  11894. std::thread thread_;
  11895. };
  11896. // stream::Get tests
  11897. TEST_F(StreamApiTest, GetBasic) {
  11898. httplib::Client cli(HOST, PORT);
  11899. auto result = httplib::stream::Get(cli, "/hello");
  11900. ASSERT_TRUE(result.is_valid());
  11901. EXPECT_EQ(200, result.status());
  11902. EXPECT_EQ("Hello World!", read_body(result));
  11903. }
  11904. TEST_F(StreamApiTest, GetWithParams) {
  11905. httplib::Client cli(HOST, PORT);
  11906. httplib::Params params{{"foo", "bar"}};
  11907. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11908. ASSERT_TRUE(result.is_valid());
  11909. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11910. }
  11911. TEST_F(StreamApiTest, GetConnectionError) {
  11912. httplib::Client cli(HOST, 9999);
  11913. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11914. }
  11915. TEST_F(StreamApiTest, Get404) {
  11916. httplib::Client cli(HOST, PORT);
  11917. auto result = httplib::stream::Get(cli, "/nonexistent");
  11918. EXPECT_TRUE(result.is_valid());
  11919. EXPECT_EQ(404, result.status());
  11920. }
  11921. // stream::Post tests
  11922. TEST_F(StreamApiTest, PostBasic) {
  11923. httplib::Client cli(HOST, PORT);
  11924. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11925. "application/json");
  11926. ASSERT_TRUE(result.is_valid());
  11927. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11928. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11929. }
  11930. TEST_F(StreamApiTest, PostWithHeaders) {
  11931. httplib::Client cli(HOST, PORT);
  11932. httplib::Headers headers{{"X-Custom", "value"}};
  11933. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11934. "text/plain");
  11935. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11936. }
  11937. TEST_F(StreamApiTest, PostWithParams) {
  11938. httplib::Client cli(HOST, PORT);
  11939. httplib::Params params{{"k", "v"}};
  11940. auto result =
  11941. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11942. auto body = read_body(result);
  11943. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11944. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11945. }
  11946. TEST_F(StreamApiTest, PostLarge) {
  11947. httplib::Client cli(HOST, PORT);
  11948. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11949. size_t total = 0;
  11950. while (result.next()) {
  11951. total += result.size();
  11952. }
  11953. EXPECT_EQ(100u * 1024u, total);
  11954. }
  11955. // stream::Put/Patch tests
  11956. TEST_F(StreamApiTest, PutAndPatch) {
  11957. httplib::Client cli(HOST, PORT);
  11958. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11959. EXPECT_EQ("PUT:test", read_body(put));
  11960. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11961. EXPECT_EQ("PATCH:test", read_body(patch));
  11962. }
  11963. // stream::Delete tests
  11964. TEST_F(StreamApiTest, Delete) {
  11965. httplib::Client cli(HOST, PORT);
  11966. auto del1 = httplib::stream::Delete(cli, "/resource");
  11967. EXPECT_EQ("Deleted", read_body(del1));
  11968. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11969. EXPECT_EQ("Deleted:data", read_body(del2));
  11970. }
  11971. // stream::Head/Options tests
  11972. TEST_F(StreamApiTest, HeadAndOptions) {
  11973. httplib::Client cli(HOST, PORT);
  11974. auto head = httplib::stream::Head(cli, "/head-test");
  11975. EXPECT_TRUE(head.is_valid());
  11976. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11977. auto opts = httplib::stream::Options(cli, "/options");
  11978. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11979. }
  11980. // SSL stream::* tests
  11981. #ifdef CPPHTTPLIB_SSL_ENABLED
  11982. class SSLStreamApiTest : public ::testing::Test {
  11983. protected:
  11984. void SetUp() override {
  11985. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11986. res.set_content("Hello SSL!", "text/plain");
  11987. });
  11988. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11989. res.set_content(req.body, "text/plain");
  11990. });
  11991. port_ = svr_.bind_to_any_port("127.0.0.1");
  11992. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11993. svr_.wait_until_ready();
  11994. }
  11995. void TearDown() override {
  11996. svr_.stop();
  11997. if (thread_.joinable()) thread_.join();
  11998. }
  11999. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12000. std::thread thread_;
  12001. int port_ = 0;
  12002. };
  12003. TEST_F(SSLStreamApiTest, GetAndPost) {
  12004. httplib::SSLClient cli("127.0.0.1", port_);
  12005. cli.enable_server_certificate_verification(false);
  12006. auto get = httplib::stream::Get(cli, "/hello");
  12007. EXPECT_EQ("Hello SSL!", read_body(get));
  12008. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12009. EXPECT_EQ("test", read_body(post));
  12010. }
  12011. #endif
  12012. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12013. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12014. // BodyReader
  12015. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12016. // Test that read timeout during streaming is detected
  12017. // Use a large content-length response where server delays mid-stream
  12018. Server svr;
  12019. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12020. // Send a large response with delay in the middle
  12021. res.set_content_provider(
  12022. 1000, // content_length
  12023. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12024. if (offset < 100) {
  12025. // Send first 100 bytes immediately
  12026. std::string data(100, 'A');
  12027. sink.write(data.c_str(), data.size());
  12028. return true;
  12029. }
  12030. // Then delay longer than client timeout
  12031. std::this_thread::sleep_for(std::chrono::seconds(3));
  12032. std::string data(900, 'B');
  12033. sink.write(data.c_str(), data.size());
  12034. return true;
  12035. });
  12036. });
  12037. auto port = 8091;
  12038. std::thread t([&]() { svr.listen("localhost", port); });
  12039. svr.wait_until_ready();
  12040. Client cli("localhost", port);
  12041. cli.set_read_timeout(1, 0); // 1 second timeout
  12042. auto handle = cli.open_stream("GET", "/slow-stream");
  12043. ASSERT_TRUE(handle.is_valid());
  12044. char buf[256];
  12045. ssize_t total = 0;
  12046. ssize_t n;
  12047. bool got_error = false;
  12048. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12049. total += n;
  12050. }
  12051. if (n < 0) {
  12052. got_error = true;
  12053. // Should be timeout or read error
  12054. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12055. handle.get_read_error() == Error::Read)
  12056. << "Actual error: " << to_string(handle.get_read_error());
  12057. }
  12058. // Either we got an error, or we got less data than expected
  12059. EXPECT_TRUE(got_error || total < 1000)
  12060. << "Expected timeout but got all " << total << " bytes";
  12061. svr.stop();
  12062. t.join();
  12063. }
  12064. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12065. // Test connection closed detection via BodyReader
  12066. Server svr;
  12067. std::atomic<bool> close_now{false};
  12068. svr.Get("/will-close", [&](const Request &, Response &res) {
  12069. res.set_content_provider(
  12070. 10000, // Large content_length that we won't fully send
  12071. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12072. if (offset < 100) {
  12073. std::string data(100, 'X');
  12074. sink.write(data.c_str(), data.size());
  12075. return true;
  12076. }
  12077. // Wait for signal then abort
  12078. while (!close_now) {
  12079. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12080. }
  12081. return false; // Abort - server will close connection
  12082. });
  12083. });
  12084. auto port = 8092;
  12085. std::thread t([&]() { svr.listen("localhost", port); });
  12086. svr.wait_until_ready();
  12087. Client cli("localhost", port);
  12088. auto handle = cli.open_stream("GET", "/will-close");
  12089. ASSERT_TRUE(handle.is_valid());
  12090. char buf[256];
  12091. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12092. EXPECT_GT(n, 0) << "First read should succeed";
  12093. // Signal server to close
  12094. close_now = true;
  12095. // Keep reading until error or EOF
  12096. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12097. // Keep reading
  12098. }
  12099. // Should get an error since content_length wasn't satisfied
  12100. if (n < 0) {
  12101. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12102. handle.get_read_error() == Error::Read)
  12103. << "Actual error: " << to_string(handle.get_read_error());
  12104. }
  12105. svr.stop();
  12106. t.join();
  12107. }
  12108. #ifdef CPPHTTPLIB_SSL_ENABLED
  12109. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12110. // Test that read timeout during SSL streaming is detected
  12111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12112. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12113. res.set_content_provider(
  12114. 1000, "text/plain",
  12115. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12116. if (offset < 100) {
  12117. std::string data(100, 'A');
  12118. sink.write(data.c_str(), data.size());
  12119. return true;
  12120. }
  12121. std::this_thread::sleep_for(std::chrono::seconds(3));
  12122. std::string data(900, 'B');
  12123. sink.write(data.c_str(), data.size());
  12124. return true;
  12125. });
  12126. });
  12127. auto port = 8093;
  12128. std::thread t([&]() { svr.listen("localhost", port); });
  12129. svr.wait_until_ready();
  12130. SSLClient cli("localhost", port);
  12131. cli.enable_server_certificate_verification(false);
  12132. cli.set_read_timeout(1, 0); // 1 second timeout
  12133. auto handle = cli.open_stream("GET", "/slow-stream");
  12134. ASSERT_TRUE(handle.is_valid());
  12135. char buf[256];
  12136. ssize_t total = 0;
  12137. ssize_t n;
  12138. bool got_error = false;
  12139. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12140. total += n;
  12141. }
  12142. if (n < 0) {
  12143. got_error = true;
  12144. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12145. handle.get_read_error() == Error::Read)
  12146. << "Actual error: " << to_string(handle.get_read_error());
  12147. }
  12148. EXPECT_TRUE(got_error || total < 1000)
  12149. << "Expected timeout but got all " << total << " bytes";
  12150. svr.stop();
  12151. t.join();
  12152. }
  12153. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12154. // Test SSL connection closed detection
  12155. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12156. std::atomic<bool> close_now{false};
  12157. svr.Get("/will-close", [&](const Request &, Response &res) {
  12158. res.set_content_provider(
  12159. 10000, "text/plain",
  12160. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12161. if (offset < 100) {
  12162. std::string data(100, 'X');
  12163. sink.write(data.c_str(), data.size());
  12164. return true;
  12165. }
  12166. while (!close_now) {
  12167. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12168. }
  12169. return false;
  12170. });
  12171. });
  12172. auto port = 8094;
  12173. std::thread t([&]() { svr.listen("localhost", port); });
  12174. svr.wait_until_ready();
  12175. SSLClient cli("localhost", port);
  12176. cli.enable_server_certificate_verification(false);
  12177. auto handle = cli.open_stream("GET", "/will-close");
  12178. ASSERT_TRUE(handle.is_valid());
  12179. char buf[256];
  12180. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12181. EXPECT_GT(n, 0);
  12182. // Signal server to close
  12183. close_now = true;
  12184. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12185. // Keep reading
  12186. }
  12187. if (n < 0) {
  12188. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12189. handle.get_read_error() == Error::Read)
  12190. << "Actual error: " << to_string(handle.get_read_error());
  12191. }
  12192. svr.stop();
  12193. t.join();
  12194. }
  12195. #endif
  12196. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12197. using namespace httplib;
  12198. // Create a test file
  12199. const char *fname = "etag_testfile.txt";
  12200. const char *content = "etag-content";
  12201. {
  12202. std::ofstream ofs(fname);
  12203. ofs << content;
  12204. ASSERT_TRUE(ofs.good());
  12205. }
  12206. Server svr;
  12207. svr.set_mount_point("/static", ".");
  12208. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12209. svr.wait_until_ready();
  12210. Client cli(HOST, PORT);
  12211. // First request: should get 200 with ETag header
  12212. auto res1 = cli.Get("/static/etag_testfile.txt");
  12213. ASSERT_TRUE(res1);
  12214. ASSERT_EQ(200, res1->status);
  12215. ASSERT_TRUE(res1->has_header("ETag"));
  12216. std::string etag = res1->get_header_value("ETag");
  12217. EXPECT_FALSE(etag.empty());
  12218. // Verify ETag format: W/"hex-hex"
  12219. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12220. EXPECT_EQ('W', etag[0]);
  12221. EXPECT_EQ('/', etag[1]);
  12222. EXPECT_EQ('"', etag[2]);
  12223. EXPECT_EQ('"', etag.back());
  12224. // Exact match: expect 304 Not Modified
  12225. Headers h2 = {{"If-None-Match", etag}};
  12226. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12227. ASSERT_TRUE(res2);
  12228. EXPECT_EQ(304, res2->status);
  12229. // Wildcard match: expect 304 Not Modified
  12230. Headers h3 = {{"If-None-Match", "*"}};
  12231. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12232. ASSERT_TRUE(res3);
  12233. EXPECT_EQ(304, res3->status);
  12234. // Non-matching ETag: expect 200
  12235. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12236. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12237. ASSERT_TRUE(res4);
  12238. EXPECT_EQ(200, res4->status);
  12239. // Multiple ETags with one matching: expect 304
  12240. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12241. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12242. ASSERT_TRUE(res5);
  12243. EXPECT_EQ(304, res5->status);
  12244. svr.stop();
  12245. t.join();
  12246. std::remove(fname);
  12247. }
  12248. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12249. using namespace httplib;
  12250. Server svr;
  12251. svr.set_mount_point("/static", ".");
  12252. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12253. svr.wait_until_ready();
  12254. Client cli(HOST, PORT);
  12255. // Send If-None-Match: * to a non-existent file
  12256. Headers h = {{"If-None-Match", "*"}};
  12257. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12258. ASSERT_TRUE(res);
  12259. EXPECT_EQ(404, res->status);
  12260. svr.stop();
  12261. t.join();
  12262. }
  12263. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12264. using namespace httplib;
  12265. // Create a test file
  12266. const char *fname = "etag_boundary_testfile.txt";
  12267. const char *content = "boundary-test";
  12268. {
  12269. std::ofstream ofs(fname);
  12270. ofs << content;
  12271. ASSERT_TRUE(ofs.good());
  12272. }
  12273. Server svr;
  12274. svr.set_mount_point("/static", ".");
  12275. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12276. svr.wait_until_ready();
  12277. Client cli(HOST, PORT);
  12278. // Get the actual ETag
  12279. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12280. ASSERT_TRUE(res1);
  12281. ASSERT_EQ(200, res1->status);
  12282. ASSERT_TRUE(res1->has_header("ETag"));
  12283. std::string etag = res1->get_header_value("ETag");
  12284. // Test 1: Very long ETag value (longer than actual ETag)
  12285. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12286. Headers h1 = {{"If-None-Match", "W/"
  12287. "\"very-long-etag-value-that-is-much-longer-"
  12288. "than-the-actual-etag-value\""}};
  12289. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12290. ASSERT_TRUE(res2);
  12291. EXPECT_EQ(200, res2->status); // Should not match
  12292. // Test 2: Long string followed by wildcard
  12293. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12294. // string)
  12295. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12296. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12297. ASSERT_TRUE(res3);
  12298. EXPECT_EQ(304, res3->status); // Should match on "*"
  12299. // Test 3: Wildcard followed by long string
  12300. // Should match on "*" immediately and return 304
  12301. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12302. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12303. ASSERT_TRUE(res4);
  12304. EXPECT_EQ(304, res4->status); // Should match on "*"
  12305. // Test 4: Multiple long non-matching values
  12306. // Should NOT match and return 200 (test that all comparisons are safe)
  12307. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12308. "W/\"second-long-non-matching-value\", "
  12309. "W/\"third-long-non-matching-value\""}};
  12310. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12311. ASSERT_TRUE(res5);
  12312. EXPECT_EQ(200, res5->status); // Should not match
  12313. // Test 5: Single character that is not "*" (edge case)
  12314. Headers h5 = {{"If-None-Match", "X"}};
  12315. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12316. ASSERT_TRUE(res6);
  12317. EXPECT_EQ(200, res6->status); // Should not match
  12318. svr.stop();
  12319. t.join();
  12320. std::remove(fname);
  12321. }
  12322. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12323. using namespace httplib;
  12324. // Create a test file
  12325. const char *fname = "ims_testfile.txt";
  12326. const char *content = "if-modified-since-test";
  12327. {
  12328. std::ofstream ofs(fname);
  12329. ofs << content;
  12330. ASSERT_TRUE(ofs.good());
  12331. }
  12332. Server svr;
  12333. svr.set_mount_point("/static", ".");
  12334. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12335. svr.wait_until_ready();
  12336. Client cli(HOST, PORT);
  12337. // First request: should get 200 with Last-Modified header
  12338. auto res1 = cli.Get("/static/ims_testfile.txt");
  12339. ASSERT_TRUE(res1);
  12340. ASSERT_EQ(200, res1->status);
  12341. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12342. std::string last_modified = res1->get_header_value("Last-Modified");
  12343. EXPECT_FALSE(last_modified.empty());
  12344. // If-Modified-Since with same time: expect 304
  12345. Headers h2 = {{"If-Modified-Since", last_modified}};
  12346. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12347. ASSERT_TRUE(res2);
  12348. EXPECT_EQ(304, res2->status);
  12349. // If-Modified-Since with future time: expect 304
  12350. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12351. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12352. ASSERT_TRUE(res3);
  12353. EXPECT_EQ(304, res3->status);
  12354. // If-Modified-Since with past time: expect 200
  12355. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12356. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12357. ASSERT_TRUE(res4);
  12358. EXPECT_EQ(200, res4->status);
  12359. // If-None-Match takes precedence over If-Modified-Since
  12360. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12361. ASSERT_TRUE(res1->has_header("ETag"));
  12362. std::string etag = res1->get_header_value("ETag");
  12363. Headers h5 = {{"If-None-Match", etag},
  12364. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12365. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12366. ASSERT_TRUE(res5);
  12367. EXPECT_EQ(304, res5->status);
  12368. svr.stop();
  12369. t.join();
  12370. std::remove(fname);
  12371. }
  12372. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12373. using namespace httplib;
  12374. Server svr;
  12375. // Endpoint that returns compressible content
  12376. svr.Get("/compressible", [](const Request &, Response &res) {
  12377. // Return a large enough body to trigger compression
  12378. std::string body(1000, 'a');
  12379. res.set_content(body, "text/plain");
  12380. });
  12381. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12382. svr.wait_until_ready();
  12383. Client cli(HOST, PORT);
  12384. // Request with gzip support: should get Vary header when compressed
  12385. cli.set_compress(true);
  12386. auto res1 = cli.Get("/compressible");
  12387. ASSERT_TRUE(res1);
  12388. EXPECT_EQ(200, res1->status);
  12389. // If Content-Encoding is set, Vary should also be set
  12390. if (res1->has_header("Content-Encoding")) {
  12391. EXPECT_TRUE(res1->has_header("Vary"));
  12392. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12393. }
  12394. // Request without Accept-Encoding header: should not have compression
  12395. Headers h_no_compress;
  12396. auto res2 = cli.Get("/compressible", h_no_compress);
  12397. ASSERT_TRUE(res2);
  12398. EXPECT_EQ(200, res2->status);
  12399. // Verify Vary header is present when compression is applied
  12400. // (the exact behavior depends on server configuration)
  12401. svr.stop();
  12402. t.join();
  12403. }
  12404. TEST(ETagTest, IfRangeWithETag) {
  12405. using namespace httplib;
  12406. // Create a test file with known content
  12407. const char *fname = "if_range_testfile.txt";
  12408. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12409. {
  12410. std::ofstream ofs(fname);
  12411. ofs << content;
  12412. ASSERT_TRUE(ofs.good());
  12413. }
  12414. Server svr;
  12415. svr.set_mount_point("/static", ".");
  12416. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12417. svr.wait_until_ready();
  12418. Client cli(HOST, PORT);
  12419. // First request: get ETag
  12420. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12421. ASSERT_TRUE(res1);
  12422. ASSERT_EQ(200, res1->status);
  12423. ASSERT_TRUE(res1->has_header("ETag"));
  12424. std::string etag = res1->get_header_value("ETag");
  12425. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12426. // Since our server generates weak ETags (W/"..."), If-Range with our
  12427. // ETag should NOT result in partial content - it should return full content.
  12428. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12429. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12430. ASSERT_TRUE(res2);
  12431. // Weak ETag in If-Range -> full content (200), not partial (206)
  12432. EXPECT_EQ(200, res2->status);
  12433. EXPECT_EQ(content, res2->body);
  12434. EXPECT_FALSE(res2->has_header("Content-Range"));
  12435. // Range request with non-matching If-Range (ETag): should get 200 (full
  12436. // content)
  12437. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12438. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12439. ASSERT_TRUE(res3);
  12440. EXPECT_EQ(200, res3->status);
  12441. EXPECT_EQ(content, res3->body);
  12442. EXPECT_FALSE(res3->has_header("Content-Range"));
  12443. // Range request with strong ETag (hypothetical - our server doesn't generate
  12444. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12445. // should return full content)
  12446. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12447. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12448. ASSERT_TRUE(res4);
  12449. EXPECT_EQ(200, res4->status);
  12450. EXPECT_EQ(content, res4->body);
  12451. EXPECT_FALSE(res4->has_header("Content-Range"));
  12452. svr.stop();
  12453. t.join();
  12454. std::remove(fname);
  12455. }
  12456. TEST(ETagTest, IfRangeWithDate) {
  12457. using namespace httplib;
  12458. // Create a test file
  12459. const char *fname = "if_range_date_testfile.txt";
  12460. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12461. {
  12462. std::ofstream ofs(fname);
  12463. ofs << content;
  12464. ASSERT_TRUE(ofs.good());
  12465. }
  12466. Server svr;
  12467. svr.set_mount_point("/static", ".");
  12468. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12469. svr.wait_until_ready();
  12470. Client cli(HOST, PORT);
  12471. // First request: get Last-Modified
  12472. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12473. ASSERT_TRUE(res1);
  12474. ASSERT_EQ(200, res1->status);
  12475. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12476. std::string last_modified = res1->get_header_value("Last-Modified");
  12477. // Range request with matching If-Range (date): should get 206
  12478. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12479. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12480. ASSERT_TRUE(res2);
  12481. EXPECT_EQ(206, res2->status);
  12482. EXPECT_EQ("FGHIJ", res2->body);
  12483. // Range request with old If-Range date: should get 200 (full content)
  12484. Headers h3 = {{"Range", "bytes=5-9"},
  12485. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12486. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12487. ASSERT_TRUE(res3);
  12488. EXPECT_EQ(200, res3->status);
  12489. EXPECT_EQ(content, res3->body);
  12490. // Range request with future If-Range date: should get 206
  12491. Headers h4 = {{"Range", "bytes=0-4"},
  12492. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12493. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12494. ASSERT_TRUE(res4);
  12495. EXPECT_EQ(206, res4->status);
  12496. EXPECT_EQ("ABCDE", res4->body);
  12497. svr.stop();
  12498. t.join();
  12499. std::remove(fname);
  12500. }
  12501. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12502. using namespace httplib;
  12503. const char *fname = "etag_malformed.txt";
  12504. const char *content = "malformed-etag";
  12505. {
  12506. std::ofstream ofs(fname);
  12507. ofs << content;
  12508. ASSERT_TRUE(ofs.good());
  12509. }
  12510. Server svr;
  12511. svr.set_mount_point("/static", ".");
  12512. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12513. svr.wait_until_ready();
  12514. Client cli(HOST, PORT);
  12515. // baseline: should get 200 and an ETag
  12516. auto res1 = cli.Get("/static/etag_malformed.txt");
  12517. ASSERT_TRUE(res1);
  12518. ASSERT_EQ(200, res1->status);
  12519. ASSERT_TRUE(res1->has_header("ETag"));
  12520. // Malformed ETag value (missing quotes) should be treated as non-matching
  12521. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12522. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12523. ASSERT_TRUE(res_bad);
  12524. EXPECT_EQ(200, res_bad->status);
  12525. // Whitespace-only header value should be considered invalid / non-matching
  12526. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12527. "Host: localhost\r\n"
  12528. "If-None-Match: \r\n"
  12529. "Connection: close\r\n"
  12530. "\r\n";
  12531. std::string out;
  12532. ASSERT_TRUE(send_request(5, raw_req, &out));
  12533. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12534. svr.stop();
  12535. t.join();
  12536. std::remove(fname);
  12537. }
  12538. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12539. using namespace httplib;
  12540. const char *fname = "ims_invalid_format.txt";
  12541. const char *content = "ims-bad-format";
  12542. {
  12543. std::ofstream ofs(fname);
  12544. ofs << content;
  12545. ASSERT_TRUE(ofs.good());
  12546. }
  12547. Server svr;
  12548. svr.set_mount_point("/static", ".");
  12549. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12550. svr.wait_until_ready();
  12551. Client cli(HOST, PORT);
  12552. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12553. ASSERT_TRUE(res1);
  12554. ASSERT_EQ(200, res1->status);
  12555. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12556. // If-Modified-Since with invalid format should not result in 304
  12557. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12558. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12559. ASSERT_TRUE(res_bad);
  12560. EXPECT_EQ(200, res_bad->status);
  12561. // If-Range with invalid date format should be treated as mismatch -> full
  12562. // content (200)
  12563. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12564. {"If-Range", "invalid-date"}};
  12565. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12566. ASSERT_TRUE(res_ifrange);
  12567. EXPECT_EQ(200, res_ifrange->status);
  12568. svr.stop();
  12569. t.join();
  12570. std::remove(fname);
  12571. }
  12572. TEST(ETagTest, IfRangeWithMalformedETag) {
  12573. using namespace httplib;
  12574. const char *fname = "ifrange_malformed.txt";
  12575. const std::string content = "0123456789";
  12576. {
  12577. std::ofstream ofs(fname);
  12578. ofs << content;
  12579. ASSERT_TRUE(ofs.good());
  12580. }
  12581. Server svr;
  12582. svr.set_mount_point("/static", ".");
  12583. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12584. svr.wait_until_ready();
  12585. Client cli(HOST, PORT);
  12586. // First request: get ETag
  12587. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12588. ASSERT_TRUE(res1);
  12589. ASSERT_EQ(200, res1->status);
  12590. ASSERT_TRUE(res1->has_header("ETag"));
  12591. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12592. // full content (200)
  12593. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12594. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12595. ASSERT_TRUE(res2);
  12596. EXPECT_EQ(200, res2->status);
  12597. EXPECT_EQ(content, res2->body);
  12598. svr.stop();
  12599. t.join();
  12600. std::remove(fname);
  12601. }
  12602. TEST(ETagTest, ExtremeLargeDateValues) {
  12603. using namespace httplib;
  12604. const char *fname = "ims_extreme_date.txt";
  12605. const char *content = "ims-extreme-date";
  12606. {
  12607. std::ofstream ofs(fname);
  12608. ofs << content;
  12609. ASSERT_TRUE(ofs.good());
  12610. }
  12611. Server svr;
  12612. svr.set_mount_point("/static", ".");
  12613. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12614. svr.wait_until_ready();
  12615. Client cli(HOST, PORT);
  12616. auto res1 = cli.Get(std::string("/static/") + fname);
  12617. ASSERT_TRUE(res1);
  12618. ASSERT_EQ(200, res1->status);
  12619. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12620. // Extremely large year that may overflow date parsing routines.
  12621. Headers h_large_date = {
  12622. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12623. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12624. ASSERT_TRUE(res_bad);
  12625. // Expect server to treat this as invalid/mismatch and return full content
  12626. EXPECT_EQ(200, res_bad->status);
  12627. // If-Range with extremely large date should be treated as mismatch -> full
  12628. // content (200)
  12629. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12630. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12631. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12632. ASSERT_TRUE(res_ifrange);
  12633. EXPECT_EQ(200, res_ifrange->status);
  12634. svr.stop();
  12635. t.join();
  12636. std::remove(fname);
  12637. }
  12638. TEST(ETagTest, NegativeFileModificationTime) {
  12639. using namespace httplib;
  12640. const char *fname = "ims_negative_mtime.txt";
  12641. const std::string content = "negative-mtime";
  12642. {
  12643. std::ofstream ofs(fname);
  12644. ofs << content;
  12645. ASSERT_TRUE(ofs.good());
  12646. }
  12647. // Try to set file mtime to a negative value. This may fail on some
  12648. // platforms/filesystems; if it fails, the test will still verify server
  12649. // behaves safely by performing a regular conditional request.
  12650. #if defined(__APPLE__) || defined(__linux__)
  12651. bool set_negative = false;
  12652. do {
  12653. struct timeval times[2];
  12654. // access time: now
  12655. times[0].tv_sec = time(nullptr);
  12656. times[0].tv_usec = 0;
  12657. // modification time: negative (e.g., -1)
  12658. times[1].tv_sec = -1;
  12659. times[1].tv_usec = 0;
  12660. if (utimes(fname, times) == 0) { set_negative = true; }
  12661. } while (0);
  12662. #else
  12663. bool set_negative = false;
  12664. #endif
  12665. Server svr;
  12666. svr.set_mount_point("/static", ".");
  12667. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12668. svr.wait_until_ready();
  12669. Client cli(HOST, PORT);
  12670. auto res1 = cli.Get(std::string("/static/") + fname);
  12671. ASSERT_TRUE(res1);
  12672. ASSERT_EQ(200, res1->status);
  12673. bool has_last_modified = res1->has_header("Last-Modified");
  12674. std::string last_modified;
  12675. if (has_last_modified) {
  12676. last_modified = res1->get_header_value("Last-Modified");
  12677. }
  12678. if (set_negative) {
  12679. // If we successfully set a negative mtime, ensure server returns a
  12680. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12681. // with an old date and ensure server handles it without crash.
  12682. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12683. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12684. ASSERT_TRUE(res2);
  12685. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12686. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12687. } else {
  12688. // Could not set negative mtime on this platform; fall back to verifying
  12689. // that normal invalid/malformed dates are treated safely (non-304).
  12690. Headers h_bad_date = {
  12691. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12692. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12693. ASSERT_TRUE(res_bad);
  12694. EXPECT_EQ(200, res_bad->status);
  12695. }
  12696. svr.stop();
  12697. t.join();
  12698. std::remove(fname);
  12699. }
  12700. //==============================================================================
  12701. // SSE Parsing Tests
  12702. //==============================================================================
  12703. class SSEParsingTest : public ::testing::Test {
  12704. protected:
  12705. // Test helper that mimics SSE parsing behavior
  12706. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12707. int &retry_ms) {
  12708. // Blank line signals end of event
  12709. if (line.empty() || line == "\r") { return true; }
  12710. // Lines starting with ':' are comments (ignored)
  12711. if (!line.empty() && line[0] == ':') { return false; }
  12712. // Find the colon separator
  12713. auto colon_pos = line.find(':');
  12714. if (colon_pos == std::string::npos) {
  12715. // Line with no colon is treated as field name with empty value
  12716. return false;
  12717. }
  12718. std::string field = line.substr(0, colon_pos);
  12719. std::string value;
  12720. // Value starts after colon, skip optional single space
  12721. if (colon_pos + 1 < line.size()) {
  12722. size_t value_start = colon_pos + 1;
  12723. if (line[value_start] == ' ') { value_start++; }
  12724. value = line.substr(value_start);
  12725. // Remove trailing \r if present
  12726. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12727. }
  12728. // Handle known fields
  12729. if (field == "event") {
  12730. msg.event = value;
  12731. } else if (field == "data") {
  12732. // Multiple data lines are concatenated with newlines
  12733. if (!msg.data.empty()) { msg.data += "\n"; }
  12734. msg.data += value;
  12735. } else if (field == "id") {
  12736. // Empty id is valid (clears the last event ID)
  12737. msg.id = value;
  12738. } else if (field == "retry") {
  12739. // Parse retry interval in milliseconds
  12740. {
  12741. int v = 0;
  12742. auto res =
  12743. detail::from_chars(value.data(), value.data() + value.size(), v);
  12744. if (res.ec == std::errc{}) { retry_ms = v; }
  12745. }
  12746. }
  12747. // Unknown fields are ignored per SSE spec
  12748. return false;
  12749. }
  12750. };
  12751. // Test: Single-line data
  12752. TEST_F(SSEParsingTest, SingleLineData) {
  12753. sse::SSEMessage msg;
  12754. int retry_ms = 3000;
  12755. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12756. EXPECT_EQ(msg.data, "hello");
  12757. EXPECT_EQ(msg.event, "message");
  12758. // Blank line ends event
  12759. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12760. }
  12761. // Test: Multi-line data
  12762. TEST_F(SSEParsingTest, MultiLineData) {
  12763. sse::SSEMessage msg;
  12764. int retry_ms = 3000;
  12765. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12766. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12767. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12768. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12769. }
  12770. // Test: Custom event types
  12771. TEST_F(SSEParsingTest, CustomEventType) {
  12772. sse::SSEMessage msg;
  12773. int retry_ms = 3000;
  12774. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12775. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12776. EXPECT_EQ(msg.event, "update");
  12777. EXPECT_EQ(msg.data, "payload");
  12778. }
  12779. // Test: Event ID handling
  12780. TEST_F(SSEParsingTest, EventIdHandling) {
  12781. sse::SSEMessage msg;
  12782. int retry_ms = 3000;
  12783. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12784. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12785. EXPECT_EQ(msg.id, "12345");
  12786. }
  12787. // Test: Empty event ID (clears last event ID)
  12788. TEST_F(SSEParsingTest, EmptyEventId) {
  12789. sse::SSEMessage msg;
  12790. msg.id = "previous";
  12791. int retry_ms = 3000;
  12792. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12793. EXPECT_EQ(msg.id, "");
  12794. }
  12795. // Test: Retry field parsing
  12796. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12797. sse::SSEMessage msg;
  12798. int retry_ms = 3000;
  12799. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12800. EXPECT_EQ(retry_ms, 5000);
  12801. }
  12802. // Test: Invalid retry value
  12803. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12804. sse::SSEMessage msg;
  12805. int retry_ms = 3000;
  12806. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12807. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12808. }
  12809. // Test: Comments (lines starting with :)
  12810. TEST_F(SSEParsingTest, CommentsIgnored) {
  12811. sse::SSEMessage msg;
  12812. int retry_ms = 3000;
  12813. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12814. EXPECT_EQ(msg.data, "");
  12815. EXPECT_EQ(msg.event, "message");
  12816. }
  12817. // Test: Colon in value
  12818. TEST_F(SSEParsingTest, ColonInValue) {
  12819. sse::SSEMessage msg;
  12820. int retry_ms = 3000;
  12821. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12822. EXPECT_EQ(msg.data, "hello:world:test");
  12823. }
  12824. // Test: Line with no colon (field name only)
  12825. TEST_F(SSEParsingTest, FieldNameOnly) {
  12826. sse::SSEMessage msg;
  12827. int retry_ms = 3000;
  12828. // According to SSE spec, this is treated as field name with empty value
  12829. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12830. // Since we don't recognize "data" without colon, data should be empty
  12831. EXPECT_EQ(msg.data, "");
  12832. }
  12833. // Test: Trailing \r handling
  12834. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12835. sse::SSEMessage msg;
  12836. int retry_ms = 3000;
  12837. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12838. EXPECT_EQ(msg.data, "hello");
  12839. }
  12840. // Test: Unknown fields ignored
  12841. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12842. sse::SSEMessage msg;
  12843. int retry_ms = 3000;
  12844. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12845. EXPECT_EQ(msg.data, "");
  12846. EXPECT_EQ(msg.event, "message");
  12847. }
  12848. // Test: Space after colon is optional
  12849. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12850. sse::SSEMessage msg1, msg2;
  12851. int retry_ms = 3000;
  12852. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12853. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12854. EXPECT_EQ(msg1.data, "hello");
  12855. EXPECT_EQ(msg2.data, "hello");
  12856. }
  12857. // Test: SSEMessage clear
  12858. TEST_F(SSEParsingTest, MessageClear) {
  12859. sse::SSEMessage msg;
  12860. msg.event = "custom";
  12861. msg.data = "some data";
  12862. msg.id = "123";
  12863. msg.clear();
  12864. EXPECT_EQ(msg.event, "message");
  12865. EXPECT_EQ(msg.data, "");
  12866. EXPECT_EQ(msg.id, "");
  12867. }
  12868. // Test: Complete event parsing
  12869. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12870. sse::SSEMessage msg;
  12871. int retry_ms = 3000;
  12872. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12873. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12874. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12875. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12876. // Blank line ends event
  12877. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12878. EXPECT_EQ(msg.event, "notification");
  12879. EXPECT_EQ(msg.id, "evt-42");
  12880. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12881. EXPECT_EQ(retry_ms, 1000);
  12882. }
  12883. //==============================================================================
  12884. // Integration Tests with Server
  12885. //==============================================================================
  12886. class SSEIntegrationTest : public ::testing::Test {
  12887. protected:
  12888. void SetUp() override {
  12889. stop_server_.store(false);
  12890. events_.clear();
  12891. server_ = httplib::detail::make_unique<Server>();
  12892. setup_server();
  12893. start_server();
  12894. }
  12895. void TearDown() override {
  12896. stop_server_.store(true);
  12897. event_cv_.notify_all();
  12898. server_->stop();
  12899. if (server_thread_.joinable()) { server_thread_.join(); }
  12900. }
  12901. void setup_server() {
  12902. // Simple SSE endpoint
  12903. server_->Get("/events", [this](const Request &req, Response &res) {
  12904. auto last_id = req.get_header_value("Last-Event-ID");
  12905. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12906. res.set_chunked_content_provider(
  12907. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12908. std::unique_lock<std::mutex> lock(event_mutex_);
  12909. if (event_cv_.wait_for(
  12910. lock, std::chrono::milliseconds(200), [this] {
  12911. return !events_.empty() || stop_server_.load();
  12912. })) {
  12913. if (stop_server_.load()) { return false; }
  12914. if (!events_.empty()) {
  12915. std::string event = events_.front();
  12916. events_.erase(events_.begin());
  12917. sink.write(event.data(), event.size());
  12918. return true;
  12919. }
  12920. }
  12921. return !stop_server_.load();
  12922. });
  12923. });
  12924. // Endpoint that returns error
  12925. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12926. res.status = 500;
  12927. res.set_content("Internal Server Error", "text/plain");
  12928. });
  12929. // Endpoint for custom event types
  12930. server_->Get("/custom-events", [](const Request &, Response &res) {
  12931. res.set_chunked_content_provider(
  12932. "text/event-stream", [](size_t offset, DataSink &sink) {
  12933. if (offset == 0) {
  12934. std::string event = "event: update\ndata: updated\n\n"
  12935. "event: delete\ndata: deleted\n\n";
  12936. sink.write(event.data(), event.size());
  12937. }
  12938. return false; // End stream after sending
  12939. });
  12940. });
  12941. }
  12942. void start_server() {
  12943. port_ = server_->bind_to_any_port(HOST);
  12944. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12945. // Wait for server to start
  12946. while (!server_->is_running()) {
  12947. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12948. }
  12949. }
  12950. int get_port() const { return port_; }
  12951. void send_event(const std::string &event) {
  12952. std::lock_guard<std::mutex> lock(event_mutex_);
  12953. events_.push_back(event);
  12954. event_cv_.notify_all();
  12955. }
  12956. std::unique_ptr<Server> server_;
  12957. std::thread server_thread_;
  12958. std::mutex event_mutex_;
  12959. std::condition_variable event_cv_;
  12960. std::vector<std::string> events_;
  12961. std::atomic<bool> stop_server_{false};
  12962. std::string last_received_event_id_;
  12963. int port_ = 0;
  12964. };
  12965. // Test: Successful connection and on_open callback
  12966. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12967. // Add a simple endpoint that sends one event and closes
  12968. server_->Get("/simple-event", [](const Request &, Response &res) {
  12969. res.set_chunked_content_provider(
  12970. "text/event-stream", [](size_t offset, DataSink &sink) {
  12971. if (offset == 0) {
  12972. std::string event = "data: hello\n\n";
  12973. sink.write(event.data(), event.size());
  12974. }
  12975. return false; // Close stream after sending
  12976. });
  12977. });
  12978. Client client("localhost", get_port());
  12979. sse::SSEClient sse(client, "/simple-event");
  12980. std::atomic<bool> open_called{false};
  12981. std::atomic<bool> message_received{false};
  12982. sse.on_open([&open_called]() { open_called.store(true); });
  12983. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12984. if (msg.data == "hello") { message_received.store(true); }
  12985. });
  12986. sse.set_reconnect_interval(100);
  12987. sse.set_max_reconnect_attempts(1);
  12988. // Start async
  12989. sse.start_async();
  12990. // Wait for message to be processed
  12991. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12992. sse.stop();
  12993. EXPECT_TRUE(open_called.load());
  12994. EXPECT_TRUE(message_received.load());
  12995. }
  12996. // Test: on_message callback
  12997. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12998. // Endpoint that sends multiple events then closes
  12999. server_->Get("/multi-event", [](const Request &, Response &res) {
  13000. res.set_chunked_content_provider(
  13001. "text/event-stream", [](size_t offset, DataSink &sink) {
  13002. if (offset == 0) {
  13003. std::string events = "data: message1\n\ndata: message2\n\n";
  13004. sink.write(events.data(), events.size());
  13005. }
  13006. return false;
  13007. });
  13008. });
  13009. Client client("localhost", get_port());
  13010. sse::SSEClient sse(client, "/multi-event");
  13011. std::vector<std::string> received_messages;
  13012. std::mutex messages_mutex;
  13013. sse.on_message([&](const sse::SSEMessage &msg) {
  13014. std::lock_guard<std::mutex> lock(messages_mutex);
  13015. received_messages.push_back(msg.data);
  13016. });
  13017. sse.set_reconnect_interval(100);
  13018. sse.set_max_reconnect_attempts(1);
  13019. sse.start_async();
  13020. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13021. sse.stop();
  13022. std::lock_guard<std::mutex> lock(messages_mutex);
  13023. EXPECT_GE(received_messages.size(), 2u);
  13024. if (received_messages.size() >= 2) {
  13025. EXPECT_EQ(received_messages[0], "message1");
  13026. EXPECT_EQ(received_messages[1], "message2");
  13027. }
  13028. }
  13029. // Test: on_event for specific types
  13030. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13031. Client client("localhost", get_port());
  13032. sse::SSEClient sse(client, "/custom-events");
  13033. std::atomic<bool> update_received{false};
  13034. std::atomic<bool> delete_received{false};
  13035. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13036. if (msg.data == "updated") { update_received.store(true); }
  13037. });
  13038. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13039. if (msg.data == "deleted") { delete_received.store(true); }
  13040. });
  13041. sse.set_max_reconnect_attempts(1);
  13042. sse.start_async();
  13043. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13044. sse.stop();
  13045. EXPECT_TRUE(update_received.load());
  13046. EXPECT_TRUE(delete_received.load());
  13047. }
  13048. // Test: on_error callback on connection failure
  13049. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13050. // Connect to a non-existent port
  13051. Client client("localhost", 59999);
  13052. sse::SSEClient sse(client, "/events");
  13053. std::atomic<bool> error_called{false};
  13054. Error received_error = Error::Success;
  13055. sse.on_error([&](Error err) {
  13056. error_called.store(true);
  13057. received_error = err;
  13058. });
  13059. sse.set_reconnect_interval(50);
  13060. sse.set_max_reconnect_attempts(1);
  13061. sse.start_async();
  13062. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13063. sse.stop();
  13064. EXPECT_TRUE(error_called.load());
  13065. EXPECT_NE(received_error, Error::Success);
  13066. }
  13067. // Test: Last-Event-ID header sent on reconnect
  13068. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13069. // Endpoint that sends event with ID
  13070. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13071. res.set_chunked_content_provider(
  13072. "text/event-stream", [](size_t offset, DataSink &sink) {
  13073. if (offset == 0) {
  13074. std::string event = "id: evt-123\ndata: test\n\n";
  13075. sink.write(event.data(), event.size());
  13076. }
  13077. return false;
  13078. });
  13079. });
  13080. Client client("localhost", get_port());
  13081. sse::SSEClient sse(client, "/event-with-id");
  13082. std::atomic<bool> id_received{false};
  13083. sse.on_message([&](const sse::SSEMessage &msg) {
  13084. if (!msg.id.empty()) { id_received.store(true); }
  13085. });
  13086. sse.set_reconnect_interval(100);
  13087. sse.set_max_reconnect_attempts(1);
  13088. sse.start_async();
  13089. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13090. sse.stop();
  13091. EXPECT_TRUE(id_received.load());
  13092. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13093. }
  13094. // Test: Manual stop
  13095. TEST_F(SSEIntegrationTest, ManualStop) {
  13096. // Endpoint that sends one event and stays open briefly
  13097. std::atomic<bool> handler_running{true};
  13098. server_->Get("/stay-open", [&handler_running](const Request &,
  13099. Response &res) {
  13100. res.set_chunked_content_provider(
  13101. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13102. if (offset == 0) {
  13103. std::string event = "data: connected\n\n";
  13104. sink.write(event.data(), event.size());
  13105. }
  13106. // Keep connection open while handler_running is true
  13107. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13108. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13109. }
  13110. return false;
  13111. });
  13112. });
  13113. Client client("localhost", get_port());
  13114. sse::SSEClient sse(client, "/stay-open");
  13115. std::atomic<bool> connected{false};
  13116. sse.on_open([&connected]() { connected.store(true); });
  13117. sse.set_reconnect_interval(100);
  13118. sse.set_max_reconnect_attempts(1);
  13119. sse.start_async();
  13120. // Wait for connection to establish
  13121. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13122. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13123. }
  13124. EXPECT_TRUE(connected.load());
  13125. EXPECT_TRUE(sse.is_connected());
  13126. // Signal handler to stop
  13127. handler_running.store(false);
  13128. // Stop SSE client
  13129. sse.stop();
  13130. EXPECT_FALSE(sse.is_connected());
  13131. }
  13132. // Test: SSEClient with custom headers
  13133. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13134. // Setup a server endpoint that checks for custom header
  13135. std::atomic<bool> header_received{false};
  13136. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13137. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13138. header_received.store(true);
  13139. }
  13140. res.set_chunked_content_provider("text/event-stream",
  13141. [](size_t, DataSink &) { return false; });
  13142. });
  13143. Client client("localhost", get_port());
  13144. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13145. sse::SSEClient sse(client, "/header-check", headers);
  13146. sse.set_max_reconnect_attempts(1);
  13147. sse.start_async();
  13148. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13149. sse.stop();
  13150. EXPECT_TRUE(header_received.load());
  13151. }
  13152. // Test: Reconnect interval configuration
  13153. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13154. Client client("localhost", get_port());
  13155. sse::SSEClient sse(client, "/events");
  13156. auto &result = sse.set_reconnect_interval(500);
  13157. // Builder pattern should return reference to self
  13158. EXPECT_EQ(&result, &sse);
  13159. }
  13160. // Test: Max reconnect attempts
  13161. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13162. // Connect to non-existent port to force reconnects
  13163. Client client("localhost", 59998);
  13164. sse::SSEClient sse(client, "/events");
  13165. std::atomic<int> error_count{0};
  13166. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13167. sse.set_reconnect_interval(50);
  13168. sse.set_max_reconnect_attempts(2);
  13169. auto start = std::chrono::steady_clock::now();
  13170. sse.start(); // Blocking call
  13171. auto end = std::chrono::steady_clock::now();
  13172. // Should have stopped after 2 failed attempts
  13173. EXPECT_GE(error_count.load(), 2);
  13174. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13175. auto duration =
  13176. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13177. #ifdef _WIN32
  13178. // Windows is much slower for socket connection failures
  13179. EXPECT_LT(duration.count(), 7000);
  13180. #else
  13181. EXPECT_LT(duration.count(), 1000);
  13182. #endif
  13183. }
  13184. // Test: Multi-line data in integration
  13185. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13186. // Endpoint with multi-line data
  13187. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13188. res.set_chunked_content_provider(
  13189. "text/event-stream", [](size_t offset, DataSink &sink) {
  13190. if (offset == 0) {
  13191. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13192. sink.write(event.data(), event.size());
  13193. }
  13194. return false;
  13195. });
  13196. });
  13197. Client client("localhost", get_port());
  13198. sse::SSEClient sse(client, "/multiline-data");
  13199. std::string received_data;
  13200. std::mutex data_mutex;
  13201. sse.on_message([&](const sse::SSEMessage &msg) {
  13202. std::lock_guard<std::mutex> lock(data_mutex);
  13203. received_data = msg.data;
  13204. });
  13205. sse.set_reconnect_interval(100);
  13206. sse.set_max_reconnect_attempts(1);
  13207. sse.start_async();
  13208. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13209. sse.stop();
  13210. std::lock_guard<std::mutex> lock(data_mutex);
  13211. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13212. }
  13213. // Test: Auto-reconnect after server disconnection
  13214. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13215. std::atomic<int> connection_count{0};
  13216. std::atomic<int> message_count{0};
  13217. // Endpoint that sends one event and closes, forcing reconnect
  13218. server_->Get("/reconnect-test",
  13219. [&connection_count](const Request &, Response &res) {
  13220. connection_count.fetch_add(1);
  13221. res.set_chunked_content_provider(
  13222. "text/event-stream", [](size_t offset, DataSink &sink) {
  13223. if (offset == 0) {
  13224. std::string event = "data: hello\n\n";
  13225. sink.write(event.data(), event.size());
  13226. }
  13227. return false; // Close connection after sending
  13228. });
  13229. });
  13230. Client client("localhost", get_port());
  13231. sse::SSEClient sse(client, "/reconnect-test");
  13232. sse.on_message([&message_count](const sse::SSEMessage &) {
  13233. message_count.fetch_add(1);
  13234. });
  13235. sse.set_reconnect_interval(100);
  13236. sse.set_max_reconnect_attempts(3);
  13237. sse.start_async();
  13238. // Wait long enough for multiple reconnects
  13239. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13240. sse.stop();
  13241. // Should have connected multiple times (initial + reconnects)
  13242. EXPECT_GE(connection_count.load(), 2);
  13243. // Should have received messages from multiple connections
  13244. EXPECT_GE(message_count.load(), 2);
  13245. }
  13246. // Test: Last-Event-ID sent on reconnect
  13247. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13248. std::atomic<int> connection_count{0};
  13249. std::vector<std::string> received_last_event_ids;
  13250. std::mutex id_mutex;
  13251. // Endpoint that checks Last-Event-ID header and sends event with ID
  13252. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13253. int conn = connection_count.fetch_add(1);
  13254. // Capture the Last-Event-ID header from each connection
  13255. {
  13256. std::lock_guard<std::mutex> lock(id_mutex);
  13257. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13258. }
  13259. res.set_chunked_content_provider(
  13260. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13261. if (offset == 0) {
  13262. std::string event =
  13263. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13264. sink.write(event.data(), event.size());
  13265. }
  13266. return false;
  13267. });
  13268. });
  13269. Client client("localhost", get_port());
  13270. sse::SSEClient sse(client, "/reconnect-with-id");
  13271. sse.set_reconnect_interval(100);
  13272. sse.set_max_reconnect_attempts(3);
  13273. sse.start_async();
  13274. // Wait for at least 2 connections
  13275. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13276. sse.stop();
  13277. // Verify behavior
  13278. std::lock_guard<std::mutex> lock(id_mutex);
  13279. EXPECT_GE(received_last_event_ids.size(), 2u);
  13280. // First connection should have no Last-Event-ID
  13281. if (!received_last_event_ids.empty()) {
  13282. EXPECT_EQ(received_last_event_ids[0], "");
  13283. }
  13284. // Second connection should have Last-Event-ID from first connection
  13285. if (received_last_event_ids.size() >= 2) {
  13286. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13287. }
  13288. }
  13289. TEST(Issue2318Test, EmptyHostString) {
  13290. {
  13291. httplib::Client cli_empty("", PORT);
  13292. auto res = cli_empty.Get("/");
  13293. ASSERT_FALSE(res);
  13294. EXPECT_EQ(httplib::Error::Connection, res.error());
  13295. }
  13296. {
  13297. httplib::Client cli(" ", PORT);
  13298. auto res = cli.Get("/");
  13299. ASSERT_FALSE(res);
  13300. EXPECT_EQ(httplib::Error::Connection, res.error());
  13301. }
  13302. }
  13303. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13304. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13305. Server svr;
  13306. // Set a small payload limit (1KB)
  13307. svr.set_payload_max_length(1024);
  13308. svr.Post("/test", [&](const Request &req, Response &res) {
  13309. res.set_content("Body size: " + std::to_string(req.body.size()),
  13310. "text/plain");
  13311. });
  13312. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13313. auto se = detail::scope_exit([&] {
  13314. svr.stop();
  13315. listen_thread.join();
  13316. });
  13317. svr.wait_until_ready();
  13318. // Create data that compresses well but exceeds limit when decompressed
  13319. // 8KB of repeated null bytes compresses to a very small size
  13320. std::string original_data(8 * 1024, '\0');
  13321. // Compress the data using gzip
  13322. std::string compressed_data;
  13323. detail::gzip_compressor compressor;
  13324. compressor.compress(original_data.data(), original_data.size(), true,
  13325. [&](const char *data, size_t size) {
  13326. compressed_data.append(data, size);
  13327. return true;
  13328. });
  13329. // Verify compression worked (compressed should be much smaller)
  13330. ASSERT_LT(compressed_data.size(), original_data.size());
  13331. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13332. // Send compressed data with Content-Encoding: gzip
  13333. Client cli(HOST, PORT);
  13334. Headers headers = {{"Content-Encoding", "gzip"}};
  13335. auto res =
  13336. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13337. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13338. ASSERT_TRUE(res);
  13339. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13340. }
  13341. #endif
  13342. // ============================================================================
  13343. // OpenSSL-Specific Tests
  13344. // ============================================================================
  13345. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13346. X509 *readCertificate(const std::string &strFileName) {
  13347. std::ifstream inStream(strFileName);
  13348. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13349. std::istreambuf_iterator<char>());
  13350. if (strCertPEM.empty()) return (nullptr);
  13351. BIO *pbCert = BIO_new(BIO_s_mem());
  13352. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13353. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13354. BIO_free(pbCert);
  13355. return (pCert);
  13356. }
  13357. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13358. std::ifstream inStream(strFileName);
  13359. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13360. std::istreambuf_iterator<char>());
  13361. if (strPrivateKeyPEM.empty()) return (nullptr);
  13362. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13363. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13364. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13365. BIO_free(pbPrivKey);
  13366. return (pPrivateKey);
  13367. }
  13368. TEST(BindServerTest, UpdateCerts) {
  13369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13370. int port = svr.bind_to_any_port("0.0.0.0");
  13371. ASSERT_TRUE(svr.is_valid());
  13372. ASSERT_TRUE(port > 0);
  13373. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13374. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13375. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13376. ASSERT_TRUE(cert != nullptr);
  13377. ASSERT_TRUE(ca_cert != nullptr);
  13378. ASSERT_TRUE(key != nullptr);
  13379. X509_STORE *cert_store = X509_STORE_new();
  13380. X509_STORE_add_cert(cert_store, ca_cert);
  13381. // svr.update_certs(cert, key, cert_store); // deprecated
  13382. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13383. CLIENT_CA_CERT_FILE);
  13384. ASSERT_TRUE(svr.is_valid());
  13385. svr.stop();
  13386. X509_STORE_free(cert_store);
  13387. X509_free(cert);
  13388. X509_free(ca_cert);
  13389. EVP_PKEY_free(key);
  13390. }
  13391. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13392. // client CA list correctly for TLS handshake
  13393. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13394. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13395. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13396. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13397. ASSERT_TRUE(cert != nullptr);
  13398. ASSERT_TRUE(ca_cert != nullptr);
  13399. ASSERT_TRUE(key != nullptr);
  13400. X509_STORE *cert_store = X509_STORE_new();
  13401. X509_STORE_add_cert(cert_store, ca_cert);
  13402. // Use X509-based constructor (deprecated but should still work correctly)
  13403. #pragma GCC diagnostic push
  13404. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13405. SSLServer svr(cert, key, cert_store);
  13406. #pragma GCC diagnostic pop
  13407. ASSERT_TRUE(svr.is_valid());
  13408. // Verify that client CA list is set in SSL_CTX
  13409. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13410. ASSERT_TRUE(ssl_ctx != nullptr);
  13411. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13412. ASSERT_TRUE(ca_list != nullptr);
  13413. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13414. X509_free(cert);
  13415. X509_free(ca_cert);
  13416. EVP_PKEY_free(key);
  13417. }
  13418. // Test that update_certs() updates client CA list correctly
  13419. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13420. // Start with file-based constructor
  13421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13422. ASSERT_TRUE(svr.is_valid());
  13423. // Initially no client CA list should be set
  13424. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13425. ASSERT_TRUE(ssl_ctx != nullptr);
  13426. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13427. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13428. EXPECT_EQ(0, count_before);
  13429. // Now update with client CA (PEM string)
  13430. std::string cert_pem, key_pem, ca_pem;
  13431. read_file(SERVER_CERT_FILE, cert_pem);
  13432. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13433. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13434. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13435. ASSERT_TRUE(svr.is_valid());
  13436. // Now client CA list should be set
  13437. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13438. ASSERT_TRUE(ca_list_after != nullptr);
  13439. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13440. }
  13441. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13442. // Test that the file-path SSLServer constructor properly sets the client CA
  13443. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13445. ASSERT_TRUE(svr.is_valid());
  13446. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13447. ASSERT_TRUE(ssl_ctx != nullptr);
  13448. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13449. ASSERT_TRUE(ca_list != nullptr);
  13450. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13451. }
  13452. #endif
  13453. // ============================================================================
  13454. // MbedTLS-Specific Tests
  13455. // ============================================================================
  13456. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13457. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13458. using namespace httplib::tls;
  13459. // Track if callback was invoked
  13460. bool callback_invoked = false;
  13461. // The callback receives void* ctx which is actually MbedTlsContext*
  13462. // We can access the mbedtls_ssl_config via the context
  13463. auto setup_callback = [&callback_invoked](void *ctx) {
  13464. callback_invoked = true;
  13465. // Cast to MbedTlsContext* to access the ssl config
  13466. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13467. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13468. // Use static variables to hold certificate data (simplified for test)
  13469. static mbedtls_x509_crt own_cert;
  13470. static mbedtls_pk_context own_key;
  13471. static mbedtls_x509_crt ca_chain;
  13472. static bool initialized = false;
  13473. if (!initialized) {
  13474. mbedtls_x509_crt_init(&own_cert);
  13475. mbedtls_pk_init(&own_key);
  13476. mbedtls_x509_crt_init(&ca_chain);
  13477. // Load server certificate
  13478. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13479. return false;
  13480. }
  13481. // Load server private key
  13482. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13483. #if MBEDTLS_VERSION_MAJOR >= 3
  13484. ,
  13485. mbedtls_ctr_drbg_random, nullptr
  13486. #endif
  13487. ) != 0) {
  13488. return false;
  13489. }
  13490. // Load CA chain for client verification
  13491. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13492. return false;
  13493. }
  13494. initialized = true;
  13495. }
  13496. // Configure the SSL config
  13497. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13498. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13499. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13500. // Set minimum TLS version using mbedTLS native API
  13501. #if MBEDTLS_VERSION_MAJOR >= 3
  13502. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13503. #else
  13504. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13505. MBEDTLS_SSL_MINOR_VERSION_3);
  13506. #endif
  13507. return true;
  13508. };
  13509. SSLServer svr(setup_callback);
  13510. ASSERT_TRUE(svr.is_valid());
  13511. ASSERT_TRUE(callback_invoked);
  13512. svr.Get("/test", [&](const Request &req, Response &res) {
  13513. res.set_content("test", "text/plain");
  13514. auto cert = req.peer_cert();
  13515. ASSERT_TRUE(static_cast<bool>(cert));
  13516. auto common_name = cert.subject_cn();
  13517. EXPECT_EQ("Common Name", common_name);
  13518. });
  13519. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13520. auto se = detail::scope_exit([&] {
  13521. svr.stop();
  13522. t.join();
  13523. ASSERT_FALSE(svr.is_running());
  13524. });
  13525. svr.wait_until_ready();
  13526. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13527. cli.enable_server_certificate_verification(false);
  13528. cli.set_connection_timeout(30);
  13529. auto res = cli.Get("/test");
  13530. ASSERT_TRUE(res);
  13531. ASSERT_EQ(StatusCode::OK_200, res->status);
  13532. }
  13533. #endif
  13534. // WebSocket Tests
  13535. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13536. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13537. // defining the meaning of these bits has been negotiated.
  13538. auto make_frame = [](uint8_t first_byte) {
  13539. std::string frame;
  13540. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13541. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13542. frame += "Hello";
  13543. return frame;
  13544. };
  13545. // RSV1 set (0x40)
  13546. {
  13547. detail::BufferStream strm;
  13548. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13549. ws::Opcode opcode;
  13550. std::string payload;
  13551. bool fin;
  13552. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13553. false, 1024));
  13554. }
  13555. // RSV2 set (0x20)
  13556. {
  13557. detail::BufferStream strm;
  13558. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13559. ws::Opcode opcode;
  13560. std::string payload;
  13561. bool fin;
  13562. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13563. false, 1024));
  13564. }
  13565. // RSV3 set (0x10)
  13566. {
  13567. detail::BufferStream strm;
  13568. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13569. ws::Opcode opcode;
  13570. std::string payload;
  13571. bool fin;
  13572. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13573. false, 1024));
  13574. }
  13575. // No RSV bits set - should succeed
  13576. {
  13577. detail::BufferStream strm;
  13578. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13579. ws::Opcode opcode;
  13580. std::string payload;
  13581. bool fin;
  13582. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13583. false, 1024));
  13584. EXPECT_EQ(ws::Opcode::Text, opcode);
  13585. EXPECT_EQ("Hello", payload);
  13586. EXPECT_TRUE(fin);
  13587. }
  13588. }
  13589. TEST(WebSocketTest, ControlFrameValidation) {
  13590. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13591. // payload length <= 125.
  13592. // Ping with FIN=0 - must be rejected
  13593. {
  13594. detail::BufferStream strm;
  13595. std::string frame;
  13596. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13597. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13598. strm.write(frame.data(), frame.size());
  13599. ws::Opcode opcode;
  13600. std::string payload;
  13601. bool fin;
  13602. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13603. false, 1024));
  13604. }
  13605. // Close with FIN=0 - must be rejected
  13606. {
  13607. detail::BufferStream strm;
  13608. std::string frame;
  13609. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13610. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13611. strm.write(frame.data(), frame.size());
  13612. ws::Opcode opcode;
  13613. std::string payload;
  13614. bool fin;
  13615. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13616. false, 1024));
  13617. }
  13618. // Ping with payload_len=126 (extended length) - must be rejected
  13619. {
  13620. detail::BufferStream strm;
  13621. std::string frame;
  13622. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13623. frame += static_cast<char>(126); // payload_len=126 (>125)
  13624. frame += static_cast<char>(0x00); // extended length high byte
  13625. frame += static_cast<char>(126); // extended length low byte
  13626. frame += std::string(126, 'x');
  13627. strm.write(frame.data(), frame.size());
  13628. ws::Opcode opcode;
  13629. std::string payload;
  13630. bool fin;
  13631. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13632. false, 1024));
  13633. }
  13634. // Ping with FIN=1 and payload_len=125 - should succeed
  13635. {
  13636. detail::BufferStream strm;
  13637. std::string frame;
  13638. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13639. frame += static_cast<char>(125); // payload_len=125
  13640. frame += std::string(125, 'x');
  13641. strm.write(frame.data(), frame.size());
  13642. ws::Opcode opcode;
  13643. std::string payload;
  13644. bool fin;
  13645. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13646. false, 1024));
  13647. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13648. EXPECT_EQ(125u, payload.size());
  13649. EXPECT_TRUE(fin);
  13650. }
  13651. }
  13652. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13653. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13654. // length MUST be 0.
  13655. // MSB set - must be rejected
  13656. {
  13657. detail::BufferStream strm;
  13658. std::string frame;
  13659. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13660. frame += static_cast<char>(127); // 64-bit extended length
  13661. frame += static_cast<char>(0x80); // MSB set (invalid)
  13662. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13663. strm.write(frame.data(), frame.size());
  13664. ws::Opcode opcode;
  13665. std::string payload;
  13666. bool fin;
  13667. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13668. false, 1024));
  13669. }
  13670. // MSB clear - should pass length parsing (will be rejected by max_len,
  13671. // but that's a different check; use a small length to verify)
  13672. {
  13673. detail::BufferStream strm;
  13674. std::string frame;
  13675. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13676. frame += static_cast<char>(127); // 64-bit extended length
  13677. frame += std::string(7, '\0'); // high bytes = 0
  13678. frame += static_cast<char>(0x03); // length = 3
  13679. frame += "abc";
  13680. strm.write(frame.data(), frame.size());
  13681. ws::Opcode opcode;
  13682. std::string payload;
  13683. bool fin;
  13684. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13685. false, 1024));
  13686. EXPECT_EQ(ws::Opcode::Text, opcode);
  13687. EXPECT_EQ("abc", payload);
  13688. }
  13689. }
  13690. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13691. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13692. // Valid UTF-8
  13693. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13694. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13695. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13696. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13697. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13698. // Invalid UTF-8
  13699. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13700. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13701. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13702. EXPECT_FALSE(
  13703. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13704. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13705. }
  13706. TEST(WebSocketTest, ConnectAndDisconnect) {
  13707. Server svr;
  13708. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13709. std::string msg;
  13710. while (ws.read(msg)) {}
  13711. });
  13712. auto port = svr.bind_to_any_port(HOST);
  13713. std::thread t([&]() { svr.listen_after_bind(); });
  13714. svr.wait_until_ready();
  13715. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13716. ASSERT_TRUE(client.connect());
  13717. EXPECT_TRUE(client.is_open());
  13718. client.close();
  13719. EXPECT_FALSE(client.is_open());
  13720. svr.stop();
  13721. t.join();
  13722. }
  13723. TEST(WebSocketTest, ValidURL) {
  13724. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13725. EXPECT_TRUE(ws1.is_valid());
  13726. ws::WebSocketClient ws2("ws://example.com/path");
  13727. EXPECT_TRUE(ws2.is_valid());
  13728. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13729. EXPECT_TRUE(ws3.is_valid());
  13730. #ifdef CPPHTTPLIB_SSL_ENABLED
  13731. ws::WebSocketClient wss1("wss://example.com/path");
  13732. EXPECT_TRUE(wss1.is_valid());
  13733. ws::WebSocketClient wss2("wss://example.com:443/path");
  13734. EXPECT_TRUE(wss2.is_valid());
  13735. #endif
  13736. }
  13737. TEST(WebSocketTest, InvalidURL) {
  13738. // No scheme
  13739. ws::WebSocketClient ws1("localhost:8080/path");
  13740. EXPECT_FALSE(ws1.is_valid());
  13741. // No path
  13742. ws::WebSocketClient ws2("ws://localhost:8080");
  13743. EXPECT_FALSE(ws2.is_valid());
  13744. // Empty string
  13745. ws::WebSocketClient ws3("");
  13746. EXPECT_FALSE(ws3.is_valid());
  13747. // Missing host
  13748. ws::WebSocketClient ws4("ws://:8080/path");
  13749. EXPECT_FALSE(ws4.is_valid());
  13750. // Port number overflow — should not crash
  13751. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13752. EXPECT_FALSE(ws5.is_valid());
  13753. // Port out of range
  13754. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13755. EXPECT_FALSE(ws6.is_valid());
  13756. }
  13757. TEST(WebSocketTest, UnsupportedScheme) {
  13758. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13759. ws::WebSocketClient ws1("http://localhost:8080/path");
  13760. EXPECT_FALSE(ws1.is_valid());
  13761. ws::WebSocketClient ws2("https://localhost:8080/path");
  13762. EXPECT_FALSE(ws2.is_valid());
  13763. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13764. EXPECT_FALSE(ws3.is_valid());
  13765. #else
  13766. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13767. std::invalid_argument);
  13768. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13769. std::invalid_argument);
  13770. #endif
  13771. }
  13772. TEST(WebSocketTest, ConnectWhenInvalid) {
  13773. ws::WebSocketClient ws("not a valid url");
  13774. EXPECT_FALSE(ws.is_valid());
  13775. EXPECT_FALSE(ws.connect());
  13776. }
  13777. TEST(WebSocketTest, DefaultPort) {
  13778. ws::WebSocketClient ws1("ws://example.com/path");
  13779. EXPECT_TRUE(ws1.is_valid());
  13780. // ws:// defaults to port 80 (verified by successful parse)
  13781. #ifdef CPPHTTPLIB_SSL_ENABLED
  13782. ws::WebSocketClient ws2("wss://example.com/path");
  13783. EXPECT_TRUE(ws2.is_valid());
  13784. // wss:// defaults to port 443 (verified by successful parse)
  13785. #endif
  13786. }
  13787. TEST(WebSocketTest, IPv6LiteralAddress) {
  13788. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13789. EXPECT_TRUE(ws1.is_valid());
  13790. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13791. EXPECT_TRUE(ws2.is_valid());
  13792. }
  13793. TEST(WebSocketTest, ComplexPath) {
  13794. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13795. EXPECT_TRUE(ws1.is_valid());
  13796. ws::WebSocketClient ws2("ws://localhost:8080/");
  13797. EXPECT_TRUE(ws2.is_valid());
  13798. }
  13799. class WebSocketIntegrationTest : public ::testing::Test {
  13800. protected:
  13801. void SetUp() override {
  13802. server_ = httplib::detail::make_unique<Server>();
  13803. setup_server();
  13804. start_server();
  13805. }
  13806. void TearDown() override {
  13807. server_->stop();
  13808. if (server_thread_.joinable()) { server_thread_.join(); }
  13809. }
  13810. void setup_server() {
  13811. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13812. std::string msg;
  13813. ws::ReadResult ret;
  13814. while ((ret = ws.read(msg))) {
  13815. if (ret == ws::Binary) {
  13816. ws.send(msg.data(), msg.size());
  13817. } else {
  13818. ws.send(msg);
  13819. }
  13820. }
  13821. });
  13822. server_->WebSocket("/ws-echo-string",
  13823. [](const Request &, ws::WebSocket &ws) {
  13824. std::string msg;
  13825. while (ws.read(msg)) {
  13826. ws.send("echo: " + msg);
  13827. }
  13828. });
  13829. server_->WebSocket(
  13830. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13831. // Echo back request metadata
  13832. ws.send("path:" + req.path);
  13833. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13834. std::string msg;
  13835. while (ws.read(msg)) {}
  13836. });
  13837. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13838. std::string msg;
  13839. ws.read(msg); // wait for a message
  13840. ws.close();
  13841. });
  13842. server_->WebSocket("/ws-close-status",
  13843. [](const Request &, ws::WebSocket &ws) {
  13844. std::string msg;
  13845. ws.read(msg); // wait for a message
  13846. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13847. });
  13848. server_->WebSocket(
  13849. "/ws-subprotocol",
  13850. [](const Request &, ws::WebSocket &ws) {
  13851. std::string msg;
  13852. while (ws.read(msg)) {
  13853. ws.send(msg);
  13854. }
  13855. },
  13856. [](const std::vector<std::string> &protocols) -> std::string {
  13857. for (const auto &p : protocols) {
  13858. if (p == "graphql-ws") { return p; }
  13859. }
  13860. return "";
  13861. });
  13862. }
  13863. void start_server() {
  13864. port_ = server_->bind_to_any_port(HOST);
  13865. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13866. server_->wait_until_ready();
  13867. }
  13868. std::unique_ptr<Server> server_;
  13869. std::thread server_thread_;
  13870. int port_ = 0;
  13871. };
  13872. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13873. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13874. "/ws-echo");
  13875. ASSERT_TRUE(client.connect());
  13876. ASSERT_TRUE(client.is_open());
  13877. ASSERT_TRUE(client.send("Hello WebSocket"));
  13878. std::string msg;
  13879. EXPECT_EQ(ws::Text, client.read(msg));
  13880. EXPECT_EQ("Hello WebSocket", msg);
  13881. client.close();
  13882. }
  13883. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13884. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13885. "/ws-echo");
  13886. ASSERT_TRUE(client.connect());
  13887. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13888. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13889. std::string msg;
  13890. EXPECT_EQ(ws::Binary, client.read(msg));
  13891. EXPECT_EQ(binary_data, msg);
  13892. client.close();
  13893. }
  13894. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13895. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13896. "/ws-echo");
  13897. ASSERT_TRUE(client.connect());
  13898. for (int i = 0; i < 10; i++) {
  13899. auto text = "message " + std::to_string(i);
  13900. ASSERT_TRUE(client.send(text));
  13901. std::string msg;
  13902. ASSERT_TRUE(client.read(msg));
  13903. EXPECT_EQ(text, msg);
  13904. }
  13905. client.close();
  13906. }
  13907. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13908. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13909. "/ws-close");
  13910. ASSERT_TRUE(client.connect());
  13911. // Send a message to trigger the server to close
  13912. ASSERT_TRUE(client.send("trigger close"));
  13913. // The server will close, so read should return false
  13914. std::string msg;
  13915. EXPECT_FALSE(client.read(msg));
  13916. EXPECT_FALSE(client.is_open());
  13917. }
  13918. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13920. "/ws-echo");
  13921. ASSERT_TRUE(client.connect());
  13922. // 128KB message
  13923. std::string large_data(128 * 1024, 'X');
  13924. ASSERT_TRUE(client.send(large_data));
  13925. std::string msg;
  13926. ASSERT_TRUE(client.read(msg));
  13927. EXPECT_EQ(large_data, msg);
  13928. client.close();
  13929. }
  13930. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13931. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13932. "/ws-echo");
  13933. ASSERT_TRUE(client.connect());
  13934. const int num_threads = 4;
  13935. std::vector<std::thread> threads;
  13936. std::atomic<int> send_count{0};
  13937. for (int t = 0; t < num_threads; t++) {
  13938. threads.emplace_back([&client, &send_count, t]() {
  13939. for (int i = 0; i < 5; i++) {
  13940. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13941. if (client.send(text)) { send_count++; }
  13942. }
  13943. });
  13944. }
  13945. for (auto &th : threads) {
  13946. th.join();
  13947. }
  13948. int received = 0;
  13949. std::string msg;
  13950. while (received < send_count.load()) {
  13951. if (!client.read(msg)) { break; }
  13952. received++;
  13953. }
  13954. EXPECT_EQ(send_count.load(), received);
  13955. client.close();
  13956. }
  13957. TEST_F(WebSocketIntegrationTest, ReadString) {
  13958. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13959. "/ws-echo-string");
  13960. ASSERT_TRUE(client.connect());
  13961. ASSERT_TRUE(client.send("hello"));
  13962. std::string msg;
  13963. ASSERT_TRUE(client.read(msg));
  13964. EXPECT_EQ("echo: hello", msg);
  13965. ASSERT_TRUE(client.send("world"));
  13966. ASSERT_TRUE(client.read(msg));
  13967. EXPECT_EQ("echo: world", msg);
  13968. client.close();
  13969. }
  13970. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  13971. Headers headers = {{"X-Test-Header", "test-value"}};
  13972. ws::WebSocketClient client(
  13973. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  13974. ASSERT_TRUE(client.connect());
  13975. std::string msg;
  13976. ASSERT_TRUE(client.read(msg));
  13977. EXPECT_EQ("path:/ws-request-info", msg);
  13978. ASSERT_TRUE(client.read(msg));
  13979. EXPECT_EQ("header:test-value", msg);
  13980. client.close();
  13981. }
  13982. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  13983. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13984. "/ws-echo");
  13985. client.set_read_timeout(1, 0); // 1 second
  13986. ASSERT_TRUE(client.connect());
  13987. // Don't send anything — server echo handler waits for a message,
  13988. // so read() should time out and return false.
  13989. std::string msg;
  13990. EXPECT_FALSE(client.read(msg));
  13991. }
  13992. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  13993. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13994. "/ws-echo");
  13995. client.set_read_timeout(5, 0);
  13996. ASSERT_TRUE(client.connect());
  13997. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13998. // The server should reject it and close the connection.
  13999. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14000. client.send(oversized);
  14001. // The server's read() should have failed due to payload limit,
  14002. // so our read() should return false (connection closed).
  14003. std::string msg;
  14004. EXPECT_FALSE(client.read(msg));
  14005. }
  14006. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14007. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14008. "/ws-echo");
  14009. client.set_read_timeout(10, 0);
  14010. ASSERT_TRUE(client.connect());
  14011. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14012. // This should succeed.
  14013. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14014. ASSERT_TRUE(client.send(at_limit));
  14015. std::string msg;
  14016. ASSERT_TRUE(client.read(msg));
  14017. EXPECT_EQ(at_limit.size(), msg.size());
  14018. client.close();
  14019. }
  14020. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14021. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14022. "/nonexistent");
  14023. EXPECT_FALSE(client.connect());
  14024. EXPECT_FALSE(client.is_open());
  14025. }
  14026. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14027. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14028. "/ws-echo");
  14029. ASSERT_TRUE(client.connect());
  14030. ASSERT_TRUE(client.send(""));
  14031. std::string msg;
  14032. EXPECT_EQ(ws::Text, client.read(msg));
  14033. EXPECT_EQ("", msg);
  14034. client.close();
  14035. }
  14036. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14037. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14038. "/ws-echo");
  14039. // First connection
  14040. ASSERT_TRUE(client.connect());
  14041. ASSERT_TRUE(client.send("first"));
  14042. std::string msg;
  14043. ASSERT_TRUE(client.read(msg));
  14044. EXPECT_EQ("first", msg);
  14045. client.close();
  14046. EXPECT_FALSE(client.is_open());
  14047. // Reconnect using the same client object
  14048. ASSERT_TRUE(client.connect());
  14049. ASSERT_TRUE(client.is_open());
  14050. ASSERT_TRUE(client.send("second"));
  14051. ASSERT_TRUE(client.read(msg));
  14052. EXPECT_EQ("second", msg);
  14053. client.close();
  14054. }
  14055. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14056. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14057. "/ws-close-status");
  14058. ASSERT_TRUE(client.connect());
  14059. // Trigger the server to close with GoingAway status
  14060. ASSERT_TRUE(client.send("trigger"));
  14061. // read() should return false after receiving the close frame
  14062. std::string msg;
  14063. EXPECT_FALSE(client.read(msg));
  14064. EXPECT_FALSE(client.is_open());
  14065. }
  14066. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14067. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14068. "/ws-echo");
  14069. ASSERT_TRUE(client.connect());
  14070. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14071. EXPECT_FALSE(client.is_open());
  14072. }
  14073. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14074. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14075. ws::WebSocketClient client(
  14076. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14077. ASSERT_TRUE(client.connect());
  14078. // Server should have selected graphql-ws
  14079. EXPECT_EQ("graphql-ws", client.subprotocol());
  14080. client.close();
  14081. }
  14082. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14083. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14084. ws::WebSocketClient client(
  14085. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14086. ASSERT_TRUE(client.connect());
  14087. // Server should not have selected any subprotocol
  14088. EXPECT_TRUE(client.subprotocol().empty());
  14089. client.close();
  14090. }
  14091. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14092. // Connect without requesting any subprotocol
  14093. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14094. "/ws-subprotocol");
  14095. ASSERT_TRUE(client.connect());
  14096. EXPECT_TRUE(client.subprotocol().empty());
  14097. client.close();
  14098. }
  14099. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14100. Server svr;
  14101. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14102. if (!req.has_header("Authorization")) {
  14103. res.status = StatusCode::Unauthorized_401;
  14104. res.set_content("Unauthorized", "text/plain");
  14105. return Server::HandlerResponse::Handled;
  14106. }
  14107. return Server::HandlerResponse::Unhandled;
  14108. });
  14109. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14110. std::string msg;
  14111. while (ws.read(msg)) {
  14112. ws.send(msg);
  14113. }
  14114. });
  14115. auto port = svr.bind_to_any_port("localhost");
  14116. std::thread t([&]() { svr.listen_after_bind(); });
  14117. svr.wait_until_ready();
  14118. // Without Authorization header - should be rejected before upgrade
  14119. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14120. EXPECT_FALSE(client1.connect());
  14121. // With Authorization header - should succeed
  14122. Headers headers = {{"Authorization", "Bearer token123"}};
  14123. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14124. headers);
  14125. ASSERT_TRUE(client2.connect());
  14126. ASSERT_TRUE(client2.send("hello"));
  14127. std::string msg;
  14128. ASSERT_TRUE(client2.read(msg));
  14129. EXPECT_EQ("hello", msg);
  14130. client2.close();
  14131. svr.stop();
  14132. t.join();
  14133. }
  14134. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14135. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14136. protected:
  14137. void SetUp() override {
  14138. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14139. SERVER_PRIVATE_KEY_FILE);
  14140. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14141. std::string msg;
  14142. ws::ReadResult ret;
  14143. while ((ret = ws.read(msg))) {
  14144. if (ret == ws::Binary) {
  14145. ws.send(msg.data(), msg.size());
  14146. } else {
  14147. ws.send(msg);
  14148. }
  14149. }
  14150. });
  14151. port_ = server_->bind_to_any_port(HOST);
  14152. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14153. server_->wait_until_ready();
  14154. }
  14155. void TearDown() override {
  14156. server_->stop();
  14157. if (server_thread_.joinable()) { server_thread_.join(); }
  14158. }
  14159. std::unique_ptr<SSLServer> server_;
  14160. std::thread server_thread_;
  14161. int port_ = 0;
  14162. };
  14163. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14164. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14165. "/ws-echo");
  14166. client.enable_server_certificate_verification(false);
  14167. ASSERT_TRUE(client.connect());
  14168. ASSERT_TRUE(client.is_open());
  14169. ASSERT_TRUE(client.send("Hello WSS"));
  14170. std::string msg;
  14171. EXPECT_EQ(ws::Text, client.read(msg));
  14172. EXPECT_EQ("Hello WSS", msg);
  14173. client.close();
  14174. }
  14175. #endif
  14176. #if !defined(_WIN32)
  14177. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14178. auto secret_dir = std::string("./symlink_test_secret");
  14179. auto served_dir = std::string("./symlink_test_served");
  14180. auto secret_file = secret_dir + "/secret.txt";
  14181. auto symlink_path = served_dir + "/escape";
  14182. // Setup: create directories and files
  14183. mkdir(secret_dir.c_str(), 0755);
  14184. mkdir(served_dir.c_str(), 0755);
  14185. {
  14186. std::ofstream ofs(secret_file);
  14187. ofs << "SECRET_DATA";
  14188. }
  14189. // Create symlink using absolute path so it resolves correctly
  14190. char abs_secret[PATH_MAX];
  14191. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14192. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14193. auto se = detail::scope_exit([&] {
  14194. unlink(symlink_path.c_str());
  14195. unlink(secret_file.c_str());
  14196. rmdir(served_dir.c_str());
  14197. rmdir(secret_dir.c_str());
  14198. });
  14199. Server svr;
  14200. svr.set_mount_point("/", served_dir);
  14201. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14202. auto se2 = detail::scope_exit([&] {
  14203. svr.stop();
  14204. listen_thread.join();
  14205. });
  14206. svr.wait_until_ready();
  14207. Client cli("localhost", PORT);
  14208. // Symlink pointing outside base dir should be blocked
  14209. auto res = cli.Get("/escape/secret.txt");
  14210. ASSERT_TRUE(res);
  14211. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14212. }
  14213. #endif