test.cc 522 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069
  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(int port,
  11518. const std::string &response) {
  11519. return std::thread([port, 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(static_cast<uint16_t>(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. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11537. ::listen(srv, 1);
  11538. sockaddr_in cli_addr{};
  11539. socklen_t cli_len = sizeof(cli_addr);
  11540. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11541. if (cli != INVALID_SOCKET) {
  11542. char buf[4096];
  11543. ::recv(cli, buf, sizeof(buf), 0);
  11544. ::send(cli,
  11545. #ifdef _WIN32
  11546. static_cast<const char *>(response.c_str()),
  11547. static_cast<int>(response.size()),
  11548. #else
  11549. response.c_str(), response.size(),
  11550. #endif
  11551. 0);
  11552. detail::close_socket(cli);
  11553. }
  11554. detail::close_socket(srv);
  11555. });
  11556. }
  11557. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11558. #ifndef _WIN32
  11559. signal(SIGPIPE, SIG_IGN);
  11560. #endif
  11561. auto server_thread =
  11562. serve_single_response(PORT + 2, "HTTP/1.1 200 OK\r\n"
  11563. "Content-Type: text/plain\r\n"
  11564. "Content-Length: not-a-number\r\n"
  11565. "Connection: close\r\n"
  11566. "\r\n"
  11567. "hello");
  11568. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11569. Client cli("127.0.0.1", PORT + 2);
  11570. auto handle = cli.open_stream("GET", "/");
  11571. EXPECT_FALSE(handle.is_valid());
  11572. server_thread.join();
  11573. }
  11574. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11575. #ifndef _WIN32
  11576. signal(SIGPIPE, SIG_IGN);
  11577. #endif
  11578. auto server_thread = serve_single_response(
  11579. PORT + 4, "HTTP/1.1 200 OK\r\n"
  11580. "Content-Type: text/plain\r\n"
  11581. "Content-Length: 99999999999999999999999999\r\n"
  11582. "Connection: close\r\n"
  11583. "\r\n"
  11584. "hello");
  11585. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11586. // Before the fix, std::stoull would throw std::out_of_range here and
  11587. // crash the process. After the fix, strtoull silently clamps to
  11588. // ULLONG_MAX so the stream opens without crashing. The important thing
  11589. // is that the process does NOT terminate.
  11590. Client cli("127.0.0.1", PORT + 4);
  11591. auto handle = cli.open_stream("GET", "/");
  11592. EXPECT_TRUE(handle.is_valid());
  11593. server_thread.join();
  11594. }
  11595. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11596. TEST_F(OpenStreamTest, Gzip) {
  11597. Client cli("127.0.0.1", port_);
  11598. auto handle = cli.open_stream("GET", "/compressible", {},
  11599. {{"Accept-Encoding", "gzip"}});
  11600. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11601. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11602. }
  11603. #endif
  11604. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11605. TEST_F(OpenStreamTest, Brotli) {
  11606. Client cli("127.0.0.1", port_);
  11607. auto handle =
  11608. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11609. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11610. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11611. }
  11612. #endif
  11613. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11614. TEST_F(OpenStreamTest, Zstd) {
  11615. Client cli("127.0.0.1", port_);
  11616. auto handle = cli.open_stream("GET", "/compressible", {},
  11617. {{"Accept-Encoding", "zstd"}});
  11618. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11619. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11620. }
  11621. #endif
  11622. #ifdef CPPHTTPLIB_SSL_ENABLED
  11623. class SSLOpenStreamTest : public ::testing::Test {
  11624. protected:
  11625. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11626. void SetUp() override {
  11627. svr_.Get("/hello", [](const Request &, Response &res) {
  11628. res.set_content("Hello SSL World!", "text/plain");
  11629. });
  11630. svr_.Get("/chunked", [](const Request &, Response &res) {
  11631. res.set_chunked_content_provider("text/plain",
  11632. [](size_t offset, DataSink &sink) {
  11633. if (offset < 15) {
  11634. sink.write("chunk", 5);
  11635. return true;
  11636. }
  11637. sink.done();
  11638. return true;
  11639. });
  11640. });
  11641. svr_.Post("/echo", [](const Request &req, Response &res) {
  11642. res.set_content(req.body, req.get_header_value("Content-Type"));
  11643. });
  11644. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11645. std::string body = req.body;
  11646. res.set_chunked_content_provider(
  11647. "text/plain", [body](size_t offset, DataSink &sink) {
  11648. if (offset < body.size()) {
  11649. sink.write(body.data() + offset, body.size() - offset);
  11650. }
  11651. sink.done();
  11652. return true;
  11653. });
  11654. });
  11655. port_ = svr_.bind_to_any_port("127.0.0.1");
  11656. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11657. svr_.wait_until_ready();
  11658. }
  11659. void TearDown() override {
  11660. svr_.stop();
  11661. if (thread_.joinable()) thread_.join();
  11662. }
  11663. SSLServer svr_;
  11664. std::thread thread_;
  11665. int port_ = 0;
  11666. };
  11667. TEST_F(SSLOpenStreamTest, Basic) {
  11668. SSLClient cli("127.0.0.1", port_);
  11669. cli.enable_server_certificate_verification(false);
  11670. auto handle = cli.open_stream("GET", "/hello");
  11671. ASSERT_TRUE(handle.is_valid());
  11672. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11673. }
  11674. TEST_F(SSLOpenStreamTest, Chunked) {
  11675. SSLClient cli("127.0.0.1", port_);
  11676. cli.enable_server_certificate_verification(false);
  11677. auto handle = cli.open_stream("GET", "/chunked");
  11678. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11679. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11680. "Transfer-Encoding") == "chunked");
  11681. auto body = read_all(handle);
  11682. EXPECT_EQ("chunkchunkchunk", body);
  11683. }
  11684. TEST_F(SSLOpenStreamTest, Post) {
  11685. SSLClient cli("127.0.0.1", port_);
  11686. cli.enable_server_certificate_verification(false);
  11687. auto handle =
  11688. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11689. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11690. EXPECT_EQ(200, handle.response->status);
  11691. auto body = read_all(handle);
  11692. EXPECT_EQ("Hello SSL POST", body);
  11693. }
  11694. TEST_F(SSLOpenStreamTest, PostChunked) {
  11695. SSLClient cli("127.0.0.1", port_);
  11696. cli.enable_server_certificate_verification(false);
  11697. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11698. "Chunked SSL Data", "text/plain");
  11699. ASSERT_TRUE(handle.is_valid());
  11700. EXPECT_EQ(200, handle.response->status);
  11701. auto body = read_all(handle);
  11702. EXPECT_EQ("Chunked SSL Data", body);
  11703. }
  11704. #endif // CPPHTTPLIB_SSL_ENABLED
  11705. //==============================================================================
  11706. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11707. // results for various scenarios.
  11708. //==============================================================================
  11709. TEST(ParityTest, GetVsOpenStream) {
  11710. Server svr;
  11711. const std::string path = "/parity";
  11712. const std::string content = "Parity test content: hello world";
  11713. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11714. res.set_content(content, "text/plain");
  11715. });
  11716. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11717. auto se = detail::scope_exit([&] {
  11718. svr.stop();
  11719. t.join();
  11720. ASSERT_FALSE(svr.is_running());
  11721. });
  11722. svr.wait_until_ready();
  11723. Client cli(HOST, PORT);
  11724. // Non-stream path
  11725. auto r1 = cli.Get(path);
  11726. ASSERT_TRUE(r1);
  11727. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11728. // Stream path
  11729. auto h = cli.open_stream("GET", path);
  11730. ASSERT_TRUE(h.is_valid());
  11731. EXPECT_EQ(r1->body, read_all(h));
  11732. }
  11733. // Helper to compress data with provided compressor type T
  11734. template <typename Compressor>
  11735. static std::string compress_payload_for_parity(const std::string &in) {
  11736. std::string out;
  11737. Compressor compressor;
  11738. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11739. [&](const char *data, size_t n) {
  11740. out.append(data, n);
  11741. return true;
  11742. });
  11743. EXPECT_TRUE(ok);
  11744. return out;
  11745. }
  11746. // Helper function for compression parity tests
  11747. template <typename Compressor>
  11748. static void test_compression_parity(const std::string &original,
  11749. const std::string &path,
  11750. const std::string &encoding) {
  11751. const std::string compressed =
  11752. compress_payload_for_parity<Compressor>(original);
  11753. Server svr;
  11754. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11755. res.set_content(compressed, "application/octet-stream");
  11756. res.set_header("Content-Encoding", encoding);
  11757. });
  11758. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11759. auto se = detail::scope_exit([&] {
  11760. svr.stop();
  11761. t.join();
  11762. ASSERT_FALSE(svr.is_running());
  11763. });
  11764. svr.wait_until_ready();
  11765. Client cli(HOST, PORT);
  11766. // Non-streaming
  11767. {
  11768. auto res = cli.Get(path);
  11769. ASSERT_TRUE(res);
  11770. EXPECT_EQ(StatusCode::OK_200, res->status);
  11771. EXPECT_EQ(original, res->body);
  11772. }
  11773. // Streaming
  11774. {
  11775. auto h = cli.open_stream("GET", path);
  11776. ASSERT_TRUE(h.is_valid());
  11777. EXPECT_EQ(original, read_all(h));
  11778. }
  11779. }
  11780. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11781. TEST(ParityTest, Gzip) {
  11782. test_compression_parity<detail::gzip_compressor>(
  11783. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11784. }
  11785. #endif
  11786. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11787. TEST(ParityTest, Brotli) {
  11788. test_compression_parity<detail::brotli_compressor>(
  11789. "Hello, brotli parity test payload", "/parity-br", "br");
  11790. }
  11791. #endif
  11792. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11793. TEST(ParityTest, Zstd) {
  11794. test_compression_parity<detail::zstd_compressor>(
  11795. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11796. }
  11797. #endif
  11798. //==============================================================================
  11799. // New Stream API Tests
  11800. //==============================================================================
  11801. inline std::string read_body(httplib::stream::Result &result) {
  11802. std::string body;
  11803. while (result.next()) {
  11804. body.append(result.data(), result.size());
  11805. }
  11806. return body;
  11807. }
  11808. TEST(ClientConnectionTest, Basic) {
  11809. httplib::ClientConnection conn;
  11810. EXPECT_FALSE(conn.is_open());
  11811. conn.sock = 1;
  11812. EXPECT_TRUE(conn.is_open());
  11813. httplib::ClientConnection conn2(std::move(conn));
  11814. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11815. conn2.sock = INVALID_SOCKET;
  11816. }
  11817. // Unified test server for all stream::* tests
  11818. class StreamApiTest : public ::testing::Test {
  11819. protected:
  11820. void SetUp() override {
  11821. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11822. res.set_content("Hello World!", "text/plain");
  11823. });
  11824. svr_.Get("/echo-params",
  11825. [](const httplib::Request &req, httplib::Response &res) {
  11826. std::string r;
  11827. for (const auto &p : req.params) {
  11828. if (!r.empty()) r += "&";
  11829. r += p.first + "=" + p.second;
  11830. }
  11831. res.set_content(r, "text/plain");
  11832. });
  11833. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11834. res.set_content(req.body, req.get_header_value("Content-Type"));
  11835. });
  11836. svr_.Post("/echo-headers",
  11837. [](const httplib::Request &req, httplib::Response &res) {
  11838. std::string r;
  11839. for (const auto &h : req.headers)
  11840. r += h.first + ": " + h.second + "\n";
  11841. res.set_content(r, "text/plain");
  11842. });
  11843. svr_.Post("/echo-params",
  11844. [](const httplib::Request &req, httplib::Response &res) {
  11845. std::string r = "params:";
  11846. for (const auto &p : req.params)
  11847. r += p.first + "=" + p.second + ";";
  11848. res.set_content(r + " body:" + req.body, "text/plain");
  11849. });
  11850. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11851. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11852. });
  11853. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11854. res.set_content("PUT:" + req.body, "text/plain");
  11855. });
  11856. svr_.Patch("/echo",
  11857. [](const httplib::Request &req, httplib::Response &res) {
  11858. res.set_content("PATCH:" + req.body, "text/plain");
  11859. });
  11860. svr_.Delete(
  11861. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11862. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11863. "text/plain");
  11864. });
  11865. svr_.Get("/head-test",
  11866. [](const httplib::Request &, httplib::Response &res) {
  11867. res.set_content("body for HEAD", "text/plain");
  11868. });
  11869. svr_.Options("/options",
  11870. [](const httplib::Request &, httplib::Response &res) {
  11871. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11872. });
  11873. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11874. svr_.wait_until_ready();
  11875. }
  11876. void TearDown() override {
  11877. svr_.stop();
  11878. if (thread_.joinable()) thread_.join();
  11879. }
  11880. httplib::Server svr_;
  11881. std::thread thread_;
  11882. };
  11883. // stream::Get tests
  11884. TEST_F(StreamApiTest, GetBasic) {
  11885. httplib::Client cli(HOST, PORT);
  11886. auto result = httplib::stream::Get(cli, "/hello");
  11887. ASSERT_TRUE(result.is_valid());
  11888. EXPECT_EQ(200, result.status());
  11889. EXPECT_EQ("Hello World!", read_body(result));
  11890. }
  11891. TEST_F(StreamApiTest, GetWithParams) {
  11892. httplib::Client cli(HOST, PORT);
  11893. httplib::Params params{{"foo", "bar"}};
  11894. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11895. ASSERT_TRUE(result.is_valid());
  11896. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11897. }
  11898. TEST_F(StreamApiTest, GetConnectionError) {
  11899. httplib::Client cli(HOST, 9999);
  11900. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11901. }
  11902. TEST_F(StreamApiTest, Get404) {
  11903. httplib::Client cli(HOST, PORT);
  11904. auto result = httplib::stream::Get(cli, "/nonexistent");
  11905. EXPECT_TRUE(result.is_valid());
  11906. EXPECT_EQ(404, result.status());
  11907. }
  11908. // stream::Post tests
  11909. TEST_F(StreamApiTest, PostBasic) {
  11910. httplib::Client cli(HOST, PORT);
  11911. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11912. "application/json");
  11913. ASSERT_TRUE(result.is_valid());
  11914. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11915. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11916. }
  11917. TEST_F(StreamApiTest, PostWithHeaders) {
  11918. httplib::Client cli(HOST, PORT);
  11919. httplib::Headers headers{{"X-Custom", "value"}};
  11920. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11921. "text/plain");
  11922. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11923. }
  11924. TEST_F(StreamApiTest, PostWithParams) {
  11925. httplib::Client cli(HOST, PORT);
  11926. httplib::Params params{{"k", "v"}};
  11927. auto result =
  11928. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11929. auto body = read_body(result);
  11930. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11931. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11932. }
  11933. TEST_F(StreamApiTest, PostLarge) {
  11934. httplib::Client cli(HOST, PORT);
  11935. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11936. size_t total = 0;
  11937. while (result.next()) {
  11938. total += result.size();
  11939. }
  11940. EXPECT_EQ(100u * 1024u, total);
  11941. }
  11942. // stream::Put/Patch tests
  11943. TEST_F(StreamApiTest, PutAndPatch) {
  11944. httplib::Client cli(HOST, PORT);
  11945. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11946. EXPECT_EQ("PUT:test", read_body(put));
  11947. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11948. EXPECT_EQ("PATCH:test", read_body(patch));
  11949. }
  11950. // stream::Delete tests
  11951. TEST_F(StreamApiTest, Delete) {
  11952. httplib::Client cli(HOST, PORT);
  11953. auto del1 = httplib::stream::Delete(cli, "/resource");
  11954. EXPECT_EQ("Deleted", read_body(del1));
  11955. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11956. EXPECT_EQ("Deleted:data", read_body(del2));
  11957. }
  11958. // stream::Head/Options tests
  11959. TEST_F(StreamApiTest, HeadAndOptions) {
  11960. httplib::Client cli(HOST, PORT);
  11961. auto head = httplib::stream::Head(cli, "/head-test");
  11962. EXPECT_TRUE(head.is_valid());
  11963. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11964. auto opts = httplib::stream::Options(cli, "/options");
  11965. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11966. }
  11967. // SSL stream::* tests
  11968. #ifdef CPPHTTPLIB_SSL_ENABLED
  11969. class SSLStreamApiTest : public ::testing::Test {
  11970. protected:
  11971. void SetUp() override {
  11972. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11973. res.set_content("Hello SSL!", "text/plain");
  11974. });
  11975. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11976. res.set_content(req.body, "text/plain");
  11977. });
  11978. port_ = svr_.bind_to_any_port("127.0.0.1");
  11979. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11980. svr_.wait_until_ready();
  11981. }
  11982. void TearDown() override {
  11983. svr_.stop();
  11984. if (thread_.joinable()) thread_.join();
  11985. }
  11986. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11987. std::thread thread_;
  11988. int port_ = 0;
  11989. };
  11990. TEST_F(SSLStreamApiTest, GetAndPost) {
  11991. httplib::SSLClient cli("127.0.0.1", port_);
  11992. cli.enable_server_certificate_verification(false);
  11993. auto get = httplib::stream::Get(cli, "/hello");
  11994. EXPECT_EQ("Hello SSL!", read_body(get));
  11995. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11996. EXPECT_EQ("test", read_body(post));
  11997. }
  11998. #endif
  11999. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12000. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12001. // BodyReader
  12002. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12003. // Test that read timeout during streaming is detected
  12004. // Use a large content-length response where server delays mid-stream
  12005. Server svr;
  12006. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12007. // Send a large response with delay in the middle
  12008. res.set_content_provider(
  12009. 1000, // content_length
  12010. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12011. if (offset < 100) {
  12012. // Send first 100 bytes immediately
  12013. std::string data(100, 'A');
  12014. sink.write(data.c_str(), data.size());
  12015. return true;
  12016. }
  12017. // Then delay longer than client timeout
  12018. std::this_thread::sleep_for(std::chrono::seconds(3));
  12019. std::string data(900, 'B');
  12020. sink.write(data.c_str(), data.size());
  12021. return true;
  12022. });
  12023. });
  12024. auto port = 8091;
  12025. std::thread t([&]() { svr.listen("localhost", port); });
  12026. svr.wait_until_ready();
  12027. Client cli("localhost", port);
  12028. cli.set_read_timeout(1, 0); // 1 second timeout
  12029. auto handle = cli.open_stream("GET", "/slow-stream");
  12030. ASSERT_TRUE(handle.is_valid());
  12031. char buf[256];
  12032. ssize_t total = 0;
  12033. ssize_t n;
  12034. bool got_error = false;
  12035. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12036. total += n;
  12037. }
  12038. if (n < 0) {
  12039. got_error = true;
  12040. // Should be timeout or read error
  12041. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12042. handle.get_read_error() == Error::Read)
  12043. << "Actual error: " << to_string(handle.get_read_error());
  12044. }
  12045. // Either we got an error, or we got less data than expected
  12046. EXPECT_TRUE(got_error || total < 1000)
  12047. << "Expected timeout but got all " << total << " bytes";
  12048. svr.stop();
  12049. t.join();
  12050. }
  12051. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12052. // Test connection closed detection via BodyReader
  12053. Server svr;
  12054. std::atomic<bool> close_now{false};
  12055. svr.Get("/will-close", [&](const Request &, Response &res) {
  12056. res.set_content_provider(
  12057. 10000, // Large content_length that we won't fully send
  12058. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12059. if (offset < 100) {
  12060. std::string data(100, 'X');
  12061. sink.write(data.c_str(), data.size());
  12062. return true;
  12063. }
  12064. // Wait for signal then abort
  12065. while (!close_now) {
  12066. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12067. }
  12068. return false; // Abort - server will close connection
  12069. });
  12070. });
  12071. auto port = 8092;
  12072. std::thread t([&]() { svr.listen("localhost", port); });
  12073. svr.wait_until_ready();
  12074. Client cli("localhost", port);
  12075. auto handle = cli.open_stream("GET", "/will-close");
  12076. ASSERT_TRUE(handle.is_valid());
  12077. char buf[256];
  12078. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12079. EXPECT_GT(n, 0) << "First read should succeed";
  12080. // Signal server to close
  12081. close_now = true;
  12082. // Keep reading until error or EOF
  12083. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12084. // Keep reading
  12085. }
  12086. // Should get an error since content_length wasn't satisfied
  12087. if (n < 0) {
  12088. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12089. handle.get_read_error() == Error::Read)
  12090. << "Actual error: " << to_string(handle.get_read_error());
  12091. }
  12092. svr.stop();
  12093. t.join();
  12094. }
  12095. #ifdef CPPHTTPLIB_SSL_ENABLED
  12096. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12097. // Test that read timeout during SSL streaming is detected
  12098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12099. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12100. res.set_content_provider(
  12101. 1000, "text/plain",
  12102. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12103. if (offset < 100) {
  12104. std::string data(100, 'A');
  12105. sink.write(data.c_str(), data.size());
  12106. return true;
  12107. }
  12108. std::this_thread::sleep_for(std::chrono::seconds(3));
  12109. std::string data(900, 'B');
  12110. sink.write(data.c_str(), data.size());
  12111. return true;
  12112. });
  12113. });
  12114. auto port = 8093;
  12115. std::thread t([&]() { svr.listen("localhost", port); });
  12116. svr.wait_until_ready();
  12117. SSLClient cli("localhost", port);
  12118. cli.enable_server_certificate_verification(false);
  12119. cli.set_read_timeout(1, 0); // 1 second timeout
  12120. auto handle = cli.open_stream("GET", "/slow-stream");
  12121. ASSERT_TRUE(handle.is_valid());
  12122. char buf[256];
  12123. ssize_t total = 0;
  12124. ssize_t n;
  12125. bool got_error = false;
  12126. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12127. total += n;
  12128. }
  12129. if (n < 0) {
  12130. got_error = true;
  12131. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12132. handle.get_read_error() == Error::Read)
  12133. << "Actual error: " << to_string(handle.get_read_error());
  12134. }
  12135. EXPECT_TRUE(got_error || total < 1000)
  12136. << "Expected timeout but got all " << total << " bytes";
  12137. svr.stop();
  12138. t.join();
  12139. }
  12140. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12141. // Test SSL connection closed detection
  12142. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12143. std::atomic<bool> close_now{false};
  12144. svr.Get("/will-close", [&](const Request &, Response &res) {
  12145. res.set_content_provider(
  12146. 10000, "text/plain",
  12147. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12148. if (offset < 100) {
  12149. std::string data(100, 'X');
  12150. sink.write(data.c_str(), data.size());
  12151. return true;
  12152. }
  12153. while (!close_now) {
  12154. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12155. }
  12156. return false;
  12157. });
  12158. });
  12159. auto port = 8094;
  12160. std::thread t([&]() { svr.listen("localhost", port); });
  12161. svr.wait_until_ready();
  12162. SSLClient cli("localhost", port);
  12163. cli.enable_server_certificate_verification(false);
  12164. auto handle = cli.open_stream("GET", "/will-close");
  12165. ASSERT_TRUE(handle.is_valid());
  12166. char buf[256];
  12167. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12168. EXPECT_GT(n, 0);
  12169. // Signal server to close
  12170. close_now = true;
  12171. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12172. // Keep reading
  12173. }
  12174. if (n < 0) {
  12175. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12176. handle.get_read_error() == Error::Read)
  12177. << "Actual error: " << to_string(handle.get_read_error());
  12178. }
  12179. svr.stop();
  12180. t.join();
  12181. }
  12182. #endif
  12183. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12184. using namespace httplib;
  12185. // Create a test file
  12186. const char *fname = "etag_testfile.txt";
  12187. const char *content = "etag-content";
  12188. {
  12189. std::ofstream ofs(fname);
  12190. ofs << content;
  12191. ASSERT_TRUE(ofs.good());
  12192. }
  12193. Server svr;
  12194. svr.set_mount_point("/static", ".");
  12195. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12196. svr.wait_until_ready();
  12197. Client cli(HOST, PORT);
  12198. // First request: should get 200 with ETag header
  12199. auto res1 = cli.Get("/static/etag_testfile.txt");
  12200. ASSERT_TRUE(res1);
  12201. ASSERT_EQ(200, res1->status);
  12202. ASSERT_TRUE(res1->has_header("ETag"));
  12203. std::string etag = res1->get_header_value("ETag");
  12204. EXPECT_FALSE(etag.empty());
  12205. // Verify ETag format: W/"hex-hex"
  12206. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12207. EXPECT_EQ('W', etag[0]);
  12208. EXPECT_EQ('/', etag[1]);
  12209. EXPECT_EQ('"', etag[2]);
  12210. EXPECT_EQ('"', etag.back());
  12211. // Exact match: expect 304 Not Modified
  12212. Headers h2 = {{"If-None-Match", etag}};
  12213. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12214. ASSERT_TRUE(res2);
  12215. EXPECT_EQ(304, res2->status);
  12216. // Wildcard match: expect 304 Not Modified
  12217. Headers h3 = {{"If-None-Match", "*"}};
  12218. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12219. ASSERT_TRUE(res3);
  12220. EXPECT_EQ(304, res3->status);
  12221. // Non-matching ETag: expect 200
  12222. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12223. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12224. ASSERT_TRUE(res4);
  12225. EXPECT_EQ(200, res4->status);
  12226. // Multiple ETags with one matching: expect 304
  12227. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12228. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12229. ASSERT_TRUE(res5);
  12230. EXPECT_EQ(304, res5->status);
  12231. svr.stop();
  12232. t.join();
  12233. std::remove(fname);
  12234. }
  12235. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12236. using namespace httplib;
  12237. Server svr;
  12238. svr.set_mount_point("/static", ".");
  12239. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12240. svr.wait_until_ready();
  12241. Client cli(HOST, PORT);
  12242. // Send If-None-Match: * to a non-existent file
  12243. Headers h = {{"If-None-Match", "*"}};
  12244. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12245. ASSERT_TRUE(res);
  12246. EXPECT_EQ(404, res->status);
  12247. svr.stop();
  12248. t.join();
  12249. }
  12250. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12251. using namespace httplib;
  12252. // Create a test file
  12253. const char *fname = "etag_boundary_testfile.txt";
  12254. const char *content = "boundary-test";
  12255. {
  12256. std::ofstream ofs(fname);
  12257. ofs << content;
  12258. ASSERT_TRUE(ofs.good());
  12259. }
  12260. Server svr;
  12261. svr.set_mount_point("/static", ".");
  12262. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12263. svr.wait_until_ready();
  12264. Client cli(HOST, PORT);
  12265. // Get the actual ETag
  12266. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12267. ASSERT_TRUE(res1);
  12268. ASSERT_EQ(200, res1->status);
  12269. ASSERT_TRUE(res1->has_header("ETag"));
  12270. std::string etag = res1->get_header_value("ETag");
  12271. // Test 1: Very long ETag value (longer than actual ETag)
  12272. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12273. Headers h1 = {{"If-None-Match", "W/"
  12274. "\"very-long-etag-value-that-is-much-longer-"
  12275. "than-the-actual-etag-value\""}};
  12276. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12277. ASSERT_TRUE(res2);
  12278. EXPECT_EQ(200, res2->status); // Should not match
  12279. // Test 2: Long string followed by wildcard
  12280. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12281. // string)
  12282. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12283. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12284. ASSERT_TRUE(res3);
  12285. EXPECT_EQ(304, res3->status); // Should match on "*"
  12286. // Test 3: Wildcard followed by long string
  12287. // Should match on "*" immediately and return 304
  12288. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12289. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12290. ASSERT_TRUE(res4);
  12291. EXPECT_EQ(304, res4->status); // Should match on "*"
  12292. // Test 4: Multiple long non-matching values
  12293. // Should NOT match and return 200 (test that all comparisons are safe)
  12294. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12295. "W/\"second-long-non-matching-value\", "
  12296. "W/\"third-long-non-matching-value\""}};
  12297. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12298. ASSERT_TRUE(res5);
  12299. EXPECT_EQ(200, res5->status); // Should not match
  12300. // Test 5: Single character that is not "*" (edge case)
  12301. Headers h5 = {{"If-None-Match", "X"}};
  12302. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12303. ASSERT_TRUE(res6);
  12304. EXPECT_EQ(200, res6->status); // Should not match
  12305. svr.stop();
  12306. t.join();
  12307. std::remove(fname);
  12308. }
  12309. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12310. using namespace httplib;
  12311. // Create a test file
  12312. const char *fname = "ims_testfile.txt";
  12313. const char *content = "if-modified-since-test";
  12314. {
  12315. std::ofstream ofs(fname);
  12316. ofs << content;
  12317. ASSERT_TRUE(ofs.good());
  12318. }
  12319. Server svr;
  12320. svr.set_mount_point("/static", ".");
  12321. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12322. svr.wait_until_ready();
  12323. Client cli(HOST, PORT);
  12324. // First request: should get 200 with Last-Modified header
  12325. auto res1 = cli.Get("/static/ims_testfile.txt");
  12326. ASSERT_TRUE(res1);
  12327. ASSERT_EQ(200, res1->status);
  12328. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12329. std::string last_modified = res1->get_header_value("Last-Modified");
  12330. EXPECT_FALSE(last_modified.empty());
  12331. // If-Modified-Since with same time: expect 304
  12332. Headers h2 = {{"If-Modified-Since", last_modified}};
  12333. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12334. ASSERT_TRUE(res2);
  12335. EXPECT_EQ(304, res2->status);
  12336. // If-Modified-Since with future time: expect 304
  12337. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12338. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12339. ASSERT_TRUE(res3);
  12340. EXPECT_EQ(304, res3->status);
  12341. // If-Modified-Since with past time: expect 200
  12342. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12343. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12344. ASSERT_TRUE(res4);
  12345. EXPECT_EQ(200, res4->status);
  12346. // If-None-Match takes precedence over If-Modified-Since
  12347. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12348. ASSERT_TRUE(res1->has_header("ETag"));
  12349. std::string etag = res1->get_header_value("ETag");
  12350. Headers h5 = {{"If-None-Match", etag},
  12351. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12352. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12353. ASSERT_TRUE(res5);
  12354. EXPECT_EQ(304, res5->status);
  12355. svr.stop();
  12356. t.join();
  12357. std::remove(fname);
  12358. }
  12359. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12360. using namespace httplib;
  12361. Server svr;
  12362. // Endpoint that returns compressible content
  12363. svr.Get("/compressible", [](const Request &, Response &res) {
  12364. // Return a large enough body to trigger compression
  12365. std::string body(1000, 'a');
  12366. res.set_content(body, "text/plain");
  12367. });
  12368. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12369. svr.wait_until_ready();
  12370. Client cli(HOST, PORT);
  12371. // Request with gzip support: should get Vary header when compressed
  12372. cli.set_compress(true);
  12373. auto res1 = cli.Get("/compressible");
  12374. ASSERT_TRUE(res1);
  12375. EXPECT_EQ(200, res1->status);
  12376. // If Content-Encoding is set, Vary should also be set
  12377. if (res1->has_header("Content-Encoding")) {
  12378. EXPECT_TRUE(res1->has_header("Vary"));
  12379. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12380. }
  12381. // Request without Accept-Encoding header: should not have compression
  12382. Headers h_no_compress;
  12383. auto res2 = cli.Get("/compressible", h_no_compress);
  12384. ASSERT_TRUE(res2);
  12385. EXPECT_EQ(200, res2->status);
  12386. // Verify Vary header is present when compression is applied
  12387. // (the exact behavior depends on server configuration)
  12388. svr.stop();
  12389. t.join();
  12390. }
  12391. TEST(ETagTest, IfRangeWithETag) {
  12392. using namespace httplib;
  12393. // Create a test file with known content
  12394. const char *fname = "if_range_testfile.txt";
  12395. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12396. {
  12397. std::ofstream ofs(fname);
  12398. ofs << content;
  12399. ASSERT_TRUE(ofs.good());
  12400. }
  12401. Server svr;
  12402. svr.set_mount_point("/static", ".");
  12403. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12404. svr.wait_until_ready();
  12405. Client cli(HOST, PORT);
  12406. // First request: get ETag
  12407. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12408. ASSERT_TRUE(res1);
  12409. ASSERT_EQ(200, res1->status);
  12410. ASSERT_TRUE(res1->has_header("ETag"));
  12411. std::string etag = res1->get_header_value("ETag");
  12412. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12413. // Since our server generates weak ETags (W/"..."), If-Range with our
  12414. // ETag should NOT result in partial content - it should return full content.
  12415. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12416. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12417. ASSERT_TRUE(res2);
  12418. // Weak ETag in If-Range -> full content (200), not partial (206)
  12419. EXPECT_EQ(200, res2->status);
  12420. EXPECT_EQ(content, res2->body);
  12421. EXPECT_FALSE(res2->has_header("Content-Range"));
  12422. // Range request with non-matching If-Range (ETag): should get 200 (full
  12423. // content)
  12424. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12425. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12426. ASSERT_TRUE(res3);
  12427. EXPECT_EQ(200, res3->status);
  12428. EXPECT_EQ(content, res3->body);
  12429. EXPECT_FALSE(res3->has_header("Content-Range"));
  12430. // Range request with strong ETag (hypothetical - our server doesn't generate
  12431. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12432. // should return full content)
  12433. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12434. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12435. ASSERT_TRUE(res4);
  12436. EXPECT_EQ(200, res4->status);
  12437. EXPECT_EQ(content, res4->body);
  12438. EXPECT_FALSE(res4->has_header("Content-Range"));
  12439. svr.stop();
  12440. t.join();
  12441. std::remove(fname);
  12442. }
  12443. TEST(ETagTest, IfRangeWithDate) {
  12444. using namespace httplib;
  12445. // Create a test file
  12446. const char *fname = "if_range_date_testfile.txt";
  12447. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12448. {
  12449. std::ofstream ofs(fname);
  12450. ofs << content;
  12451. ASSERT_TRUE(ofs.good());
  12452. }
  12453. Server svr;
  12454. svr.set_mount_point("/static", ".");
  12455. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12456. svr.wait_until_ready();
  12457. Client cli(HOST, PORT);
  12458. // First request: get Last-Modified
  12459. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12460. ASSERT_TRUE(res1);
  12461. ASSERT_EQ(200, res1->status);
  12462. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12463. std::string last_modified = res1->get_header_value("Last-Modified");
  12464. // Range request with matching If-Range (date): should get 206
  12465. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12466. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12467. ASSERT_TRUE(res2);
  12468. EXPECT_EQ(206, res2->status);
  12469. EXPECT_EQ("FGHIJ", res2->body);
  12470. // Range request with old If-Range date: should get 200 (full content)
  12471. Headers h3 = {{"Range", "bytes=5-9"},
  12472. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12473. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12474. ASSERT_TRUE(res3);
  12475. EXPECT_EQ(200, res3->status);
  12476. EXPECT_EQ(content, res3->body);
  12477. // Range request with future If-Range date: should get 206
  12478. Headers h4 = {{"Range", "bytes=0-4"},
  12479. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12480. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12481. ASSERT_TRUE(res4);
  12482. EXPECT_EQ(206, res4->status);
  12483. EXPECT_EQ("ABCDE", res4->body);
  12484. svr.stop();
  12485. t.join();
  12486. std::remove(fname);
  12487. }
  12488. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12489. using namespace httplib;
  12490. const char *fname = "etag_malformed.txt";
  12491. const char *content = "malformed-etag";
  12492. {
  12493. std::ofstream ofs(fname);
  12494. ofs << content;
  12495. ASSERT_TRUE(ofs.good());
  12496. }
  12497. Server svr;
  12498. svr.set_mount_point("/static", ".");
  12499. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12500. svr.wait_until_ready();
  12501. Client cli(HOST, PORT);
  12502. // baseline: should get 200 and an ETag
  12503. auto res1 = cli.Get("/static/etag_malformed.txt");
  12504. ASSERT_TRUE(res1);
  12505. ASSERT_EQ(200, res1->status);
  12506. ASSERT_TRUE(res1->has_header("ETag"));
  12507. // Malformed ETag value (missing quotes) should be treated as non-matching
  12508. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12509. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12510. ASSERT_TRUE(res_bad);
  12511. EXPECT_EQ(200, res_bad->status);
  12512. // Whitespace-only header value should be considered invalid / non-matching
  12513. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12514. "Host: localhost\r\n"
  12515. "If-None-Match: \r\n"
  12516. "Connection: close\r\n"
  12517. "\r\n";
  12518. std::string out;
  12519. ASSERT_TRUE(send_request(5, raw_req, &out));
  12520. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12521. svr.stop();
  12522. t.join();
  12523. std::remove(fname);
  12524. }
  12525. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12526. using namespace httplib;
  12527. const char *fname = "ims_invalid_format.txt";
  12528. const char *content = "ims-bad-format";
  12529. {
  12530. std::ofstream ofs(fname);
  12531. ofs << content;
  12532. ASSERT_TRUE(ofs.good());
  12533. }
  12534. Server svr;
  12535. svr.set_mount_point("/static", ".");
  12536. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12537. svr.wait_until_ready();
  12538. Client cli(HOST, PORT);
  12539. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12540. ASSERT_TRUE(res1);
  12541. ASSERT_EQ(200, res1->status);
  12542. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12543. // If-Modified-Since with invalid format should not result in 304
  12544. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12545. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12546. ASSERT_TRUE(res_bad);
  12547. EXPECT_EQ(200, res_bad->status);
  12548. // If-Range with invalid date format should be treated as mismatch -> full
  12549. // content (200)
  12550. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12551. {"If-Range", "invalid-date"}};
  12552. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12553. ASSERT_TRUE(res_ifrange);
  12554. EXPECT_EQ(200, res_ifrange->status);
  12555. svr.stop();
  12556. t.join();
  12557. std::remove(fname);
  12558. }
  12559. TEST(ETagTest, IfRangeWithMalformedETag) {
  12560. using namespace httplib;
  12561. const char *fname = "ifrange_malformed.txt";
  12562. const std::string content = "0123456789";
  12563. {
  12564. std::ofstream ofs(fname);
  12565. ofs << content;
  12566. ASSERT_TRUE(ofs.good());
  12567. }
  12568. Server svr;
  12569. svr.set_mount_point("/static", ".");
  12570. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12571. svr.wait_until_ready();
  12572. Client cli(HOST, PORT);
  12573. // First request: get ETag
  12574. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12575. ASSERT_TRUE(res1);
  12576. ASSERT_EQ(200, res1->status);
  12577. ASSERT_TRUE(res1->has_header("ETag"));
  12578. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12579. // full content (200)
  12580. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12581. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12582. ASSERT_TRUE(res2);
  12583. EXPECT_EQ(200, res2->status);
  12584. EXPECT_EQ(content, res2->body);
  12585. svr.stop();
  12586. t.join();
  12587. std::remove(fname);
  12588. }
  12589. TEST(ETagTest, ExtremeLargeDateValues) {
  12590. using namespace httplib;
  12591. const char *fname = "ims_extreme_date.txt";
  12592. const char *content = "ims-extreme-date";
  12593. {
  12594. std::ofstream ofs(fname);
  12595. ofs << content;
  12596. ASSERT_TRUE(ofs.good());
  12597. }
  12598. Server svr;
  12599. svr.set_mount_point("/static", ".");
  12600. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12601. svr.wait_until_ready();
  12602. Client cli(HOST, PORT);
  12603. auto res1 = cli.Get(std::string("/static/") + fname);
  12604. ASSERT_TRUE(res1);
  12605. ASSERT_EQ(200, res1->status);
  12606. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12607. // Extremely large year that may overflow date parsing routines.
  12608. Headers h_large_date = {
  12609. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12610. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12611. ASSERT_TRUE(res_bad);
  12612. // Expect server to treat this as invalid/mismatch and return full content
  12613. EXPECT_EQ(200, res_bad->status);
  12614. // If-Range with extremely large date should be treated as mismatch -> full
  12615. // content (200)
  12616. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12617. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12618. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12619. ASSERT_TRUE(res_ifrange);
  12620. EXPECT_EQ(200, res_ifrange->status);
  12621. svr.stop();
  12622. t.join();
  12623. std::remove(fname);
  12624. }
  12625. TEST(ETagTest, NegativeFileModificationTime) {
  12626. using namespace httplib;
  12627. const char *fname = "ims_negative_mtime.txt";
  12628. const std::string content = "negative-mtime";
  12629. {
  12630. std::ofstream ofs(fname);
  12631. ofs << content;
  12632. ASSERT_TRUE(ofs.good());
  12633. }
  12634. // Try to set file mtime to a negative value. This may fail on some
  12635. // platforms/filesystems; if it fails, the test will still verify server
  12636. // behaves safely by performing a regular conditional request.
  12637. #if defined(__APPLE__) || defined(__linux__)
  12638. bool set_negative = false;
  12639. do {
  12640. struct timeval times[2];
  12641. // access time: now
  12642. times[0].tv_sec = time(nullptr);
  12643. times[0].tv_usec = 0;
  12644. // modification time: negative (e.g., -1)
  12645. times[1].tv_sec = -1;
  12646. times[1].tv_usec = 0;
  12647. if (utimes(fname, times) == 0) { set_negative = true; }
  12648. } while (0);
  12649. #else
  12650. bool set_negative = false;
  12651. #endif
  12652. Server svr;
  12653. svr.set_mount_point("/static", ".");
  12654. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12655. svr.wait_until_ready();
  12656. Client cli(HOST, PORT);
  12657. auto res1 = cli.Get(std::string("/static/") + fname);
  12658. ASSERT_TRUE(res1);
  12659. ASSERT_EQ(200, res1->status);
  12660. bool has_last_modified = res1->has_header("Last-Modified");
  12661. std::string last_modified;
  12662. if (has_last_modified) {
  12663. last_modified = res1->get_header_value("Last-Modified");
  12664. }
  12665. if (set_negative) {
  12666. // If we successfully set a negative mtime, ensure server returns a
  12667. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12668. // with an old date and ensure server handles it without crash.
  12669. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12670. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12671. ASSERT_TRUE(res2);
  12672. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12673. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12674. } else {
  12675. // Could not set negative mtime on this platform; fall back to verifying
  12676. // that normal invalid/malformed dates are treated safely (non-304).
  12677. Headers h_bad_date = {
  12678. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12679. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12680. ASSERT_TRUE(res_bad);
  12681. EXPECT_EQ(200, res_bad->status);
  12682. }
  12683. svr.stop();
  12684. t.join();
  12685. std::remove(fname);
  12686. }
  12687. //==============================================================================
  12688. // SSE Parsing Tests
  12689. //==============================================================================
  12690. class SSEParsingTest : public ::testing::Test {
  12691. protected:
  12692. // Test helper that mimics SSE parsing behavior
  12693. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12694. int &retry_ms) {
  12695. // Blank line signals end of event
  12696. if (line.empty() || line == "\r") { return true; }
  12697. // Lines starting with ':' are comments (ignored)
  12698. if (!line.empty() && line[0] == ':') { return false; }
  12699. // Find the colon separator
  12700. auto colon_pos = line.find(':');
  12701. if (colon_pos == std::string::npos) {
  12702. // Line with no colon is treated as field name with empty value
  12703. return false;
  12704. }
  12705. std::string field = line.substr(0, colon_pos);
  12706. std::string value;
  12707. // Value starts after colon, skip optional single space
  12708. if (colon_pos + 1 < line.size()) {
  12709. size_t value_start = colon_pos + 1;
  12710. if (line[value_start] == ' ') { value_start++; }
  12711. value = line.substr(value_start);
  12712. // Remove trailing \r if present
  12713. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12714. }
  12715. // Handle known fields
  12716. if (field == "event") {
  12717. msg.event = value;
  12718. } else if (field == "data") {
  12719. // Multiple data lines are concatenated with newlines
  12720. if (!msg.data.empty()) { msg.data += "\n"; }
  12721. msg.data += value;
  12722. } else if (field == "id") {
  12723. // Empty id is valid (clears the last event ID)
  12724. msg.id = value;
  12725. } else if (field == "retry") {
  12726. // Parse retry interval in milliseconds
  12727. {
  12728. int v = 0;
  12729. auto res =
  12730. detail::from_chars(value.data(), value.data() + value.size(), v);
  12731. if (res.ec == std::errc{}) { retry_ms = v; }
  12732. }
  12733. }
  12734. // Unknown fields are ignored per SSE spec
  12735. return false;
  12736. }
  12737. };
  12738. // Test: Single-line data
  12739. TEST_F(SSEParsingTest, SingleLineData) {
  12740. sse::SSEMessage msg;
  12741. int retry_ms = 3000;
  12742. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12743. EXPECT_EQ(msg.data, "hello");
  12744. EXPECT_EQ(msg.event, "message");
  12745. // Blank line ends event
  12746. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12747. }
  12748. // Test: Multi-line data
  12749. TEST_F(SSEParsingTest, MultiLineData) {
  12750. sse::SSEMessage msg;
  12751. int retry_ms = 3000;
  12752. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12753. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12754. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12755. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12756. }
  12757. // Test: Custom event types
  12758. TEST_F(SSEParsingTest, CustomEventType) {
  12759. sse::SSEMessage msg;
  12760. int retry_ms = 3000;
  12761. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12762. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12763. EXPECT_EQ(msg.event, "update");
  12764. EXPECT_EQ(msg.data, "payload");
  12765. }
  12766. // Test: Event ID handling
  12767. TEST_F(SSEParsingTest, EventIdHandling) {
  12768. sse::SSEMessage msg;
  12769. int retry_ms = 3000;
  12770. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12771. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12772. EXPECT_EQ(msg.id, "12345");
  12773. }
  12774. // Test: Empty event ID (clears last event ID)
  12775. TEST_F(SSEParsingTest, EmptyEventId) {
  12776. sse::SSEMessage msg;
  12777. msg.id = "previous";
  12778. int retry_ms = 3000;
  12779. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12780. EXPECT_EQ(msg.id, "");
  12781. }
  12782. // Test: Retry field parsing
  12783. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12784. sse::SSEMessage msg;
  12785. int retry_ms = 3000;
  12786. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12787. EXPECT_EQ(retry_ms, 5000);
  12788. }
  12789. // Test: Invalid retry value
  12790. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12791. sse::SSEMessage msg;
  12792. int retry_ms = 3000;
  12793. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12794. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12795. }
  12796. // Test: Comments (lines starting with :)
  12797. TEST_F(SSEParsingTest, CommentsIgnored) {
  12798. sse::SSEMessage msg;
  12799. int retry_ms = 3000;
  12800. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12801. EXPECT_EQ(msg.data, "");
  12802. EXPECT_EQ(msg.event, "message");
  12803. }
  12804. // Test: Colon in value
  12805. TEST_F(SSEParsingTest, ColonInValue) {
  12806. sse::SSEMessage msg;
  12807. int retry_ms = 3000;
  12808. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12809. EXPECT_EQ(msg.data, "hello:world:test");
  12810. }
  12811. // Test: Line with no colon (field name only)
  12812. TEST_F(SSEParsingTest, FieldNameOnly) {
  12813. sse::SSEMessage msg;
  12814. int retry_ms = 3000;
  12815. // According to SSE spec, this is treated as field name with empty value
  12816. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12817. // Since we don't recognize "data" without colon, data should be empty
  12818. EXPECT_EQ(msg.data, "");
  12819. }
  12820. // Test: Trailing \r handling
  12821. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12822. sse::SSEMessage msg;
  12823. int retry_ms = 3000;
  12824. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12825. EXPECT_EQ(msg.data, "hello");
  12826. }
  12827. // Test: Unknown fields ignored
  12828. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12829. sse::SSEMessage msg;
  12830. int retry_ms = 3000;
  12831. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12832. EXPECT_EQ(msg.data, "");
  12833. EXPECT_EQ(msg.event, "message");
  12834. }
  12835. // Test: Space after colon is optional
  12836. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12837. sse::SSEMessage msg1, msg2;
  12838. int retry_ms = 3000;
  12839. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12840. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12841. EXPECT_EQ(msg1.data, "hello");
  12842. EXPECT_EQ(msg2.data, "hello");
  12843. }
  12844. // Test: SSEMessage clear
  12845. TEST_F(SSEParsingTest, MessageClear) {
  12846. sse::SSEMessage msg;
  12847. msg.event = "custom";
  12848. msg.data = "some data";
  12849. msg.id = "123";
  12850. msg.clear();
  12851. EXPECT_EQ(msg.event, "message");
  12852. EXPECT_EQ(msg.data, "");
  12853. EXPECT_EQ(msg.id, "");
  12854. }
  12855. // Test: Complete event parsing
  12856. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12857. sse::SSEMessage msg;
  12858. int retry_ms = 3000;
  12859. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12860. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12861. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12862. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12863. // Blank line ends event
  12864. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12865. EXPECT_EQ(msg.event, "notification");
  12866. EXPECT_EQ(msg.id, "evt-42");
  12867. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12868. EXPECT_EQ(retry_ms, 1000);
  12869. }
  12870. //==============================================================================
  12871. // Integration Tests with Server
  12872. //==============================================================================
  12873. class SSEIntegrationTest : public ::testing::Test {
  12874. protected:
  12875. void SetUp() override {
  12876. stop_server_.store(false);
  12877. events_.clear();
  12878. server_ = httplib::detail::make_unique<Server>();
  12879. setup_server();
  12880. start_server();
  12881. }
  12882. void TearDown() override {
  12883. stop_server_.store(true);
  12884. event_cv_.notify_all();
  12885. server_->stop();
  12886. if (server_thread_.joinable()) { server_thread_.join(); }
  12887. }
  12888. void setup_server() {
  12889. // Simple SSE endpoint
  12890. server_->Get("/events", [this](const Request &req, Response &res) {
  12891. auto last_id = req.get_header_value("Last-Event-ID");
  12892. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12893. res.set_chunked_content_provider(
  12894. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12895. std::unique_lock<std::mutex> lock(event_mutex_);
  12896. if (event_cv_.wait_for(
  12897. lock, std::chrono::milliseconds(200), [this] {
  12898. return !events_.empty() || stop_server_.load();
  12899. })) {
  12900. if (stop_server_.load()) { return false; }
  12901. if (!events_.empty()) {
  12902. std::string event = events_.front();
  12903. events_.erase(events_.begin());
  12904. sink.write(event.data(), event.size());
  12905. return true;
  12906. }
  12907. }
  12908. return !stop_server_.load();
  12909. });
  12910. });
  12911. // Endpoint that returns error
  12912. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12913. res.status = 500;
  12914. res.set_content("Internal Server Error", "text/plain");
  12915. });
  12916. // Endpoint for custom event types
  12917. server_->Get("/custom-events", [](const Request &, Response &res) {
  12918. res.set_chunked_content_provider(
  12919. "text/event-stream", [](size_t offset, DataSink &sink) {
  12920. if (offset == 0) {
  12921. std::string event = "event: update\ndata: updated\n\n"
  12922. "event: delete\ndata: deleted\n\n";
  12923. sink.write(event.data(), event.size());
  12924. }
  12925. return false; // End stream after sending
  12926. });
  12927. });
  12928. }
  12929. void start_server() {
  12930. port_ = server_->bind_to_any_port(HOST);
  12931. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12932. // Wait for server to start
  12933. while (!server_->is_running()) {
  12934. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12935. }
  12936. }
  12937. int get_port() const { return port_; }
  12938. void send_event(const std::string &event) {
  12939. std::lock_guard<std::mutex> lock(event_mutex_);
  12940. events_.push_back(event);
  12941. event_cv_.notify_all();
  12942. }
  12943. std::unique_ptr<Server> server_;
  12944. std::thread server_thread_;
  12945. std::mutex event_mutex_;
  12946. std::condition_variable event_cv_;
  12947. std::vector<std::string> events_;
  12948. std::atomic<bool> stop_server_{false};
  12949. std::string last_received_event_id_;
  12950. int port_ = 0;
  12951. };
  12952. // Test: Successful connection and on_open callback
  12953. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12954. // Add a simple endpoint that sends one event and closes
  12955. server_->Get("/simple-event", [](const Request &, Response &res) {
  12956. res.set_chunked_content_provider(
  12957. "text/event-stream", [](size_t offset, DataSink &sink) {
  12958. if (offset == 0) {
  12959. std::string event = "data: hello\n\n";
  12960. sink.write(event.data(), event.size());
  12961. }
  12962. return false; // Close stream after sending
  12963. });
  12964. });
  12965. Client client("localhost", get_port());
  12966. sse::SSEClient sse(client, "/simple-event");
  12967. std::atomic<bool> open_called{false};
  12968. std::atomic<bool> message_received{false};
  12969. sse.on_open([&open_called]() { open_called.store(true); });
  12970. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12971. if (msg.data == "hello") { message_received.store(true); }
  12972. });
  12973. sse.set_reconnect_interval(100);
  12974. sse.set_max_reconnect_attempts(1);
  12975. // Start async
  12976. sse.start_async();
  12977. // Wait for message to be processed
  12978. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12979. sse.stop();
  12980. EXPECT_TRUE(open_called.load());
  12981. EXPECT_TRUE(message_received.load());
  12982. }
  12983. // Test: on_message callback
  12984. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12985. // Endpoint that sends multiple events then closes
  12986. server_->Get("/multi-event", [](const Request &, Response &res) {
  12987. res.set_chunked_content_provider(
  12988. "text/event-stream", [](size_t offset, DataSink &sink) {
  12989. if (offset == 0) {
  12990. std::string events = "data: message1\n\ndata: message2\n\n";
  12991. sink.write(events.data(), events.size());
  12992. }
  12993. return false;
  12994. });
  12995. });
  12996. Client client("localhost", get_port());
  12997. sse::SSEClient sse(client, "/multi-event");
  12998. std::vector<std::string> received_messages;
  12999. std::mutex messages_mutex;
  13000. sse.on_message([&](const sse::SSEMessage &msg) {
  13001. std::lock_guard<std::mutex> lock(messages_mutex);
  13002. received_messages.push_back(msg.data);
  13003. });
  13004. sse.set_reconnect_interval(100);
  13005. sse.set_max_reconnect_attempts(1);
  13006. sse.start_async();
  13007. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13008. sse.stop();
  13009. std::lock_guard<std::mutex> lock(messages_mutex);
  13010. EXPECT_GE(received_messages.size(), 2u);
  13011. if (received_messages.size() >= 2) {
  13012. EXPECT_EQ(received_messages[0], "message1");
  13013. EXPECT_EQ(received_messages[1], "message2");
  13014. }
  13015. }
  13016. // Test: on_event for specific types
  13017. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13018. Client client("localhost", get_port());
  13019. sse::SSEClient sse(client, "/custom-events");
  13020. std::atomic<bool> update_received{false};
  13021. std::atomic<bool> delete_received{false};
  13022. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13023. if (msg.data == "updated") { update_received.store(true); }
  13024. });
  13025. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13026. if (msg.data == "deleted") { delete_received.store(true); }
  13027. });
  13028. sse.set_max_reconnect_attempts(1);
  13029. sse.start_async();
  13030. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13031. sse.stop();
  13032. EXPECT_TRUE(update_received.load());
  13033. EXPECT_TRUE(delete_received.load());
  13034. }
  13035. // Test: on_error callback on connection failure
  13036. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13037. // Connect to a non-existent port
  13038. Client client("localhost", 59999);
  13039. sse::SSEClient sse(client, "/events");
  13040. std::atomic<bool> error_called{false};
  13041. Error received_error = Error::Success;
  13042. sse.on_error([&](Error err) {
  13043. error_called.store(true);
  13044. received_error = err;
  13045. });
  13046. sse.set_reconnect_interval(50);
  13047. sse.set_max_reconnect_attempts(1);
  13048. sse.start_async();
  13049. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13050. sse.stop();
  13051. EXPECT_TRUE(error_called.load());
  13052. EXPECT_NE(received_error, Error::Success);
  13053. }
  13054. // Test: Last-Event-ID header sent on reconnect
  13055. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13056. // Endpoint that sends event with ID
  13057. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13058. res.set_chunked_content_provider(
  13059. "text/event-stream", [](size_t offset, DataSink &sink) {
  13060. if (offset == 0) {
  13061. std::string event = "id: evt-123\ndata: test\n\n";
  13062. sink.write(event.data(), event.size());
  13063. }
  13064. return false;
  13065. });
  13066. });
  13067. Client client("localhost", get_port());
  13068. sse::SSEClient sse(client, "/event-with-id");
  13069. std::atomic<bool> id_received{false};
  13070. sse.on_message([&](const sse::SSEMessage &msg) {
  13071. if (!msg.id.empty()) { id_received.store(true); }
  13072. });
  13073. sse.set_reconnect_interval(100);
  13074. sse.set_max_reconnect_attempts(1);
  13075. sse.start_async();
  13076. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13077. sse.stop();
  13078. EXPECT_TRUE(id_received.load());
  13079. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13080. }
  13081. // Test: Manual stop
  13082. TEST_F(SSEIntegrationTest, ManualStop) {
  13083. // Endpoint that sends one event and stays open briefly
  13084. std::atomic<bool> handler_running{true};
  13085. server_->Get("/stay-open", [&handler_running](const Request &,
  13086. Response &res) {
  13087. res.set_chunked_content_provider(
  13088. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13089. if (offset == 0) {
  13090. std::string event = "data: connected\n\n";
  13091. sink.write(event.data(), event.size());
  13092. }
  13093. // Keep connection open while handler_running is true
  13094. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13095. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13096. }
  13097. return false;
  13098. });
  13099. });
  13100. Client client("localhost", get_port());
  13101. sse::SSEClient sse(client, "/stay-open");
  13102. std::atomic<bool> connected{false};
  13103. sse.on_open([&connected]() { connected.store(true); });
  13104. sse.set_reconnect_interval(100);
  13105. sse.set_max_reconnect_attempts(1);
  13106. sse.start_async();
  13107. // Wait for connection to establish
  13108. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13109. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13110. }
  13111. EXPECT_TRUE(connected.load());
  13112. EXPECT_TRUE(sse.is_connected());
  13113. // Signal handler to stop
  13114. handler_running.store(false);
  13115. // Stop SSE client
  13116. sse.stop();
  13117. EXPECT_FALSE(sse.is_connected());
  13118. }
  13119. // Test: SSEClient with custom headers
  13120. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13121. // Setup a server endpoint that checks for custom header
  13122. std::atomic<bool> header_received{false};
  13123. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13124. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13125. header_received.store(true);
  13126. }
  13127. res.set_chunked_content_provider("text/event-stream",
  13128. [](size_t, DataSink &) { return false; });
  13129. });
  13130. Client client("localhost", get_port());
  13131. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13132. sse::SSEClient sse(client, "/header-check", headers);
  13133. sse.set_max_reconnect_attempts(1);
  13134. sse.start_async();
  13135. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13136. sse.stop();
  13137. EXPECT_TRUE(header_received.load());
  13138. }
  13139. // Test: Reconnect interval configuration
  13140. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13141. Client client("localhost", get_port());
  13142. sse::SSEClient sse(client, "/events");
  13143. auto &result = sse.set_reconnect_interval(500);
  13144. // Builder pattern should return reference to self
  13145. EXPECT_EQ(&result, &sse);
  13146. }
  13147. // Test: Max reconnect attempts
  13148. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13149. // Connect to non-existent port to force reconnects
  13150. Client client("localhost", 59998);
  13151. sse::SSEClient sse(client, "/events");
  13152. std::atomic<int> error_count{0};
  13153. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13154. sse.set_reconnect_interval(50);
  13155. sse.set_max_reconnect_attempts(2);
  13156. auto start = std::chrono::steady_clock::now();
  13157. sse.start(); // Blocking call
  13158. auto end = std::chrono::steady_clock::now();
  13159. // Should have stopped after 2 failed attempts
  13160. EXPECT_GE(error_count.load(), 2);
  13161. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13162. auto duration =
  13163. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13164. #ifdef _WIN32
  13165. // Windows is much slower for socket connection failures
  13166. EXPECT_LT(duration.count(), 7000);
  13167. #else
  13168. EXPECT_LT(duration.count(), 1000);
  13169. #endif
  13170. }
  13171. // Test: Multi-line data in integration
  13172. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13173. // Endpoint with multi-line data
  13174. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13175. res.set_chunked_content_provider(
  13176. "text/event-stream", [](size_t offset, DataSink &sink) {
  13177. if (offset == 0) {
  13178. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13179. sink.write(event.data(), event.size());
  13180. }
  13181. return false;
  13182. });
  13183. });
  13184. Client client("localhost", get_port());
  13185. sse::SSEClient sse(client, "/multiline-data");
  13186. std::string received_data;
  13187. std::mutex data_mutex;
  13188. sse.on_message([&](const sse::SSEMessage &msg) {
  13189. std::lock_guard<std::mutex> lock(data_mutex);
  13190. received_data = msg.data;
  13191. });
  13192. sse.set_reconnect_interval(100);
  13193. sse.set_max_reconnect_attempts(1);
  13194. sse.start_async();
  13195. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13196. sse.stop();
  13197. std::lock_guard<std::mutex> lock(data_mutex);
  13198. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13199. }
  13200. // Test: Auto-reconnect after server disconnection
  13201. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13202. std::atomic<int> connection_count{0};
  13203. std::atomic<int> message_count{0};
  13204. // Endpoint that sends one event and closes, forcing reconnect
  13205. server_->Get("/reconnect-test",
  13206. [&connection_count](const Request &, Response &res) {
  13207. connection_count.fetch_add(1);
  13208. res.set_chunked_content_provider(
  13209. "text/event-stream", [](size_t offset, DataSink &sink) {
  13210. if (offset == 0) {
  13211. std::string event = "data: hello\n\n";
  13212. sink.write(event.data(), event.size());
  13213. }
  13214. return false; // Close connection after sending
  13215. });
  13216. });
  13217. Client client("localhost", get_port());
  13218. sse::SSEClient sse(client, "/reconnect-test");
  13219. sse.on_message([&message_count](const sse::SSEMessage &) {
  13220. message_count.fetch_add(1);
  13221. });
  13222. sse.set_reconnect_interval(100);
  13223. sse.set_max_reconnect_attempts(3);
  13224. sse.start_async();
  13225. // Wait long enough for multiple reconnects
  13226. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13227. sse.stop();
  13228. // Should have connected multiple times (initial + reconnects)
  13229. EXPECT_GE(connection_count.load(), 2);
  13230. // Should have received messages from multiple connections
  13231. EXPECT_GE(message_count.load(), 2);
  13232. }
  13233. // Test: Last-Event-ID sent on reconnect
  13234. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13235. std::atomic<int> connection_count{0};
  13236. std::vector<std::string> received_last_event_ids;
  13237. std::mutex id_mutex;
  13238. // Endpoint that checks Last-Event-ID header and sends event with ID
  13239. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13240. int conn = connection_count.fetch_add(1);
  13241. // Capture the Last-Event-ID header from each connection
  13242. {
  13243. std::lock_guard<std::mutex> lock(id_mutex);
  13244. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13245. }
  13246. res.set_chunked_content_provider(
  13247. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13248. if (offset == 0) {
  13249. std::string event =
  13250. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13251. sink.write(event.data(), event.size());
  13252. }
  13253. return false;
  13254. });
  13255. });
  13256. Client client("localhost", get_port());
  13257. sse::SSEClient sse(client, "/reconnect-with-id");
  13258. sse.set_reconnect_interval(100);
  13259. sse.set_max_reconnect_attempts(3);
  13260. sse.start_async();
  13261. // Wait for at least 2 connections
  13262. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13263. sse.stop();
  13264. // Verify behavior
  13265. std::lock_guard<std::mutex> lock(id_mutex);
  13266. EXPECT_GE(received_last_event_ids.size(), 2u);
  13267. // First connection should have no Last-Event-ID
  13268. if (!received_last_event_ids.empty()) {
  13269. EXPECT_EQ(received_last_event_ids[0], "");
  13270. }
  13271. // Second connection should have Last-Event-ID from first connection
  13272. if (received_last_event_ids.size() >= 2) {
  13273. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13274. }
  13275. }
  13276. TEST(Issue2318Test, EmptyHostString) {
  13277. {
  13278. httplib::Client cli_empty("", PORT);
  13279. auto res = cli_empty.Get("/");
  13280. ASSERT_FALSE(res);
  13281. EXPECT_EQ(httplib::Error::Connection, res.error());
  13282. }
  13283. {
  13284. httplib::Client cli(" ", PORT);
  13285. auto res = cli.Get("/");
  13286. ASSERT_FALSE(res);
  13287. EXPECT_EQ(httplib::Error::Connection, res.error());
  13288. }
  13289. }
  13290. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13291. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13292. Server svr;
  13293. // Set a small payload limit (1KB)
  13294. svr.set_payload_max_length(1024);
  13295. svr.Post("/test", [&](const Request &req, Response &res) {
  13296. res.set_content("Body size: " + std::to_string(req.body.size()),
  13297. "text/plain");
  13298. });
  13299. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13300. auto se = detail::scope_exit([&] {
  13301. svr.stop();
  13302. listen_thread.join();
  13303. });
  13304. svr.wait_until_ready();
  13305. // Create data that compresses well but exceeds limit when decompressed
  13306. // 8KB of repeated null bytes compresses to a very small size
  13307. std::string original_data(8 * 1024, '\0');
  13308. // Compress the data using gzip
  13309. std::string compressed_data;
  13310. detail::gzip_compressor compressor;
  13311. compressor.compress(original_data.data(), original_data.size(), true,
  13312. [&](const char *data, size_t size) {
  13313. compressed_data.append(data, size);
  13314. return true;
  13315. });
  13316. // Verify compression worked (compressed should be much smaller)
  13317. ASSERT_LT(compressed_data.size(), original_data.size());
  13318. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13319. // Send compressed data with Content-Encoding: gzip
  13320. Client cli(HOST, PORT);
  13321. Headers headers = {{"Content-Encoding", "gzip"}};
  13322. auto res =
  13323. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13324. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13325. ASSERT_TRUE(res);
  13326. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13327. }
  13328. #endif
  13329. // ============================================================================
  13330. // OpenSSL-Specific Tests
  13331. // ============================================================================
  13332. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13333. X509 *readCertificate(const std::string &strFileName) {
  13334. std::ifstream inStream(strFileName);
  13335. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13336. std::istreambuf_iterator<char>());
  13337. if (strCertPEM.empty()) return (nullptr);
  13338. BIO *pbCert = BIO_new(BIO_s_mem());
  13339. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13340. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13341. BIO_free(pbCert);
  13342. return (pCert);
  13343. }
  13344. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13345. std::ifstream inStream(strFileName);
  13346. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13347. std::istreambuf_iterator<char>());
  13348. if (strPrivateKeyPEM.empty()) return (nullptr);
  13349. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13350. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13351. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13352. BIO_free(pbPrivKey);
  13353. return (pPrivateKey);
  13354. }
  13355. TEST(BindServerTest, UpdateCerts) {
  13356. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13357. int port = svr.bind_to_any_port("0.0.0.0");
  13358. ASSERT_TRUE(svr.is_valid());
  13359. ASSERT_TRUE(port > 0);
  13360. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13361. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13362. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13363. ASSERT_TRUE(cert != nullptr);
  13364. ASSERT_TRUE(ca_cert != nullptr);
  13365. ASSERT_TRUE(key != nullptr);
  13366. X509_STORE *cert_store = X509_STORE_new();
  13367. X509_STORE_add_cert(cert_store, ca_cert);
  13368. // svr.update_certs(cert, key, cert_store); // deprecated
  13369. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13370. CLIENT_CA_CERT_FILE);
  13371. ASSERT_TRUE(svr.is_valid());
  13372. svr.stop();
  13373. X509_STORE_free(cert_store);
  13374. X509_free(cert);
  13375. X509_free(ca_cert);
  13376. EVP_PKEY_free(key);
  13377. }
  13378. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13379. // client CA list correctly for TLS handshake
  13380. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13381. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13382. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13383. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13384. ASSERT_TRUE(cert != nullptr);
  13385. ASSERT_TRUE(ca_cert != nullptr);
  13386. ASSERT_TRUE(key != nullptr);
  13387. X509_STORE *cert_store = X509_STORE_new();
  13388. X509_STORE_add_cert(cert_store, ca_cert);
  13389. // Use X509-based constructor (deprecated but should still work correctly)
  13390. #pragma GCC diagnostic push
  13391. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13392. SSLServer svr(cert, key, cert_store);
  13393. #pragma GCC diagnostic pop
  13394. ASSERT_TRUE(svr.is_valid());
  13395. // Verify that client CA list is set in SSL_CTX
  13396. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13397. ASSERT_TRUE(ssl_ctx != nullptr);
  13398. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13399. ASSERT_TRUE(ca_list != nullptr);
  13400. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13401. X509_free(cert);
  13402. X509_free(ca_cert);
  13403. EVP_PKEY_free(key);
  13404. }
  13405. // Test that update_certs() updates client CA list correctly
  13406. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13407. // Start with file-based constructor
  13408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13409. ASSERT_TRUE(svr.is_valid());
  13410. // Initially no client CA list should be set
  13411. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13412. ASSERT_TRUE(ssl_ctx != nullptr);
  13413. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13414. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13415. EXPECT_EQ(0, count_before);
  13416. // Now update with client CA (PEM string)
  13417. std::string cert_pem, key_pem, ca_pem;
  13418. read_file(SERVER_CERT_FILE, cert_pem);
  13419. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13420. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13421. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13422. ASSERT_TRUE(svr.is_valid());
  13423. // Now client CA list should be set
  13424. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13425. ASSERT_TRUE(ca_list_after != nullptr);
  13426. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13427. }
  13428. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13429. // Test that the file-path SSLServer constructor properly sets the client CA
  13430. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13432. ASSERT_TRUE(svr.is_valid());
  13433. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13434. ASSERT_TRUE(ssl_ctx != nullptr);
  13435. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13436. ASSERT_TRUE(ca_list != nullptr);
  13437. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13438. }
  13439. #endif
  13440. // ============================================================================
  13441. // MbedTLS-Specific Tests
  13442. // ============================================================================
  13443. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13444. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13445. using namespace httplib::tls;
  13446. // Track if callback was invoked
  13447. bool callback_invoked = false;
  13448. // The callback receives void* ctx which is actually MbedTlsContext*
  13449. // We can access the mbedtls_ssl_config via the context
  13450. auto setup_callback = [&callback_invoked](void *ctx) {
  13451. callback_invoked = true;
  13452. // Cast to MbedTlsContext* to access the ssl config
  13453. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13454. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13455. // Use static variables to hold certificate data (simplified for test)
  13456. static mbedtls_x509_crt own_cert;
  13457. static mbedtls_pk_context own_key;
  13458. static mbedtls_x509_crt ca_chain;
  13459. static bool initialized = false;
  13460. if (!initialized) {
  13461. mbedtls_x509_crt_init(&own_cert);
  13462. mbedtls_pk_init(&own_key);
  13463. mbedtls_x509_crt_init(&ca_chain);
  13464. // Load server certificate
  13465. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13466. return false;
  13467. }
  13468. // Load server private key
  13469. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13470. #if MBEDTLS_VERSION_MAJOR >= 3
  13471. ,
  13472. mbedtls_ctr_drbg_random, nullptr
  13473. #endif
  13474. ) != 0) {
  13475. return false;
  13476. }
  13477. // Load CA chain for client verification
  13478. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13479. return false;
  13480. }
  13481. initialized = true;
  13482. }
  13483. // Configure the SSL config
  13484. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13485. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13486. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13487. // Set minimum TLS version using mbedTLS native API
  13488. #if MBEDTLS_VERSION_MAJOR >= 3
  13489. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13490. #else
  13491. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13492. MBEDTLS_SSL_MINOR_VERSION_3);
  13493. #endif
  13494. return true;
  13495. };
  13496. SSLServer svr(setup_callback);
  13497. ASSERT_TRUE(svr.is_valid());
  13498. ASSERT_TRUE(callback_invoked);
  13499. svr.Get("/test", [&](const Request &req, Response &res) {
  13500. res.set_content("test", "text/plain");
  13501. auto cert = req.peer_cert();
  13502. ASSERT_TRUE(static_cast<bool>(cert));
  13503. auto common_name = cert.subject_cn();
  13504. EXPECT_EQ("Common Name", common_name);
  13505. });
  13506. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13507. auto se = detail::scope_exit([&] {
  13508. svr.stop();
  13509. t.join();
  13510. ASSERT_FALSE(svr.is_running());
  13511. });
  13512. svr.wait_until_ready();
  13513. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13514. cli.enable_server_certificate_verification(false);
  13515. cli.set_connection_timeout(30);
  13516. auto res = cli.Get("/test");
  13517. ASSERT_TRUE(res);
  13518. ASSERT_EQ(StatusCode::OK_200, res->status);
  13519. }
  13520. #endif
  13521. // WebSocket Tests
  13522. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13523. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13524. // defining the meaning of these bits has been negotiated.
  13525. auto make_frame = [](uint8_t first_byte) {
  13526. std::string frame;
  13527. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13528. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13529. frame += "Hello";
  13530. return frame;
  13531. };
  13532. // RSV1 set (0x40)
  13533. {
  13534. detail::BufferStream strm;
  13535. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13536. ws::Opcode opcode;
  13537. std::string payload;
  13538. bool fin;
  13539. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13540. false, 1024));
  13541. }
  13542. // RSV2 set (0x20)
  13543. {
  13544. detail::BufferStream strm;
  13545. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13546. ws::Opcode opcode;
  13547. std::string payload;
  13548. bool fin;
  13549. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13550. false, 1024));
  13551. }
  13552. // RSV3 set (0x10)
  13553. {
  13554. detail::BufferStream strm;
  13555. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13556. ws::Opcode opcode;
  13557. std::string payload;
  13558. bool fin;
  13559. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13560. false, 1024));
  13561. }
  13562. // No RSV bits set - should succeed
  13563. {
  13564. detail::BufferStream strm;
  13565. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13566. ws::Opcode opcode;
  13567. std::string payload;
  13568. bool fin;
  13569. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13570. false, 1024));
  13571. EXPECT_EQ(ws::Opcode::Text, opcode);
  13572. EXPECT_EQ("Hello", payload);
  13573. EXPECT_TRUE(fin);
  13574. }
  13575. }
  13576. TEST(WebSocketTest, ControlFrameValidation) {
  13577. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13578. // payload length <= 125.
  13579. // Ping with FIN=0 - must be rejected
  13580. {
  13581. detail::BufferStream strm;
  13582. std::string frame;
  13583. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13584. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13585. strm.write(frame.data(), frame.size());
  13586. ws::Opcode opcode;
  13587. std::string payload;
  13588. bool fin;
  13589. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13590. false, 1024));
  13591. }
  13592. // Close with FIN=0 - must be rejected
  13593. {
  13594. detail::BufferStream strm;
  13595. std::string frame;
  13596. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  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. // Ping with payload_len=126 (extended length) - must be rejected
  13606. {
  13607. detail::BufferStream strm;
  13608. std::string frame;
  13609. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13610. frame += static_cast<char>(126); // payload_len=126 (>125)
  13611. frame += static_cast<char>(0x00); // extended length high byte
  13612. frame += static_cast<char>(126); // extended length low byte
  13613. frame += std::string(126, 'x');
  13614. strm.write(frame.data(), frame.size());
  13615. ws::Opcode opcode;
  13616. std::string payload;
  13617. bool fin;
  13618. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13619. false, 1024));
  13620. }
  13621. // Ping with FIN=1 and payload_len=125 - should succeed
  13622. {
  13623. detail::BufferStream strm;
  13624. std::string frame;
  13625. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13626. frame += static_cast<char>(125); // payload_len=125
  13627. frame += std::string(125, 'x');
  13628. strm.write(frame.data(), frame.size());
  13629. ws::Opcode opcode;
  13630. std::string payload;
  13631. bool fin;
  13632. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13633. false, 1024));
  13634. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13635. EXPECT_EQ(125u, payload.size());
  13636. EXPECT_TRUE(fin);
  13637. }
  13638. }
  13639. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13640. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13641. // length MUST be 0.
  13642. // MSB set - must be rejected
  13643. {
  13644. detail::BufferStream strm;
  13645. std::string frame;
  13646. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13647. frame += static_cast<char>(127); // 64-bit extended length
  13648. frame += static_cast<char>(0x80); // MSB set (invalid)
  13649. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13650. strm.write(frame.data(), frame.size());
  13651. ws::Opcode opcode;
  13652. std::string payload;
  13653. bool fin;
  13654. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13655. false, 1024));
  13656. }
  13657. // MSB clear - should pass length parsing (will be rejected by max_len,
  13658. // but that's a different check; use a small length to verify)
  13659. {
  13660. detail::BufferStream strm;
  13661. std::string frame;
  13662. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13663. frame += static_cast<char>(127); // 64-bit extended length
  13664. frame += std::string(7, '\0'); // high bytes = 0
  13665. frame += static_cast<char>(0x03); // length = 3
  13666. frame += "abc";
  13667. strm.write(frame.data(), frame.size());
  13668. ws::Opcode opcode;
  13669. std::string payload;
  13670. bool fin;
  13671. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13672. false, 1024));
  13673. EXPECT_EQ(ws::Opcode::Text, opcode);
  13674. EXPECT_EQ("abc", payload);
  13675. }
  13676. }
  13677. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13678. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13679. // Valid UTF-8
  13680. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13681. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13682. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13683. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13684. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13685. // Invalid UTF-8
  13686. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13687. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13688. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13689. EXPECT_FALSE(
  13690. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13691. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13692. }
  13693. TEST(WebSocketTest, ConnectAndDisconnect) {
  13694. Server svr;
  13695. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13696. std::string msg;
  13697. while (ws.read(msg)) {}
  13698. });
  13699. auto port = svr.bind_to_any_port(HOST);
  13700. std::thread t([&]() { svr.listen_after_bind(); });
  13701. svr.wait_until_ready();
  13702. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13703. ASSERT_TRUE(client.connect());
  13704. EXPECT_TRUE(client.is_open());
  13705. client.close();
  13706. EXPECT_FALSE(client.is_open());
  13707. svr.stop();
  13708. t.join();
  13709. }
  13710. TEST(WebSocketTest, ValidURL) {
  13711. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13712. EXPECT_TRUE(ws1.is_valid());
  13713. ws::WebSocketClient ws2("ws://example.com/path");
  13714. EXPECT_TRUE(ws2.is_valid());
  13715. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13716. EXPECT_TRUE(ws3.is_valid());
  13717. #ifdef CPPHTTPLIB_SSL_ENABLED
  13718. ws::WebSocketClient wss1("wss://example.com/path");
  13719. EXPECT_TRUE(wss1.is_valid());
  13720. ws::WebSocketClient wss2("wss://example.com:443/path");
  13721. EXPECT_TRUE(wss2.is_valid());
  13722. #endif
  13723. }
  13724. TEST(WebSocketTest, InvalidURL) {
  13725. // No scheme
  13726. ws::WebSocketClient ws1("localhost:8080/path");
  13727. EXPECT_FALSE(ws1.is_valid());
  13728. // No path
  13729. ws::WebSocketClient ws2("ws://localhost:8080");
  13730. EXPECT_FALSE(ws2.is_valid());
  13731. // Empty string
  13732. ws::WebSocketClient ws3("");
  13733. EXPECT_FALSE(ws3.is_valid());
  13734. // Missing host
  13735. ws::WebSocketClient ws4("ws://:8080/path");
  13736. EXPECT_FALSE(ws4.is_valid());
  13737. // Port number overflow — should not crash
  13738. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13739. EXPECT_FALSE(ws5.is_valid());
  13740. // Port out of range
  13741. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13742. EXPECT_FALSE(ws6.is_valid());
  13743. }
  13744. TEST(WebSocketTest, UnsupportedScheme) {
  13745. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13746. ws::WebSocketClient ws1("http://localhost:8080/path");
  13747. EXPECT_FALSE(ws1.is_valid());
  13748. ws::WebSocketClient ws2("https://localhost:8080/path");
  13749. EXPECT_FALSE(ws2.is_valid());
  13750. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13751. EXPECT_FALSE(ws3.is_valid());
  13752. #else
  13753. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13754. std::invalid_argument);
  13755. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13756. std::invalid_argument);
  13757. #endif
  13758. }
  13759. TEST(WebSocketTest, ConnectWhenInvalid) {
  13760. ws::WebSocketClient ws("not a valid url");
  13761. EXPECT_FALSE(ws.is_valid());
  13762. EXPECT_FALSE(ws.connect());
  13763. }
  13764. TEST(WebSocketTest, DefaultPort) {
  13765. ws::WebSocketClient ws1("ws://example.com/path");
  13766. EXPECT_TRUE(ws1.is_valid());
  13767. // ws:// defaults to port 80 (verified by successful parse)
  13768. #ifdef CPPHTTPLIB_SSL_ENABLED
  13769. ws::WebSocketClient ws2("wss://example.com/path");
  13770. EXPECT_TRUE(ws2.is_valid());
  13771. // wss:// defaults to port 443 (verified by successful parse)
  13772. #endif
  13773. }
  13774. TEST(WebSocketTest, IPv6LiteralAddress) {
  13775. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13776. EXPECT_TRUE(ws1.is_valid());
  13777. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13778. EXPECT_TRUE(ws2.is_valid());
  13779. }
  13780. TEST(WebSocketTest, ComplexPath) {
  13781. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13782. EXPECT_TRUE(ws1.is_valid());
  13783. ws::WebSocketClient ws2("ws://localhost:8080/");
  13784. EXPECT_TRUE(ws2.is_valid());
  13785. }
  13786. class WebSocketIntegrationTest : public ::testing::Test {
  13787. protected:
  13788. void SetUp() override {
  13789. server_ = httplib::detail::make_unique<Server>();
  13790. setup_server();
  13791. start_server();
  13792. }
  13793. void TearDown() override {
  13794. server_->stop();
  13795. if (server_thread_.joinable()) { server_thread_.join(); }
  13796. }
  13797. void setup_server() {
  13798. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13799. std::string msg;
  13800. ws::ReadResult ret;
  13801. while ((ret = ws.read(msg))) {
  13802. if (ret == ws::Binary) {
  13803. ws.send(msg.data(), msg.size());
  13804. } else {
  13805. ws.send(msg);
  13806. }
  13807. }
  13808. });
  13809. server_->WebSocket("/ws-echo-string",
  13810. [](const Request &, ws::WebSocket &ws) {
  13811. std::string msg;
  13812. while (ws.read(msg)) {
  13813. ws.send("echo: " + msg);
  13814. }
  13815. });
  13816. server_->WebSocket(
  13817. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13818. // Echo back request metadata
  13819. ws.send("path:" + req.path);
  13820. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13821. std::string msg;
  13822. while (ws.read(msg)) {}
  13823. });
  13824. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13825. std::string msg;
  13826. ws.read(msg); // wait for a message
  13827. ws.close();
  13828. });
  13829. server_->WebSocket("/ws-close-status",
  13830. [](const Request &, ws::WebSocket &ws) {
  13831. std::string msg;
  13832. ws.read(msg); // wait for a message
  13833. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13834. });
  13835. server_->WebSocket(
  13836. "/ws-subprotocol",
  13837. [](const Request &, ws::WebSocket &ws) {
  13838. std::string msg;
  13839. while (ws.read(msg)) {
  13840. ws.send(msg);
  13841. }
  13842. },
  13843. [](const std::vector<std::string> &protocols) -> std::string {
  13844. for (const auto &p : protocols) {
  13845. if (p == "graphql-ws") { return p; }
  13846. }
  13847. return "";
  13848. });
  13849. }
  13850. void start_server() {
  13851. port_ = server_->bind_to_any_port(HOST);
  13852. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13853. server_->wait_until_ready();
  13854. }
  13855. std::unique_ptr<Server> server_;
  13856. std::thread server_thread_;
  13857. int port_ = 0;
  13858. };
  13859. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13860. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13861. "/ws-echo");
  13862. ASSERT_TRUE(client.connect());
  13863. ASSERT_TRUE(client.is_open());
  13864. ASSERT_TRUE(client.send("Hello WebSocket"));
  13865. std::string msg;
  13866. EXPECT_EQ(ws::Text, client.read(msg));
  13867. EXPECT_EQ("Hello WebSocket", msg);
  13868. client.close();
  13869. }
  13870. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13871. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13872. "/ws-echo");
  13873. ASSERT_TRUE(client.connect());
  13874. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13875. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13876. std::string msg;
  13877. EXPECT_EQ(ws::Binary, client.read(msg));
  13878. EXPECT_EQ(binary_data, msg);
  13879. client.close();
  13880. }
  13881. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13882. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13883. "/ws-echo");
  13884. ASSERT_TRUE(client.connect());
  13885. for (int i = 0; i < 10; i++) {
  13886. auto text = "message " + std::to_string(i);
  13887. ASSERT_TRUE(client.send(text));
  13888. std::string msg;
  13889. ASSERT_TRUE(client.read(msg));
  13890. EXPECT_EQ(text, msg);
  13891. }
  13892. client.close();
  13893. }
  13894. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13895. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13896. "/ws-close");
  13897. ASSERT_TRUE(client.connect());
  13898. // Send a message to trigger the server to close
  13899. ASSERT_TRUE(client.send("trigger close"));
  13900. // The server will close, so read should return false
  13901. std::string msg;
  13902. EXPECT_FALSE(client.read(msg));
  13903. EXPECT_FALSE(client.is_open());
  13904. }
  13905. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13906. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13907. "/ws-echo");
  13908. ASSERT_TRUE(client.connect());
  13909. // 128KB message
  13910. std::string large_data(128 * 1024, 'X');
  13911. ASSERT_TRUE(client.send(large_data));
  13912. std::string msg;
  13913. ASSERT_TRUE(client.read(msg));
  13914. EXPECT_EQ(large_data, msg);
  13915. client.close();
  13916. }
  13917. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13918. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13919. "/ws-echo");
  13920. ASSERT_TRUE(client.connect());
  13921. const int num_threads = 4;
  13922. std::vector<std::thread> threads;
  13923. std::atomic<int> send_count{0};
  13924. for (int t = 0; t < num_threads; t++) {
  13925. threads.emplace_back([&client, &send_count, t]() {
  13926. for (int i = 0; i < 5; i++) {
  13927. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13928. if (client.send(text)) { send_count++; }
  13929. }
  13930. });
  13931. }
  13932. for (auto &th : threads) {
  13933. th.join();
  13934. }
  13935. int received = 0;
  13936. std::string msg;
  13937. while (received < send_count.load()) {
  13938. if (!client.read(msg)) { break; }
  13939. received++;
  13940. }
  13941. EXPECT_EQ(send_count.load(), received);
  13942. client.close();
  13943. }
  13944. TEST_F(WebSocketIntegrationTest, ReadString) {
  13945. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13946. "/ws-echo-string");
  13947. ASSERT_TRUE(client.connect());
  13948. ASSERT_TRUE(client.send("hello"));
  13949. std::string msg;
  13950. ASSERT_TRUE(client.read(msg));
  13951. EXPECT_EQ("echo: hello", msg);
  13952. ASSERT_TRUE(client.send("world"));
  13953. ASSERT_TRUE(client.read(msg));
  13954. EXPECT_EQ("echo: world", msg);
  13955. client.close();
  13956. }
  13957. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  13958. Headers headers = {{"X-Test-Header", "test-value"}};
  13959. ws::WebSocketClient client(
  13960. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  13961. ASSERT_TRUE(client.connect());
  13962. std::string msg;
  13963. ASSERT_TRUE(client.read(msg));
  13964. EXPECT_EQ("path:/ws-request-info", msg);
  13965. ASSERT_TRUE(client.read(msg));
  13966. EXPECT_EQ("header:test-value", msg);
  13967. client.close();
  13968. }
  13969. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  13970. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13971. "/ws-echo");
  13972. client.set_read_timeout(1, 0); // 1 second
  13973. ASSERT_TRUE(client.connect());
  13974. // Don't send anything — server echo handler waits for a message,
  13975. // so read() should time out and return false.
  13976. std::string msg;
  13977. EXPECT_FALSE(client.read(msg));
  13978. }
  13979. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  13980. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13981. "/ws-echo");
  13982. client.set_read_timeout(5, 0);
  13983. ASSERT_TRUE(client.connect());
  13984. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13985. // The server should reject it and close the connection.
  13986. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  13987. client.send(oversized);
  13988. // The server's read() should have failed due to payload limit,
  13989. // so our read() should return false (connection closed).
  13990. std::string msg;
  13991. EXPECT_FALSE(client.read(msg));
  13992. }
  13993. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  13994. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13995. "/ws-echo");
  13996. client.set_read_timeout(10, 0);
  13997. ASSERT_TRUE(client.connect());
  13998. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13999. // This should succeed.
  14000. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14001. ASSERT_TRUE(client.send(at_limit));
  14002. std::string msg;
  14003. ASSERT_TRUE(client.read(msg));
  14004. EXPECT_EQ(at_limit.size(), msg.size());
  14005. client.close();
  14006. }
  14007. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14008. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14009. "/nonexistent");
  14010. EXPECT_FALSE(client.connect());
  14011. EXPECT_FALSE(client.is_open());
  14012. }
  14013. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14014. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14015. "/ws-echo");
  14016. ASSERT_TRUE(client.connect());
  14017. ASSERT_TRUE(client.send(""));
  14018. std::string msg;
  14019. EXPECT_EQ(ws::Text, client.read(msg));
  14020. EXPECT_EQ("", msg);
  14021. client.close();
  14022. }
  14023. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14024. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14025. "/ws-echo");
  14026. // First connection
  14027. ASSERT_TRUE(client.connect());
  14028. ASSERT_TRUE(client.send("first"));
  14029. std::string msg;
  14030. ASSERT_TRUE(client.read(msg));
  14031. EXPECT_EQ("first", msg);
  14032. client.close();
  14033. EXPECT_FALSE(client.is_open());
  14034. // Reconnect using the same client object
  14035. ASSERT_TRUE(client.connect());
  14036. ASSERT_TRUE(client.is_open());
  14037. ASSERT_TRUE(client.send("second"));
  14038. ASSERT_TRUE(client.read(msg));
  14039. EXPECT_EQ("second", msg);
  14040. client.close();
  14041. }
  14042. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14043. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14044. "/ws-close-status");
  14045. ASSERT_TRUE(client.connect());
  14046. // Trigger the server to close with GoingAway status
  14047. ASSERT_TRUE(client.send("trigger"));
  14048. // read() should return false after receiving the close frame
  14049. std::string msg;
  14050. EXPECT_FALSE(client.read(msg));
  14051. EXPECT_FALSE(client.is_open());
  14052. }
  14053. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14054. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14055. "/ws-echo");
  14056. ASSERT_TRUE(client.connect());
  14057. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14058. EXPECT_FALSE(client.is_open());
  14059. }
  14060. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14061. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14062. ws::WebSocketClient client(
  14063. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14064. ASSERT_TRUE(client.connect());
  14065. // Server should have selected graphql-ws
  14066. EXPECT_EQ("graphql-ws", client.subprotocol());
  14067. client.close();
  14068. }
  14069. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14070. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14071. ws::WebSocketClient client(
  14072. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14073. ASSERT_TRUE(client.connect());
  14074. // Server should not have selected any subprotocol
  14075. EXPECT_TRUE(client.subprotocol().empty());
  14076. client.close();
  14077. }
  14078. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14079. // Connect without requesting any subprotocol
  14080. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14081. "/ws-subprotocol");
  14082. ASSERT_TRUE(client.connect());
  14083. EXPECT_TRUE(client.subprotocol().empty());
  14084. client.close();
  14085. }
  14086. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14087. Server svr;
  14088. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14089. if (!req.has_header("Authorization")) {
  14090. res.status = StatusCode::Unauthorized_401;
  14091. res.set_content("Unauthorized", "text/plain");
  14092. return Server::HandlerResponse::Handled;
  14093. }
  14094. return Server::HandlerResponse::Unhandled;
  14095. });
  14096. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14097. std::string msg;
  14098. while (ws.read(msg)) {
  14099. ws.send(msg);
  14100. }
  14101. });
  14102. auto port = svr.bind_to_any_port("localhost");
  14103. std::thread t([&]() { svr.listen_after_bind(); });
  14104. svr.wait_until_ready();
  14105. // Without Authorization header - should be rejected before upgrade
  14106. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14107. EXPECT_FALSE(client1.connect());
  14108. // With Authorization header - should succeed
  14109. Headers headers = {{"Authorization", "Bearer token123"}};
  14110. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14111. headers);
  14112. ASSERT_TRUE(client2.connect());
  14113. ASSERT_TRUE(client2.send("hello"));
  14114. std::string msg;
  14115. ASSERT_TRUE(client2.read(msg));
  14116. EXPECT_EQ("hello", msg);
  14117. client2.close();
  14118. svr.stop();
  14119. t.join();
  14120. }
  14121. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14122. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14123. protected:
  14124. void SetUp() override {
  14125. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14126. SERVER_PRIVATE_KEY_FILE);
  14127. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14128. std::string msg;
  14129. ws::ReadResult ret;
  14130. while ((ret = ws.read(msg))) {
  14131. if (ret == ws::Binary) {
  14132. ws.send(msg.data(), msg.size());
  14133. } else {
  14134. ws.send(msg);
  14135. }
  14136. }
  14137. });
  14138. port_ = server_->bind_to_any_port(HOST);
  14139. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14140. server_->wait_until_ready();
  14141. }
  14142. void TearDown() override {
  14143. server_->stop();
  14144. if (server_thread_.joinable()) { server_thread_.join(); }
  14145. }
  14146. std::unique_ptr<SSLServer> server_;
  14147. std::thread server_thread_;
  14148. int port_ = 0;
  14149. };
  14150. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14151. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14152. "/ws-echo");
  14153. client.enable_server_certificate_verification(false);
  14154. ASSERT_TRUE(client.connect());
  14155. ASSERT_TRUE(client.is_open());
  14156. ASSERT_TRUE(client.send("Hello WSS"));
  14157. std::string msg;
  14158. EXPECT_EQ(ws::Text, client.read(msg));
  14159. EXPECT_EQ("Hello WSS", msg);
  14160. client.close();
  14161. }
  14162. #endif
  14163. #if !defined(_WIN32)
  14164. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14165. auto secret_dir = std::string("./symlink_test_secret");
  14166. auto served_dir = std::string("./symlink_test_served");
  14167. auto secret_file = secret_dir + "/secret.txt";
  14168. auto symlink_path = served_dir + "/escape";
  14169. // Setup: create directories and files
  14170. mkdir(secret_dir.c_str(), 0755);
  14171. mkdir(served_dir.c_str(), 0755);
  14172. {
  14173. std::ofstream ofs(secret_file);
  14174. ofs << "SECRET_DATA";
  14175. }
  14176. // Create symlink using absolute path so it resolves correctly
  14177. char abs_secret[PATH_MAX];
  14178. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14179. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14180. auto se = detail::scope_exit([&] {
  14181. unlink(symlink_path.c_str());
  14182. unlink(secret_file.c_str());
  14183. rmdir(served_dir.c_str());
  14184. rmdir(secret_dir.c_str());
  14185. });
  14186. Server svr;
  14187. svr.set_mount_point("/", served_dir);
  14188. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14189. auto se2 = detail::scope_exit([&] {
  14190. svr.stop();
  14191. listen_thread.join();
  14192. });
  14193. svr.wait_until_ready();
  14194. Client cli("localhost", PORT);
  14195. // Symlink pointing outside base dir should be blocked
  14196. auto res = cli.Get("/escape/secret.txt");
  14197. ASSERT_TRUE(res);
  14198. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14199. }
  14200. #endif