test.cc 508 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578
  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. void performance_test(const char *host) {
  91. Server svr;
  92. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  93. res.set_content("Benchmark Response", "text/plain");
  94. });
  95. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  96. auto se = detail::scope_exit([&] {
  97. svr.stop();
  98. listen_thread.join();
  99. ASSERT_FALSE(svr.is_running());
  100. });
  101. svr.wait_until_ready();
  102. Client cli(host, PORT);
  103. // Warm-up request to establish connection and resolve DNS
  104. auto warmup_res = cli.Get("/benchmark");
  105. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  106. // Run multiple trials and collect timings
  107. const int num_trials = 20;
  108. std::vector<int64_t> timings;
  109. timings.reserve(num_trials);
  110. for (int i = 0; i < num_trials; i++) {
  111. auto start = std::chrono::high_resolution_clock::now();
  112. auto res = cli.Get("/benchmark");
  113. auto end = std::chrono::high_resolution_clock::now();
  114. auto elapsed =
  115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  116. .count();
  117. // Assertions after timing measurement to avoid overhead
  118. ASSERT_TRUE(res);
  119. EXPECT_EQ(StatusCode::OK_200, res->status);
  120. timings.push_back(elapsed);
  121. }
  122. // Calculate 25th percentile (lower quartile)
  123. std::sort(timings.begin(), timings.end());
  124. auto p25 = timings[num_trials / 4];
  125. // Format timings for output
  126. std::ostringstream timings_str;
  127. timings_str << "[";
  128. for (size_t i = 0; i < timings.size(); i++) {
  129. if (i > 0) timings_str << ", ";
  130. timings_str << timings[i];
  131. }
  132. timings_str << "]";
  133. // Localhost HTTP GET should be fast even in CI environments
  134. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  135. << "ms (Issue #1777). Timings: " << timings_str.str();
  136. }
  137. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  138. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  139. class UnixSocketTest : public ::testing::Test {
  140. protected:
  141. void TearDown() override { std::remove(pathname_.c_str()); }
  142. void client_GET(const std::string &addr) {
  143. httplib::Client cli{addr};
  144. cli.set_address_family(AF_UNIX);
  145. ASSERT_TRUE(cli.is_valid());
  146. const auto &result = cli.Get(pattern_);
  147. ASSERT_TRUE(result) << "error: " << result.error();
  148. const auto &resp = result.value();
  149. EXPECT_EQ(resp.status, StatusCode::OK_200);
  150. EXPECT_EQ(resp.body, content_);
  151. }
  152. static std::string make_sock_path() {
  153. const char *shard = getenv("GTEST_SHARD_INDEX");
  154. return shard ? std::string("./httplib-server-") + shard + ".sock"
  155. : "./httplib-server.sock";
  156. }
  157. const std::string pathname_{make_sock_path()};
  158. const std::string pattern_{"/hi"};
  159. const std::string content_{"Hello World!"};
  160. };
  161. TEST_F(UnixSocketTest, pathname) {
  162. httplib::Server svr;
  163. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  164. res.set_content(content_, "text/plain");
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. }
  178. #if defined(__linux__) || \
  179. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  180. TEST_F(UnixSocketTest, PeerPid) {
  181. httplib::Server svr;
  182. std::string remote_port_val;
  183. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. remote_port_val = std::to_string(req.remote_port);
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(pathname_);
  198. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  199. }
  200. #endif
  201. #ifdef __linux__
  202. TEST_F(UnixSocketTest, abstract) {
  203. constexpr char svr_path[]{"\x00httplib-server.sock"};
  204. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  205. httplib::Server svr;
  206. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. client_GET(abstract_addr);
  220. }
  221. #endif
  222. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  223. httplib::Server svr;
  224. std::string received_host_header;
  225. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  226. // Capture the Host header sent by the client
  227. auto host_iter = req.headers.find("Host");
  228. if (host_iter != req.headers.end()) {
  229. received_host_header = host_iter->second;
  230. }
  231. res.set_content(content_, "text/plain");
  232. });
  233. std::thread t{[&] {
  234. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  235. }};
  236. auto se = detail::scope_exit([&] {
  237. svr.stop();
  238. t.join();
  239. ASSERT_FALSE(svr.is_running());
  240. });
  241. svr.wait_until_ready();
  242. ASSERT_TRUE(svr.is_running());
  243. // Test that Host header is automatically set to "localhost" for Unix socket
  244. // connections
  245. httplib::Client cli{pathname_};
  246. cli.set_address_family(AF_UNIX);
  247. ASSERT_TRUE(cli.is_valid());
  248. const auto &result = cli.Get(pattern_);
  249. ASSERT_TRUE(result) << "error: " << result.error();
  250. const auto &resp = result.value();
  251. EXPECT_EQ(resp.status, StatusCode::OK_200);
  252. EXPECT_EQ(resp.body, content_);
  253. // Verify that Host header was automatically set to "localhost"
  254. EXPECT_EQ(received_host_header, "localhost");
  255. }
  256. #ifndef _WIN32
  257. TEST(SocketStream, wait_writable_UNIX) {
  258. int fds[2];
  259. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  260. const auto asSocketStream = [&](socket_t fd,
  261. std::function<bool(Stream &)> func) {
  262. return detail::process_client_socket(
  263. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  264. };
  265. asSocketStream(fds[0], [&](Stream &s0) {
  266. EXPECT_EQ(s0.socket(), fds[0]);
  267. EXPECT_TRUE(s0.wait_writable());
  268. EXPECT_EQ(0, close(fds[1]));
  269. EXPECT_FALSE(s0.wait_writable());
  270. return true;
  271. });
  272. EXPECT_EQ(0, close(fds[0]));
  273. }
  274. TEST(SocketStream, wait_writable_INET) {
  275. sockaddr_in addr;
  276. memset(&addr, 0, sizeof(addr));
  277. addr.sin_family = AF_INET;
  278. addr.sin_port = htons(PORT + 1);
  279. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  280. int disconnected_svr_sock = -1;
  281. std::thread svr{[&] {
  282. const int s = socket(AF_INET, SOCK_STREAM, 0);
  283. ASSERT_LE(0, s);
  284. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  285. ASSERT_EQ(0, listen(s, 1));
  286. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  287. ASSERT_EQ(0, close(s));
  288. }};
  289. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  290. std::thread cli{[&] {
  291. const int s = socket(AF_INET, SOCK_STREAM, 0);
  292. ASSERT_LE(0, s);
  293. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  294. ASSERT_EQ(0, close(s));
  295. }};
  296. cli.join();
  297. svr.join();
  298. ASSERT_NE(disconnected_svr_sock, -1);
  299. const auto asSocketStream = [&](socket_t fd,
  300. std::function<bool(Stream &)> func) {
  301. return detail::process_client_socket(
  302. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  303. };
  304. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  305. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  306. EXPECT_FALSE(ss.wait_writable());
  307. return true;
  308. });
  309. ASSERT_EQ(0, close(disconnected_svr_sock));
  310. }
  311. #endif // #ifndef _WIN32
  312. TEST(ClientTest, MoveConstructible) {
  313. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  314. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  315. }
  316. TEST(ClientTest, MoveAssignable) {
  317. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  318. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  319. }
  320. #ifdef _WIN32
  321. TEST(StartupTest, WSAStartup) {
  322. WSADATA wsaData;
  323. int ret = WSAStartup(0x0002, &wsaData);
  324. ASSERT_EQ(0, ret);
  325. }
  326. #endif
  327. TEST(DecodePathTest, PercentCharacter) {
  328. EXPECT_EQ(
  329. decode_path_component(
  330. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  331. U8("descrip=Gastos áéíóúñÑ 6"));
  332. }
  333. TEST(DecodePathTest, PercentCharacterNUL) {
  334. string expected;
  335. expected.push_back('x');
  336. expected.push_back('\0');
  337. expected.push_back('x');
  338. EXPECT_EQ(decode_path_component("x%00x"), expected);
  339. }
  340. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  341. string unescapedCharacters = "-_.!~*'()";
  342. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  343. }
  344. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  345. string reservedCharacters = ";,/?:@&=+$";
  346. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  347. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  348. }
  349. TEST(ClientQueryOrder, PreserveOrder) {
  350. // This test reproduces Issue #2259: client may reorder query parameters
  351. // when sending a GET request. The expected behavior is that the client
  352. // preserves the original query string order when the caller supplied it
  353. // as part of the path.
  354. Server svr;
  355. svr.Get("/", [&](const Request &req, Response &res) {
  356. // Echo back the raw target so the test can assert ordering
  357. res.set_content(req.target, "text/plain");
  358. });
  359. std::thread t{[&] { svr.listen(HOST, PORT); }};
  360. auto se = detail::scope_exit([&] {
  361. svr.stop();
  362. t.join();
  363. ASSERT_FALSE(svr.is_running());
  364. });
  365. svr.wait_until_ready();
  366. Client cli(HOST, PORT);
  367. ASSERT_TRUE(cli.is_valid());
  368. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  369. auto res = cli.Get(original);
  370. ASSERT_TRUE(res);
  371. // Expect the echoed target to exactly match the original path (order
  372. // preserved)
  373. EXPECT_EQ(res->body, original);
  374. }
  375. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  376. string chineseCharacters = U8("中国語");
  377. string russianCharacters = U8("дом");
  378. string brazilianCharacters = U8("óculos");
  379. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  380. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  381. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  382. "%D0%B4%D0%BE%D0%BC");
  383. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  384. }
  385. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  386. string unescapedCharacters = "-_.!~*'()";
  387. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  388. }
  389. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  390. string reservedCharacters = ";,/?:@&=+$";
  391. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  392. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  393. }
  394. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  395. string chineseCharacters = U8("中国語");
  396. string russianCharacters = U8("дом");
  397. string brazilianCharacters = U8("óculos");
  398. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  399. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  400. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  401. "%D0%B4%D0%BE%D0%BC");
  402. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  403. }
  404. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  405. // Issue #2082 use case: encoding path component with ampersand
  406. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  407. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  408. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  409. }
  410. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  411. string unescapedCharacters = "-_.!~*'()";
  412. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  413. }
  414. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  415. string reservedCharacters = ";,/?:@&=+$#";
  416. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  417. }
  418. TEST(EncodeUriTest, TestUTF8Characters) {
  419. string chineseCharacters = U8("中国語");
  420. string russianCharacters = U8("дом");
  421. string brazilianCharacters = U8("óculos");
  422. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  423. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  424. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  425. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  426. }
  427. TEST(EncodeUriTest, TestCompleteUri) {
  428. string uri =
  429. "https://example.com/path/to/resource?query=value&param=test#fragment";
  430. EXPECT_EQ(
  431. httplib::encode_uri(uri),
  432. "https://example.com/path/to/resource?query=value&param=test#fragment");
  433. }
  434. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  435. string uri =
  436. "https://example.com/path with spaces/file name.html?q=hello world";
  437. EXPECT_EQ(httplib::encode_uri(uri),
  438. "https://example.com/path%20with%20spaces/"
  439. "file%20name.html?q=hello%20world");
  440. }
  441. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  442. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  443. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  444. }
  445. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  446. string unescapedCharacters = "-_.!~*'()";
  447. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  448. }
  449. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  450. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  451. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  452. string encodedBrazilian = "%C3%B3culos";
  453. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  454. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  455. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  456. }
  457. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  458. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  459. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  460. "Piri Tommy Villiers - on & on");
  461. }
  462. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  463. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  464. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  465. }
  466. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  467. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  468. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  469. }
  470. TEST(DecodeUriTest, TestUTF8Characters) {
  471. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  472. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  473. string encodedBrazilian = "%C3%B3culos";
  474. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  475. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  476. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  477. }
  478. TEST(DecodeUriTest, TestCompleteUri) {
  479. string encodedUri = "https://example.com/path%20with%20spaces/"
  480. "file%20name.html?q=hello%20world";
  481. EXPECT_EQ(
  482. httplib::decode_uri(encodedUri),
  483. "https://example.com/path with spaces/file name.html?q=hello world");
  484. }
  485. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  486. string original =
  487. "https://example.com/path with spaces/file name.html?q=hello world";
  488. string encoded = httplib::encode_uri(original);
  489. string decoded = httplib::decode_uri(encoded);
  490. EXPECT_EQ(decoded, original);
  491. }
  492. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  493. string original = "Piri Tommy Villiers - on & on";
  494. string encoded = httplib::encode_uri_component(original);
  495. string decoded = httplib::decode_uri_component(encoded);
  496. EXPECT_EQ(decoded, original);
  497. }
  498. TEST(TrimTests, TrimStringTests) {
  499. EXPECT_EQ("abc", detail::trim_copy("abc"));
  500. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  501. EXPECT_TRUE(detail::trim_copy("").empty());
  502. }
  503. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  504. // Simple case without quality values
  505. std::vector<std::string> result1;
  506. EXPECT_TRUE(detail::parse_accept_header(
  507. "text/html,application/json,text/plain", result1));
  508. EXPECT_EQ(result1.size(), 3U);
  509. EXPECT_EQ(result1[0], "text/html");
  510. EXPECT_EQ(result1[1], "application/json");
  511. EXPECT_EQ(result1[2], "text/plain");
  512. // With quality values
  513. std::vector<std::string> result2;
  514. EXPECT_TRUE(detail::parse_accept_header(
  515. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  516. EXPECT_EQ(result2.size(), 3U);
  517. EXPECT_EQ(result2[0], "application/json"); // highest q value
  518. EXPECT_EQ(result2[1], "text/html");
  519. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  520. }
  521. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  522. // Mixed with and without quality values
  523. std::vector<std::string> result;
  524. EXPECT_TRUE(detail::parse_accept_header(
  525. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  526. EXPECT_EQ(result.size(), 3U);
  527. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  528. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  529. EXPECT_EQ(result[2], "application/json"); // q=0.5
  530. }
  531. TEST(ParseAcceptHeaderTest, EdgeCases) {
  532. // Empty header
  533. std::vector<std::string> empty_result;
  534. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  535. EXPECT_TRUE(empty_result.empty());
  536. // Single type
  537. std::vector<std::string> single_result;
  538. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  539. EXPECT_EQ(single_result.size(), 1U);
  540. EXPECT_EQ(single_result[0], "application/json");
  541. // Wildcard types
  542. std::vector<std::string> wildcard_result;
  543. EXPECT_TRUE(detail::parse_accept_header(
  544. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  545. EXPECT_EQ(wildcard_result.size(), 3U);
  546. EXPECT_EQ(wildcard_result[0], "application/json");
  547. EXPECT_EQ(wildcard_result[1], "text/*");
  548. EXPECT_EQ(wildcard_result[2], "*/*");
  549. }
  550. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  551. // Common browser Accept header
  552. std::vector<std::string> browser_result;
  553. EXPECT_TRUE(
  554. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  555. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  556. browser_result));
  557. EXPECT_EQ(browser_result.size(), 6U);
  558. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  560. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  561. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  562. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  563. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  564. // API client header
  565. std::vector<std::string> api_result;
  566. EXPECT_TRUE(detail::parse_accept_header(
  567. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  568. api_result));
  569. EXPECT_EQ(api_result.size(), 3U);
  570. EXPECT_EQ(api_result[0], "application/json");
  571. EXPECT_EQ(api_result[1], "application/xml");
  572. EXPECT_EQ(api_result[2], "text/plain");
  573. }
  574. TEST(ParseAcceptHeaderTest, SpecialCases) {
  575. // Quality value with 3 decimal places
  576. std::vector<std::string> decimal_result;
  577. EXPECT_TRUE(detail::parse_accept_header(
  578. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  579. EXPECT_EQ(decimal_result.size(), 2U);
  580. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  581. EXPECT_EQ(decimal_result[1], "text/html");
  582. // Zero quality (should still be included but with lowest priority)
  583. std::vector<std::string> zero_q_result;
  584. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  585. zero_q_result));
  586. EXPECT_EQ(zero_q_result.size(), 2U);
  587. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  588. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  589. // No spaces around commas
  590. std::vector<std::string> no_space_result;
  591. EXPECT_TRUE(detail::parse_accept_header(
  592. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  593. no_space_result));
  594. EXPECT_EQ(no_space_result.size(), 3U);
  595. EXPECT_EQ(no_space_result[0], "text/html");
  596. EXPECT_EQ(no_space_result[1], "application/json");
  597. EXPECT_EQ(no_space_result[2], "text/plain");
  598. }
  599. TEST(ParseAcceptHeaderTest, InvalidCases) {
  600. std::vector<std::string> result;
  601. // Invalid quality value (> 1.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  604. // Invalid quality value (< 0.0)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  607. // Invalid quality value (not a number)
  608. EXPECT_FALSE(detail::parse_accept_header(
  609. "text/html;q=invalid,application/json", result));
  610. // Empty quality value
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("text/html;q=,application/json", result));
  613. // Invalid media type format (no slash and not wildcard)
  614. EXPECT_FALSE(
  615. detail::parse_accept_header("invalidtype,application/json", result));
  616. // Empty media type
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  619. // Only commas
  620. result.clear();
  621. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  622. // Valid cases should still work
  623. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*/*");
  626. EXPECT_TRUE(detail::parse_accept_header("*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "*");
  629. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  630. EXPECT_EQ(result.size(), 1U);
  631. EXPECT_EQ(result[0], "text/*");
  632. }
  633. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  634. Server svr;
  635. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  636. EXPECT_EQ(req.accept_content_types.size(), 3U);
  637. EXPECT_EQ(req.accept_content_types[0], "application/json");
  638. EXPECT_EQ(req.accept_content_types[1], "text/html");
  639. EXPECT_EQ(req.accept_content_types[2], "*/*");
  640. res.set_content("ok", "text/plain");
  641. });
  642. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  643. EXPECT_TRUE(false);
  644. res.set_content("bad request", "text/plain");
  645. });
  646. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  647. auto se = detail::scope_exit([&] {
  648. svr.stop();
  649. listen_thread.join();
  650. ASSERT_FALSE(svr.is_running());
  651. });
  652. svr.wait_until_ready();
  653. Client cli("localhost", PORT);
  654. {
  655. auto res =
  656. cli.Get("/accept_ok",
  657. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  658. ASSERT_TRUE(res);
  659. EXPECT_EQ(StatusCode::OK_200, res->status);
  660. }
  661. {
  662. auto res = cli.Get("/accept_bad_request",
  663. {{"Accept", "text/html;q=abc,application/json"}});
  664. ASSERT_TRUE(res);
  665. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  666. }
  667. }
  668. TEST(DivideTest, DivideStringTests) {
  669. auto divide = [](const std::string &str, char d) {
  670. std::string lhs;
  671. std::string rhs;
  672. detail::divide(str, d,
  673. [&](const char *lhs_data, std::size_t lhs_size,
  674. const char *rhs_data, std::size_t rhs_size) {
  675. lhs.assign(lhs_data, lhs_size);
  676. rhs.assign(rhs_data, rhs_size);
  677. });
  678. return std::make_pair(std::move(lhs), std::move(rhs));
  679. };
  680. {
  681. const auto res = divide("", '=');
  682. EXPECT_EQ(res.first, "");
  683. EXPECT_EQ(res.second, "");
  684. }
  685. {
  686. const auto res = divide("=", '=');
  687. EXPECT_EQ(res.first, "");
  688. EXPECT_EQ(res.second, "");
  689. }
  690. {
  691. const auto res = divide(" ", '=');
  692. EXPECT_EQ(res.first, " ");
  693. EXPECT_EQ(res.second, "");
  694. }
  695. {
  696. const auto res = divide("a", '=');
  697. EXPECT_EQ(res.first, "a");
  698. EXPECT_EQ(res.second, "");
  699. }
  700. {
  701. const auto res = divide("a=", '=');
  702. EXPECT_EQ(res.first, "a");
  703. EXPECT_EQ(res.second, "");
  704. }
  705. {
  706. const auto res = divide("=b", '=');
  707. EXPECT_EQ(res.first, "");
  708. EXPECT_EQ(res.second, "b");
  709. }
  710. {
  711. const auto res = divide("a=b", '=');
  712. EXPECT_EQ(res.first, "a");
  713. EXPECT_EQ(res.second, "b");
  714. }
  715. {
  716. const auto res = divide("a=b=", '=');
  717. EXPECT_EQ(res.first, "a");
  718. EXPECT_EQ(res.second, "b=");
  719. }
  720. {
  721. const auto res = divide("a=b=c", '=');
  722. EXPECT_EQ(res.first, "a");
  723. EXPECT_EQ(res.second, "b=c");
  724. }
  725. }
  726. TEST(SplitTest, ParseQueryString) {
  727. string s = "key1=val1&key2=val2&key3=val3";
  728. Params dic;
  729. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  730. [&](const char *b, const char *e) {
  731. string key, val;
  732. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  733. if (key.empty()) {
  734. key.assign(b2, e2);
  735. } else {
  736. val.assign(b2, e2);
  737. }
  738. });
  739. dic.emplace(key, val);
  740. });
  741. EXPECT_EQ("val1", dic.find("key1")->second);
  742. EXPECT_EQ("val2", dic.find("key2")->second);
  743. EXPECT_EQ("val3", dic.find("key3")->second);
  744. }
  745. TEST(SplitTest, ParseInvalidQueryTests) {
  746. {
  747. string s = " ";
  748. Params dict;
  749. detail::parse_query_text(s, dict);
  750. EXPECT_TRUE(dict.empty());
  751. }
  752. {
  753. string s = " = =";
  754. Params dict;
  755. detail::parse_query_text(s, dict);
  756. EXPECT_TRUE(dict.empty());
  757. }
  758. }
  759. TEST(ParseQueryTest, ParseQueryString) {
  760. {
  761. std::string s = "key1=val1&key2=val2&key3=val3";
  762. Params dic;
  763. detail::parse_query_text(s, dic);
  764. EXPECT_EQ("val1", dic.find("key1")->second);
  765. EXPECT_EQ("val2", dic.find("key2")->second);
  766. EXPECT_EQ("val3", dic.find("key3")->second);
  767. }
  768. {
  769. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  770. Params dic;
  771. detail::parse_query_text(s, dic);
  772. EXPECT_EQ("", dic.find("key1")->second);
  773. EXPECT_EQ("val1", dic.find("key2")->second);
  774. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  775. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  776. }
  777. }
  778. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  779. Params dic;
  780. EXPECT_EQ(detail::params_to_query_str(dic), "");
  781. dic.emplace("key1", "val1");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  783. dic.emplace("key2", "val2");
  784. dic.emplace("key3", "val3");
  785. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  786. }
  787. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  788. string content_type = "multipart/form-data; boundary=something";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "something");
  793. }
  794. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  795. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  796. string boundary;
  797. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  798. EXPECT_TRUE(ret);
  799. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  800. }
  801. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  802. string content_type =
  803. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  804. string boundary;
  805. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  806. EXPECT_TRUE(ret);
  807. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  808. }
  809. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  810. string content_type =
  811. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  812. string boundary;
  813. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  814. EXPECT_TRUE(ret);
  815. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  816. }
  817. TEST(GetHeaderValueTest, DefaultValue) {
  818. Headers headers = {{"Dummy", "Dummy"}};
  819. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  820. EXPECT_STREQ("text/plain", val);
  821. }
  822. TEST(GetHeaderValueTest, DefaultValueInt) {
  823. Headers headers = {{"Dummy", "Dummy"}};
  824. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  825. EXPECT_EQ(100ull, val);
  826. }
  827. TEST(GetHeaderValueTest, RegularValue) {
  828. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  829. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  830. EXPECT_STREQ("text/html", val);
  831. }
  832. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  833. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  834. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  835. EXPECT_STREQ("text/html", val);
  836. }
  837. TEST(GetHeaderValueTest, SetContent) {
  838. Response res;
  839. res.set_content("html", "text/html");
  840. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  841. res.set_content("text", "text/plain");
  842. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  843. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  844. }
  845. TEST(GetHeaderValueTest, RegularValueInt) {
  846. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  847. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  848. EXPECT_EQ(100ull, val);
  849. }
  850. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  851. Headers headers = {{"Content-Length", "x"}};
  852. auto is_invalid_value = false;
  853. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  854. is_invalid_value);
  855. EXPECT_EQ(0ull, val);
  856. EXPECT_TRUE(is_invalid_value);
  857. }
  858. TEST(GetHeaderValueTest, Range) {
  859. {
  860. Headers headers = {make_range_header({{1, -1}})};
  861. auto val = detail::get_header_value(headers, "Range", 0, 0);
  862. EXPECT_STREQ("bytes=1-", val);
  863. }
  864. {
  865. Headers headers = {make_range_header({{-1, 1}})};
  866. auto val = detail::get_header_value(headers, "Range", 0, 0);
  867. EXPECT_STREQ("bytes=-1", val);
  868. }
  869. {
  870. Headers headers = {make_range_header({{1, 10}})};
  871. auto val = detail::get_header_value(headers, "Range", 0, 0);
  872. EXPECT_STREQ("bytes=1-10", val);
  873. }
  874. {
  875. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  876. auto val = detail::get_header_value(headers, "Range", 0, 0);
  877. EXPECT_STREQ("bytes=1-10, 100-", val);
  878. }
  879. {
  880. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  881. auto val = detail::get_header_value(headers, "Range", 0, 0);
  882. EXPECT_STREQ("bytes=1-10, 100-200", val);
  883. }
  884. {
  885. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  886. auto val = detail::get_header_value(headers, "Range", 0, 0);
  887. EXPECT_STREQ("bytes=0-0, -1", val);
  888. }
  889. }
  890. TEST(ParseHeaderValueTest, Range) {
  891. {
  892. Ranges ranges;
  893. auto ret = detail::parse_range_header("bytes=1-", ranges);
  894. EXPECT_TRUE(ret);
  895. EXPECT_EQ(1u, ranges.size());
  896. EXPECT_EQ(1u, ranges[0].first);
  897. EXPECT_EQ(-1, ranges[0].second);
  898. }
  899. {
  900. Ranges ranges;
  901. auto ret = detail::parse_range_header("bytes=-1", ranges);
  902. EXPECT_TRUE(ret);
  903. EXPECT_EQ(1u, ranges.size());
  904. EXPECT_EQ(-1, ranges[0].first);
  905. EXPECT_EQ(1u, ranges[0].second);
  906. }
  907. {
  908. Ranges ranges;
  909. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  910. EXPECT_TRUE(ret);
  911. EXPECT_EQ(1u, ranges.size());
  912. EXPECT_EQ(1u, ranges[0].first);
  913. EXPECT_EQ(10u, ranges[0].second);
  914. }
  915. {
  916. Ranges ranges;
  917. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  918. EXPECT_FALSE(ret);
  919. }
  920. {
  921. Ranges ranges;
  922. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  923. EXPECT_TRUE(ret);
  924. EXPECT_EQ(2u, ranges.size());
  925. EXPECT_EQ(1u, ranges[0].first);
  926. EXPECT_EQ(10u, ranges[0].second);
  927. EXPECT_EQ(100u, ranges[1].first);
  928. EXPECT_EQ(-1, ranges[1].second);
  929. }
  930. {
  931. Ranges ranges;
  932. auto ret =
  933. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  934. EXPECT_TRUE(ret);
  935. EXPECT_EQ(3u, ranges.size());
  936. EXPECT_EQ(1u, ranges[0].first);
  937. EXPECT_EQ(10u, ranges[0].second);
  938. EXPECT_EQ(100u, ranges[1].first);
  939. EXPECT_EQ(200u, ranges[1].second);
  940. EXPECT_EQ(300u, ranges[2].first);
  941. EXPECT_EQ(400u, ranges[2].second);
  942. }
  943. {
  944. Ranges ranges;
  945. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  955. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  956. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  957. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  958. EXPECT_TRUE(ranges.empty());
  959. }
  960. }
  961. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  962. Request req;
  963. req.set_header("Accept-Encoding", "gzip");
  964. Response res;
  965. res.set_header("Content-Type", "text/plain");
  966. auto ret = detail::encoding_type(req, res);
  967. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  968. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  969. #else
  970. EXPECT_TRUE(ret == detail::EncodingType::None);
  971. #endif
  972. }
  973. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  974. Request req;
  975. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  976. Response res;
  977. res.set_header("Content-Type", "text/plain");
  978. auto ret = detail::encoding_type(req, res);
  979. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  980. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  981. #elif CPPHTTPLIB_ZLIB_SUPPORT
  982. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  983. #elif CPPHTTPLIB_ZSTD_SUPPORT
  984. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  985. #else
  986. EXPECT_TRUE(ret == detail::EncodingType::None);
  987. #endif
  988. }
  989. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  990. Request req;
  991. req.set_header("Accept-Encoding",
  992. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  993. Response res;
  994. res.set_header("Content-Type", "text/plain");
  995. auto ret = detail::encoding_type(req, res);
  996. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  997. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  998. #elif CPPHTTPLIB_ZLIB_SUPPORT
  999. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1000. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1001. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1002. #else
  1003. EXPECT_TRUE(ret == detail::EncodingType::None);
  1004. #endif
  1005. }
  1006. TEST(BufferStreamTest, read) {
  1007. detail::BufferStream strm1;
  1008. Stream &strm = strm1;
  1009. EXPECT_EQ(5, strm.write("hello"));
  1010. char buf[512];
  1011. EXPECT_EQ(2, strm.read(buf, 2));
  1012. EXPECT_EQ('h', buf[0]);
  1013. EXPECT_EQ('e', buf[1]);
  1014. EXPECT_EQ(2, strm.read(buf, 2));
  1015. EXPECT_EQ('l', buf[0]);
  1016. EXPECT_EQ('l', buf[1]);
  1017. EXPECT_EQ(1, strm.read(buf, 1));
  1018. EXPECT_EQ('o', buf[0]);
  1019. EXPECT_EQ(0, strm.read(buf, 1));
  1020. }
  1021. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1022. auto host = "www.httpwatch.com";
  1023. auto ip = hosted_at(host);
  1024. EXPECT_EQ("23.96.13.243", ip);
  1025. std::vector<std::string> addrs;
  1026. hosted_at(host, addrs);
  1027. EXPECT_EQ(1u, addrs.size());
  1028. }
  1029. #if 0 // It depends on each test environment...
  1030. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1031. auto host = "www.youtube.com";
  1032. std::vector<std::string> addrs;
  1033. hosted_at(host, addrs);
  1034. EXPECT_EQ(20u, addrs.size());
  1035. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1036. EXPECT_TRUE(it != addrs.end());
  1037. }
  1038. #endif
  1039. class ChunkedEncodingTest : public ::testing::Test {
  1040. protected:
  1041. ChunkedEncodingTest()
  1042. : cli_(HOST, PORT)
  1043. #ifdef CPPHTTPLIB_SSL_ENABLED
  1044. ,
  1045. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1046. #endif
  1047. {
  1048. cli_.set_connection_timeout(2);
  1049. #ifdef CPPHTTPLIB_SSL_ENABLED
  1050. cli_.enable_server_certificate_verification(false);
  1051. #endif
  1052. }
  1053. virtual void SetUp() {
  1054. read_file("./image.jpg", image_data_);
  1055. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1056. res.set_content("Hello World!", "text/plain");
  1057. });
  1058. svr_.Get(
  1059. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1060. res.set_chunked_content_provider(
  1061. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1062. size_t remaining = image_data_.size() - offset;
  1063. if (remaining == 0) {
  1064. sink.done();
  1065. } else {
  1066. constexpr size_t CHUNK_SIZE = 1024;
  1067. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1068. sink.write(&image_data_[offset], send_size);
  1069. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1070. }
  1071. return true;
  1072. });
  1073. });
  1074. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1075. svr_.wait_until_ready();
  1076. }
  1077. virtual void TearDown() {
  1078. svr_.stop();
  1079. if (!request_threads_.empty()) {
  1080. std::this_thread::sleep_for(std::chrono::seconds(1));
  1081. for (auto &t : request_threads_) {
  1082. t.join();
  1083. }
  1084. }
  1085. t_.join();
  1086. }
  1087. #ifdef CPPHTTPLIB_SSL_ENABLED
  1088. SSLClient cli_;
  1089. SSLServer svr_;
  1090. #else
  1091. Client cli_;
  1092. Server svr_;
  1093. #endif
  1094. thread t_;
  1095. std::vector<thread> request_threads_;
  1096. std::string image_data_;
  1097. };
  1098. TEST_F(ChunkedEncodingTest, NormalGet) {
  1099. auto res = cli_.Get("/chunked");
  1100. ASSERT_TRUE(res);
  1101. std::string out;
  1102. read_file("./image.jpg", out);
  1103. EXPECT_EQ(StatusCode::OK_200, res->status);
  1104. EXPECT_EQ(out, res->body);
  1105. }
  1106. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1107. std::string body;
  1108. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1109. body.append(data, data_length);
  1110. return true;
  1111. });
  1112. ASSERT_TRUE(res);
  1113. std::string out;
  1114. read_file("./image.jpg", out);
  1115. EXPECT_EQ(StatusCode::OK_200, res->status);
  1116. EXPECT_EQ(out, body);
  1117. }
  1118. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1119. std::string body;
  1120. auto res = cli_.Get(
  1121. "/chunked",
  1122. [&](const Response &response) {
  1123. EXPECT_EQ(StatusCode::OK_200, response.status);
  1124. return true;
  1125. },
  1126. [&](const char *data, size_t data_length) {
  1127. body.append(data, data_length);
  1128. return true;
  1129. });
  1130. ASSERT_TRUE(res);
  1131. std::string out;
  1132. read_file("./image.jpg", out);
  1133. EXPECT_EQ(StatusCode::OK_200, res->status);
  1134. EXPECT_EQ(out, body);
  1135. }
  1136. TEST(RangeTest, FromHTTPBin_Online) {
  1137. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1138. auto host = "httpcan.org";
  1139. auto path = std::string{"/range/32"};
  1140. #else
  1141. auto host = "nghttp2.org";
  1142. auto path = std::string{"/httpbin/range/32"};
  1143. #endif
  1144. #ifdef CPPHTTPLIB_SSL_ENABLED
  1145. auto port = 443;
  1146. SSLClient cli(host, port);
  1147. #else
  1148. auto port = 80;
  1149. Client cli(host, port);
  1150. #endif
  1151. cli.set_connection_timeout(5);
  1152. {
  1153. auto res = cli.Get(path);
  1154. ASSERT_TRUE(res);
  1155. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1156. EXPECT_EQ(StatusCode::OK_200, res->status);
  1157. }
  1158. {
  1159. Headers headers = {make_range_header({{1, -1}})};
  1160. auto res = cli.Get(path, headers);
  1161. ASSERT_TRUE(res);
  1162. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1164. }
  1165. {
  1166. Headers headers = {make_range_header({{1, 10}})};
  1167. auto res = cli.Get(path, headers);
  1168. ASSERT_TRUE(res);
  1169. EXPECT_EQ("bcdefghijk", res->body);
  1170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1171. }
  1172. {
  1173. Headers headers = {make_range_header({{0, 31}})};
  1174. auto res = cli.Get(path, headers);
  1175. ASSERT_TRUE(res);
  1176. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1177. EXPECT_EQ(StatusCode::OK_200, res->status);
  1178. }
  1179. {
  1180. Headers headers = {make_range_header({{0, -1}})};
  1181. auto res = cli.Get(path, headers);
  1182. ASSERT_TRUE(res);
  1183. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1184. EXPECT_EQ(StatusCode::OK_200, res->status);
  1185. }
  1186. {
  1187. Headers headers = {make_range_header({{0, 32}})};
  1188. auto res = cli.Get(path, headers);
  1189. ASSERT_TRUE(res);
  1190. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1191. }
  1192. }
  1193. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1194. auto host = "unresolvableaddress.local";
  1195. auto path = std::string{"/"};
  1196. #ifdef CPPHTTPLIB_SSL_ENABLED
  1197. auto port = 443;
  1198. SSLClient cli(host, port);
  1199. #else
  1200. auto port = 80;
  1201. Client cli(host, port);
  1202. #endif
  1203. cli.set_connection_timeout(1);
  1204. {
  1205. auto res = cli.Get(path);
  1206. ASSERT_FALSE(res);
  1207. }
  1208. std::this_thread::sleep_for(std::chrono::seconds(8));
  1209. }
  1210. TEST(ConnectionErrorTest, InvalidHost) {
  1211. auto host = "-abcde.com";
  1212. #ifdef CPPHTTPLIB_SSL_ENABLED
  1213. auto port = 443;
  1214. SSLClient cli(host, port);
  1215. #else
  1216. auto port = 80;
  1217. Client cli(host, port);
  1218. #endif
  1219. cli.set_connection_timeout(std::chrono::seconds(2));
  1220. auto res = cli.Get("/");
  1221. ASSERT_TRUE(!res);
  1222. EXPECT_EQ(Error::Connection, res.error());
  1223. }
  1224. TEST(ConnectionErrorTest, InvalidHost2) {
  1225. auto host = "httpcan.org/";
  1226. #ifdef CPPHTTPLIB_SSL_ENABLED
  1227. SSLClient cli(host);
  1228. #else
  1229. Client cli(host);
  1230. #endif
  1231. cli.set_connection_timeout(std::chrono::seconds(2));
  1232. auto res = cli.Get("/");
  1233. ASSERT_TRUE(!res);
  1234. EXPECT_EQ(Error::Connection, res.error());
  1235. }
  1236. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1237. auto host = "httpcan.org/";
  1238. #ifdef CPPHTTPLIB_SSL_ENABLED
  1239. SSLClient cli(host);
  1240. #else
  1241. Client cli(host);
  1242. #endif
  1243. cli.set_connection_timeout(std::chrono::seconds(2));
  1244. auto res = cli.Get("/");
  1245. ASSERT_TRUE(!res);
  1246. stringstream s;
  1247. s << "error code: " << res.error();
  1248. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1249. }
  1250. TEST(ConnectionErrorTest, InvalidPort) {
  1251. auto host = "localhost";
  1252. auto port = 44380;
  1253. #ifdef CPPHTTPLIB_SSL_ENABLED
  1254. SSLClient cli(host, port);
  1255. #else
  1256. Client cli(host, port);
  1257. #endif
  1258. cli.set_connection_timeout(std::chrono::seconds(2));
  1259. auto res = cli.Get("/");
  1260. ASSERT_TRUE(!res);
  1261. EXPECT_TRUE(Error::Connection == res.error() ||
  1262. Error::ConnectionTimeout == res.error());
  1263. }
  1264. TEST(ConnectionErrorTest, Timeout_Online) {
  1265. auto host = "google.com";
  1266. #ifdef CPPHTTPLIB_SSL_ENABLED
  1267. auto port = 44380;
  1268. SSLClient cli(host, port);
  1269. #else
  1270. auto port = 8080;
  1271. Client cli(host, port);
  1272. #endif
  1273. cli.set_connection_timeout(std::chrono::seconds(2));
  1274. // only probe one address type so that the error reason
  1275. // correlates to the timed-out IPv4, not the unsupported
  1276. // IPv6 connection attempt
  1277. cli.set_address_family(AF_INET);
  1278. auto res = cli.Get("/");
  1279. ASSERT_TRUE(!res);
  1280. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1281. }
  1282. TEST(CancelTest, NoCancel_Online) {
  1283. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1284. auto host = "httpcan.org";
  1285. auto path = std::string{"/range/32"};
  1286. #else
  1287. auto host = "nghttp2.org";
  1288. auto path = std::string{"/httpbin/range/32"};
  1289. #endif
  1290. #ifdef CPPHTTPLIB_SSL_ENABLED
  1291. auto port = 443;
  1292. SSLClient cli(host, port);
  1293. #else
  1294. auto port = 80;
  1295. Client cli(host, port);
  1296. #endif
  1297. cli.set_connection_timeout(std::chrono::seconds(5));
  1298. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1299. ASSERT_TRUE(res);
  1300. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1301. EXPECT_EQ(StatusCode::OK_200, res->status);
  1302. }
  1303. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1304. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1305. auto host = "httpcan.org";
  1306. auto path = std::string{"/range/32"};
  1307. #else
  1308. auto host = "nghttp2.org";
  1309. auto path = std::string{"/httpbin/range/32"};
  1310. #endif
  1311. #ifdef CPPHTTPLIB_SSL_ENABLED
  1312. auto port = 443;
  1313. SSLClient cli(host, port);
  1314. #else
  1315. auto port = 80;
  1316. Client cli(host, port);
  1317. #endif
  1318. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1319. cli.set_connection_timeout(std::chrono::seconds(5));
  1320. ASSERT_TRUE(!res);
  1321. EXPECT_EQ(Error::Canceled, res.error());
  1322. }
  1323. TEST(CancelTest, WithCancelLargePayload_Online) {
  1324. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1325. auto host = "httpcan.org";
  1326. auto path = std::string{"/range/65536"};
  1327. #else
  1328. auto host = "nghttp2.org";
  1329. auto path = std::string{"/httpbin/range/65536"};
  1330. #endif
  1331. #ifdef CPPHTTPLIB_SSL_ENABLED
  1332. auto port = 443;
  1333. SSLClient cli(host, port);
  1334. #else
  1335. auto port = 80;
  1336. Client cli(host, port);
  1337. #endif
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. uint32_t count = 0;
  1340. auto res =
  1341. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1342. ASSERT_TRUE(!res);
  1343. EXPECT_EQ(Error::Canceled, res.error());
  1344. }
  1345. TEST(CancelTest, NoCancelPost) {
  1346. Server svr;
  1347. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1348. res.set_content("Hello World!", "text/plain");
  1349. });
  1350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1351. auto se = detail::scope_exit([&] {
  1352. svr.stop();
  1353. thread.join();
  1354. ASSERT_FALSE(svr.is_running());
  1355. });
  1356. svr.wait_until_ready();
  1357. Client cli(HOST, PORT);
  1358. cli.set_connection_timeout(std::chrono::seconds(5));
  1359. auto res =
  1360. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1361. "application/json", [](uint64_t, uint64_t) { return true; });
  1362. ASSERT_TRUE(res);
  1363. EXPECT_EQ("Hello World!", res->body);
  1364. EXPECT_EQ(StatusCode::OK_200, res->status);
  1365. }
  1366. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1367. Server svr;
  1368. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1369. res.set_content("Hello World!", "text/plain");
  1370. });
  1371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1372. auto se = detail::scope_exit([&] {
  1373. svr.stop();
  1374. thread.join();
  1375. ASSERT_FALSE(svr.is_running());
  1376. });
  1377. svr.wait_until_ready();
  1378. Client cli(HOST, PORT);
  1379. cli.set_connection_timeout(std::chrono::seconds(5));
  1380. auto res =
  1381. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1382. "application/json", [](uint64_t, uint64_t) { return false; });
  1383. ASSERT_TRUE(!res);
  1384. EXPECT_EQ(Error::Canceled, res.error());
  1385. }
  1386. TEST(CancelTest, WithCancelLargePayloadPost) {
  1387. Server svr;
  1388. svr.set_payload_max_length(200 * 1024 * 1024);
  1389. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1390. res.set_content(LARGE_DATA, "text/plain");
  1391. });
  1392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1393. auto se = detail::scope_exit([&] {
  1394. svr.stop();
  1395. thread.join();
  1396. ASSERT_FALSE(svr.is_running());
  1397. });
  1398. svr.wait_until_ready();
  1399. Client cli(HOST, PORT);
  1400. cli.set_payload_max_length(200 * 1024 * 1024);
  1401. cli.set_connection_timeout(std::chrono::seconds(5));
  1402. auto res =
  1403. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1404. "application/json", [](uint64_t, uint64_t) { return false; });
  1405. ASSERT_TRUE(!res);
  1406. EXPECT_EQ(Error::Canceled, res.error());
  1407. }
  1408. TEST(CancelTest, NoCancelPut) {
  1409. Server svr;
  1410. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1411. res.set_content("Hello World!", "text/plain");
  1412. });
  1413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1414. auto se = detail::scope_exit([&] {
  1415. svr.stop();
  1416. thread.join();
  1417. ASSERT_FALSE(svr.is_running());
  1418. });
  1419. svr.wait_until_ready();
  1420. Client cli(HOST, PORT);
  1421. cli.set_connection_timeout(std::chrono::seconds(5));
  1422. auto res =
  1423. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1424. "application/json", [](uint64_t, uint64_t) { return true; });
  1425. ASSERT_TRUE(res);
  1426. EXPECT_EQ("Hello World!", res->body);
  1427. EXPECT_EQ(StatusCode::OK_200, res->status);
  1428. }
  1429. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1430. Server svr;
  1431. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1432. res.set_content("Hello World!", "text/plain");
  1433. });
  1434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1435. auto se = detail::scope_exit([&] {
  1436. svr.stop();
  1437. thread.join();
  1438. ASSERT_FALSE(svr.is_running());
  1439. });
  1440. svr.wait_until_ready();
  1441. Client cli(HOST, PORT);
  1442. cli.set_connection_timeout(std::chrono::seconds(5));
  1443. auto res =
  1444. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1445. "application/json", [](uint64_t, uint64_t) { return false; });
  1446. ASSERT_TRUE(!res);
  1447. EXPECT_EQ(Error::Canceled, res.error());
  1448. }
  1449. TEST(CancelTest, WithCancelLargePayloadPut) {
  1450. Server svr;
  1451. svr.set_payload_max_length(200 * 1024 * 1024);
  1452. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1453. res.set_content(LARGE_DATA, "text/plain");
  1454. });
  1455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. thread.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. Client cli(HOST, PORT);
  1463. cli.set_payload_max_length(200 * 1024 * 1024);
  1464. cli.set_connection_timeout(std::chrono::seconds(5));
  1465. auto res =
  1466. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1467. "application/json", [](uint64_t, uint64_t) { return false; });
  1468. ASSERT_TRUE(!res);
  1469. EXPECT_EQ(Error::Canceled, res.error());
  1470. }
  1471. TEST(CancelTest, NoCancelPatch) {
  1472. Server svr;
  1473. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1474. res.set_content("Hello World!", "text/plain");
  1475. });
  1476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1477. auto se = detail::scope_exit([&] {
  1478. svr.stop();
  1479. thread.join();
  1480. ASSERT_FALSE(svr.is_running());
  1481. });
  1482. svr.wait_until_ready();
  1483. Client cli(HOST, PORT);
  1484. cli.set_connection_timeout(std::chrono::seconds(5));
  1485. auto res =
  1486. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1487. "application/json", [](uint64_t, uint64_t) { return true; });
  1488. ASSERT_TRUE(res);
  1489. EXPECT_EQ("Hello World!", res->body);
  1490. EXPECT_EQ(StatusCode::OK_200, res->status);
  1491. }
  1492. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1493. Server svr;
  1494. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1495. res.set_content("Hello World!", "text/plain");
  1496. });
  1497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1498. auto se = detail::scope_exit([&] {
  1499. svr.stop();
  1500. thread.join();
  1501. ASSERT_FALSE(svr.is_running());
  1502. });
  1503. svr.wait_until_ready();
  1504. Client cli(HOST, PORT);
  1505. cli.set_connection_timeout(std::chrono::seconds(5));
  1506. auto res =
  1507. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1508. "application/json", [](uint64_t, uint64_t) { return false; });
  1509. ASSERT_TRUE(!res);
  1510. EXPECT_EQ(Error::Canceled, res.error());
  1511. }
  1512. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1513. Server svr;
  1514. svr.set_payload_max_length(200 * 1024 * 1024);
  1515. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content(LARGE_DATA, "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_payload_max_length(200 * 1024 * 1024);
  1527. cli.set_connection_timeout(std::chrono::seconds(5));
  1528. auto res =
  1529. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1530. "application/json", [](uint64_t, uint64_t) { return false; });
  1531. ASSERT_TRUE(!res);
  1532. EXPECT_EQ(Error::Canceled, res.error());
  1533. }
  1534. TEST(CancelTest, NoCancelDelete) {
  1535. Server svr;
  1536. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return true; });
  1551. ASSERT_TRUE(res);
  1552. EXPECT_EQ("Hello World!", res->body);
  1553. EXPECT_EQ(StatusCode::OK_200, res->status);
  1554. }
  1555. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1556. Server svr;
  1557. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1558. res.set_content("Hello World!", "text/plain");
  1559. });
  1560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1561. auto se = detail::scope_exit([&] {
  1562. svr.stop();
  1563. thread.join();
  1564. ASSERT_FALSE(svr.is_running());
  1565. });
  1566. svr.wait_until_ready();
  1567. Client cli(HOST, PORT);
  1568. cli.set_connection_timeout(std::chrono::seconds(5));
  1569. auto res =
  1570. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1571. "application/json", [](uint64_t, uint64_t) { return false; });
  1572. ASSERT_TRUE(!res);
  1573. EXPECT_EQ(Error::Canceled, res.error());
  1574. }
  1575. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1576. Server svr;
  1577. svr.set_payload_max_length(200 * 1024 * 1024);
  1578. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content(LARGE_DATA, "text/plain");
  1580. });
  1581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. Client cli(HOST, PORT);
  1589. cli.set_payload_max_length(200 * 1024 * 1024);
  1590. cli.set_connection_timeout(std::chrono::seconds(5));
  1591. auto res =
  1592. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1593. "application/json", [](uint64_t, uint64_t) { return false; });
  1594. ASSERT_TRUE(!res);
  1595. EXPECT_EQ(Error::Canceled, res.error());
  1596. }
  1597. static std::string remove_whitespace(const std::string &input) {
  1598. std::string output;
  1599. output.reserve(input.size());
  1600. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1601. [](unsigned char c) { return !std::isspace(c); });
  1602. return output;
  1603. }
  1604. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1605. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1606. auto host = "httpcan.org";
  1607. auto path = std::string{"/basic-auth/hello/world"};
  1608. #else
  1609. auto host = "nghttp2.org";
  1610. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1611. #endif
  1612. #ifdef CPPHTTPLIB_SSL_ENABLED
  1613. auto port = 443;
  1614. SSLClient cli(host, port);
  1615. #else
  1616. auto port = 80;
  1617. Client cli(host, port);
  1618. #endif
  1619. {
  1620. auto res = cli.Get(path);
  1621. ASSERT_TRUE(res);
  1622. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1623. }
  1624. {
  1625. auto res =
  1626. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1629. remove_whitespace(res->body));
  1630. EXPECT_EQ(StatusCode::OK_200, res->status);
  1631. }
  1632. {
  1633. cli.set_basic_auth("hello", "world");
  1634. auto res = cli.Get(path);
  1635. ASSERT_TRUE(res);
  1636. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1637. remove_whitespace(res->body));
  1638. EXPECT_EQ(StatusCode::OK_200, res->status);
  1639. }
  1640. {
  1641. cli.set_basic_auth("hello", "bad");
  1642. auto res = cli.Get(path);
  1643. ASSERT_TRUE(res);
  1644. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1645. }
  1646. {
  1647. cli.set_basic_auth("bad", "world");
  1648. auto res = cli.Get(path);
  1649. ASSERT_TRUE(res);
  1650. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1651. }
  1652. }
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1655. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1656. auto host = "httpcan.org";
  1657. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1658. auto paths = std::vector<std::string>{
  1659. "/digest-auth/auth/hello/world/MD5",
  1660. "/digest-auth/auth/hello/world/SHA-256",
  1661. "/digest-auth/auth/hello/world/SHA-512",
  1662. };
  1663. #else
  1664. auto host = "nghttp2.org";
  1665. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1666. auto paths = std::vector<std::string>{
  1667. "/httpbin/digest-auth/auth/hello/world/MD5",
  1668. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1669. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1670. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1671. };
  1672. #endif
  1673. auto port = 443;
  1674. SSLClient cli(host, port);
  1675. {
  1676. auto res = cli.Get(unauth_path);
  1677. ASSERT_TRUE(res);
  1678. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1679. }
  1680. {
  1681. cli.set_digest_auth("hello", "world");
  1682. for (const auto &path : paths) {
  1683. auto res = cli.Get(path.c_str());
  1684. ASSERT_TRUE(res);
  1685. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1686. std::string algo(path.substr(path.rfind('/') + 1));
  1687. EXPECT_EQ(
  1688. remove_whitespace("{\"algorithm\":\"" + algo +
  1689. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1690. remove_whitespace(res->body));
  1691. #else
  1692. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1693. remove_whitespace(res->body));
  1694. #endif
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. }
  1697. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1698. cli.set_digest_auth("hello", "bad");
  1699. for (const auto &path : paths) {
  1700. auto res = cli.Get(path.c_str());
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1703. }
  1704. #endif
  1705. }
  1706. }
  1707. #endif
  1708. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1709. auto host = "google.com";
  1710. auto another_host = "example.com";
  1711. auto wrong_ip = "0.0.0.0";
  1712. #ifdef CPPHTTPLIB_SSL_ENABLED
  1713. SSLClient cli(host);
  1714. #else
  1715. Client cli(host);
  1716. #endif
  1717. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1718. auto res = cli.Get("/");
  1719. ASSERT_TRUE(res);
  1720. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1721. }
  1722. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1723. auto host = "google.com";
  1724. auto wrong_ip = "0.0.0.0";
  1725. #ifdef CPPHTTPLIB_SSL_ENABLED
  1726. SSLClient cli(host);
  1727. #else
  1728. Client cli(host);
  1729. #endif
  1730. cli.set_hostname_addr_map({{host, wrong_ip}});
  1731. auto res = cli.Get("/");
  1732. ASSERT_TRUE(!res);
  1733. EXPECT_EQ(Error::Connection, res.error());
  1734. }
  1735. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1736. auto host = "nghttp2.org";
  1737. #ifdef CPPHTTPLIB_SSL_ENABLED
  1738. SSLClient cli(host);
  1739. #else
  1740. Client cli(host);
  1741. #endif
  1742. cli.set_follow_location(true);
  1743. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1744. ASSERT_TRUE(res);
  1745. EXPECT_EQ(StatusCode::OK_200, res->status);
  1746. }
  1747. TEST(RedirectTest, Redirect_Online) {
  1748. auto host = "nghttp2.org";
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. SSLClient cli(host);
  1751. #else
  1752. Client cli(host);
  1753. #endif
  1754. cli.set_follow_location(true);
  1755. auto res = cli.Get("/httpbin/redirect/3");
  1756. ASSERT_TRUE(res);
  1757. EXPECT_EQ(StatusCode::OK_200, res->status);
  1758. }
  1759. TEST(RelativeRedirectTest, Redirect_Online) {
  1760. auto host = "nghttp2.org";
  1761. #ifdef CPPHTTPLIB_SSL_ENABLED
  1762. SSLClient cli(host);
  1763. #else
  1764. Client cli(host);
  1765. #endif
  1766. cli.set_follow_location(true);
  1767. auto res = cli.Get("/httpbin/relative-redirect/3");
  1768. ASSERT_TRUE(res);
  1769. EXPECT_EQ(StatusCode::OK_200, res->status);
  1770. }
  1771. TEST(TooManyRedirectTest, Redirect_Online) {
  1772. auto host = "nghttp2.org";
  1773. #ifdef CPPHTTPLIB_SSL_ENABLED
  1774. SSLClient cli(host);
  1775. #else
  1776. Client cli(host);
  1777. #endif
  1778. cli.set_follow_location(true);
  1779. auto res = cli.Get("/httpbin/redirect/21");
  1780. ASSERT_TRUE(!res);
  1781. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1782. }
  1783. #ifdef CPPHTTPLIB_SSL_ENABLED
  1784. TEST(YahooRedirectTest, Redirect_Online) {
  1785. Client cli("yahoo.com");
  1786. auto res = cli.Get("/");
  1787. ASSERT_TRUE(res);
  1788. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1789. cli.set_follow_location(true);
  1790. res = cli.Get("/");
  1791. ASSERT_TRUE(res);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1794. }
  1795. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1796. #define REDIR_HOST "httpbingo.org"
  1797. #define REDIR_PATH "/redirect-to"
  1798. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1799. SSLClient cli(REDIR_HOST);
  1800. cli.set_follow_location(true);
  1801. auto res =
  1802. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1803. ASSERT_TRUE(res);
  1804. EXPECT_EQ(StatusCode::OK_200, res->status);
  1805. }
  1806. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1807. SSLClient cli(REDIR_HOST);
  1808. cli.set_follow_location(true);
  1809. Params params;
  1810. params.emplace("url", "http://example.com");
  1811. params.emplace("status_code", "302");
  1812. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1813. ASSERT_TRUE(res);
  1814. EXPECT_EQ(StatusCode::OK_200, res->status);
  1815. }
  1816. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1817. SSLClient cli(REDIR_HOST);
  1818. cli.set_follow_location(true);
  1819. Params params;
  1820. params.emplace("url", "http://example.com");
  1821. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1822. ASSERT_TRUE(res);
  1823. EXPECT_EQ(StatusCode::OK_200, res->status);
  1824. }
  1825. TEST(UrlWithSpace, Redirect_Online) {
  1826. SSLClient cli("edge.forgecdn.net");
  1827. cli.set_follow_location(true);
  1828. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1829. ASSERT_TRUE(res);
  1830. EXPECT_EQ(StatusCode::OK_200, res->status);
  1831. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1832. }
  1833. #endif
  1834. #if !defined(_WIN32) && !defined(_WIN64)
  1835. TEST(ReceiveSignals, Signal) {
  1836. auto setupSignalHandlers = []() {
  1837. struct sigaction act;
  1838. sigemptyset(&act.sa_mask);
  1839. act.sa_flags = SA_SIGINFO;
  1840. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1841. switch (sig) {
  1842. case SIGINT:
  1843. default: break;
  1844. }
  1845. };
  1846. ::sigaction(SIGINT, &act, nullptr);
  1847. };
  1848. Server svr;
  1849. int port = 0;
  1850. auto thread = std::thread([&]() {
  1851. setupSignalHandlers();
  1852. port = svr.bind_to_any_port(HOST);
  1853. svr.listen_after_bind();
  1854. });
  1855. auto se = detail::scope_exit([&] {
  1856. svr.stop();
  1857. thread.join();
  1858. ASSERT_FALSE(svr.is_running());
  1859. });
  1860. svr.wait_until_ready();
  1861. ASSERT_TRUE(svr.is_running());
  1862. pthread_kill(thread.native_handle(), SIGINT);
  1863. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1864. ASSERT_TRUE(svr.is_running());
  1865. }
  1866. #endif
  1867. TEST(RedirectToDifferentPort, Redirect) {
  1868. Server svr1;
  1869. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1870. res.set_content("Hello World!", "text/plain");
  1871. });
  1872. int svr1_port = 0;
  1873. auto thread1 = std::thread([&]() {
  1874. svr1_port = svr1.bind_to_any_port(HOST);
  1875. svr1.listen_after_bind();
  1876. });
  1877. Server svr2;
  1878. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1879. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1880. });
  1881. int svr2_port = 0;
  1882. auto thread2 = std::thread([&]() {
  1883. svr2_port = svr2.bind_to_any_port(HOST);
  1884. svr2.listen_after_bind();
  1885. });
  1886. auto se = detail::scope_exit([&] {
  1887. svr2.stop();
  1888. thread2.join();
  1889. svr1.stop();
  1890. thread1.join();
  1891. ASSERT_FALSE(svr2.is_running());
  1892. ASSERT_FALSE(svr1.is_running());
  1893. });
  1894. svr1.wait_until_ready();
  1895. svr2.wait_until_ready();
  1896. Client cli("localhost", svr2_port);
  1897. cli.set_follow_location(true);
  1898. auto res = cli.Get("/2");
  1899. ASSERT_TRUE(res);
  1900. EXPECT_EQ(StatusCode::OK_200, res->status);
  1901. EXPECT_EQ("Hello World!", res->body);
  1902. }
  1903. TEST(RedirectFromPageWithContent, Redirect) {
  1904. Server svr;
  1905. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1906. res.set_content("___", "text/plain");
  1907. res.set_redirect("/2");
  1908. });
  1909. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1910. res.set_content("Hello World!", "text/plain");
  1911. });
  1912. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1913. auto se = detail::scope_exit([&] {
  1914. svr.stop();
  1915. th.join();
  1916. ASSERT_FALSE(svr.is_running());
  1917. });
  1918. svr.wait_until_ready();
  1919. {
  1920. Client cli("localhost", PORT);
  1921. cli.set_follow_location(true);
  1922. std::string body;
  1923. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1924. body.append(data, data_length);
  1925. return true;
  1926. });
  1927. ASSERT_TRUE(res);
  1928. EXPECT_EQ(StatusCode::OK_200, res->status);
  1929. EXPECT_EQ("Hello World!", body);
  1930. }
  1931. {
  1932. Client cli("localhost", PORT);
  1933. std::string body;
  1934. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1935. body.append(data, data_length);
  1936. return true;
  1937. });
  1938. ASSERT_TRUE(res);
  1939. EXPECT_EQ(StatusCode::Found_302, res->status);
  1940. EXPECT_EQ("___", body);
  1941. }
  1942. }
  1943. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1944. Server svr;
  1945. auto port_str = std::to_string(PORT);
  1946. auto redirect_url = "http://[::1]:" + port_str + "/2";
  1947. auto expected_host = "[::1]:" + port_str;
  1948. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1949. res.set_content("___", "text/plain");
  1950. // res.set_redirect("/2");
  1951. res.set_redirect(redirect_url);
  1952. });
  1953. svr.Get("/2", [&](const Request &req, Response &res) {
  1954. auto host_header = req.headers.find("Host");
  1955. ASSERT_TRUE(host_header != req.headers.end());
  1956. EXPECT_EQ(expected_host, host_header->second);
  1957. res.set_content("Hello World!", "text/plain");
  1958. });
  1959. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  1960. auto se = detail::scope_exit([&] {
  1961. svr.stop();
  1962. th.join();
  1963. ASSERT_FALSE(svr.is_running());
  1964. });
  1965. // When IPV6 support isn't available svr.listen("::1", PORT) never
  1966. // actually starts anything, so the condition !svr.is_running() will
  1967. // always remain true, and the loop never stops.
  1968. // This basically counts how many milliseconds have passed since the
  1969. // call to svr.listen(), and if after 5 seconds nothing started yet
  1970. // aborts the test.
  1971. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1972. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1973. ASSERT_LT(milliseconds, 5000U);
  1974. }
  1975. {
  1976. Client cli("::1", PORT);
  1977. cli.set_follow_location(true);
  1978. std::string body;
  1979. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1980. body.append(data, data_length);
  1981. return true;
  1982. });
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. EXPECT_EQ("Hello World!", body);
  1986. }
  1987. {
  1988. Client cli("::1", PORT);
  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::Found_302, res->status);
  1996. EXPECT_EQ("___", body);
  1997. }
  1998. }
  1999. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2000. Server svr;
  2001. svr.Get("/foo", [](const Request &req, Response &res) {
  2002. auto a = req.params.find("a");
  2003. if (a != req.params.end()) {
  2004. res.set_content((*a).second, "text/plain");
  2005. res.status = StatusCode::OK_200;
  2006. } else {
  2007. res.status = StatusCode::BadRequest_400;
  2008. }
  2009. });
  2010. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2011. auto se = detail::scope_exit([&] {
  2012. svr.stop();
  2013. thread.join();
  2014. ASSERT_FALSE(svr.is_running());
  2015. });
  2016. svr.wait_until_ready();
  2017. {
  2018. Client cli(HOST, PORT);
  2019. cli.set_path_encode(false);
  2020. auto res = cli.Get("/foo?a=explicitly+encoded");
  2021. ASSERT_TRUE(res);
  2022. EXPECT_EQ(StatusCode::OK_200, res->status);
  2023. // This expects it back with a space, as the `+` won't have been
  2024. // url-encoded, and server-side the params get decoded turning `+`
  2025. // into spaces.
  2026. EXPECT_EQ("explicitly encoded", res->body);
  2027. }
  2028. }
  2029. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2030. Server svr;
  2031. svr.Get("/", [](const Request &req, Response &) {
  2032. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2033. });
  2034. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2035. auto se = detail::scope_exit([&] {
  2036. svr.stop();
  2037. thread.join();
  2038. ASSERT_FALSE(svr.is_running());
  2039. });
  2040. svr.wait_until_ready();
  2041. {
  2042. Client cli(HOST, PORT);
  2043. cli.set_path_encode(false);
  2044. auto res = cli.Get("/?something=%0A");
  2045. ASSERT_TRUE(res);
  2046. EXPECT_EQ(StatusCode::OK_200, res->status);
  2047. }
  2048. }
  2049. TEST(BindServerTest, DISABLED_BindDualStack) {
  2050. Server svr;
  2051. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2052. res.set_content("Hello World!", "text/plain");
  2053. });
  2054. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2055. auto se = detail::scope_exit([&] {
  2056. svr.stop();
  2057. thread.join();
  2058. ASSERT_FALSE(svr.is_running());
  2059. });
  2060. svr.wait_until_ready();
  2061. {
  2062. Client cli("127.0.0.1", PORT);
  2063. auto res = cli.Get("/1");
  2064. ASSERT_TRUE(res);
  2065. EXPECT_EQ(StatusCode::OK_200, res->status);
  2066. EXPECT_EQ("Hello World!", res->body);
  2067. }
  2068. {
  2069. Client cli("::1", PORT);
  2070. auto res = cli.Get("/1");
  2071. ASSERT_TRUE(res);
  2072. EXPECT_EQ(StatusCode::OK_200, res->status);
  2073. EXPECT_EQ("Hello World!", res->body);
  2074. }
  2075. }
  2076. TEST(BindServerTest, BindAndListenSeparately) {
  2077. Server svr;
  2078. int port = svr.bind_to_any_port("0.0.0.0");
  2079. ASSERT_TRUE(svr.is_valid());
  2080. ASSERT_TRUE(port > 0);
  2081. svr.stop();
  2082. }
  2083. #ifdef CPPHTTPLIB_SSL_ENABLED
  2084. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2085. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2086. CLIENT_CA_CERT_DIR);
  2087. int port = svr.bind_to_any_port("0.0.0.0");
  2088. ASSERT_TRUE(svr.is_valid());
  2089. ASSERT_TRUE(port > 0);
  2090. svr.stop();
  2091. }
  2092. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2093. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2094. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2095. int port = svr.bind_to_any_port("0.0.0.0");
  2096. ASSERT_TRUE(svr.is_valid());
  2097. ASSERT_TRUE(port > 0);
  2098. svr.stop();
  2099. }
  2100. TEST(BindServerTest, UpdateCertsPem) {
  2101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2102. int port = svr.bind_to_any_port("0.0.0.0");
  2103. ASSERT_TRUE(svr.is_valid());
  2104. ASSERT_TRUE(port > 0);
  2105. // Read PEM files
  2106. std::string cert_pem, key_pem, ca_pem;
  2107. read_file(SERVER_CERT_FILE, cert_pem);
  2108. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2109. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2110. // Update server certificates using PEM API
  2111. ASSERT_TRUE(
  2112. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2113. ASSERT_TRUE(svr.is_valid());
  2114. svr.stop();
  2115. }
  2116. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2117. // Start server with client CA (enables client auth)
  2118. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2119. ASSERT_TRUE(svr.is_valid());
  2120. bool handler_called = false;
  2121. svr.Get("/test", [&](const Request &req, Response &res) {
  2122. handler_called = true;
  2123. // Verify client certificate is present
  2124. auto cert = req.peer_cert();
  2125. EXPECT_TRUE(static_cast<bool>(cert));
  2126. res.set_content("ok", "text/plain");
  2127. });
  2128. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2129. auto se = detail::scope_exit([&] {
  2130. svr.stop();
  2131. t.join();
  2132. ASSERT_FALSE(svr.is_running());
  2133. });
  2134. svr.wait_until_ready();
  2135. // Read PEM files
  2136. std::string cert_pem, key_pem, ca_pem;
  2137. read_file(SERVER_CERT_FILE, cert_pem);
  2138. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2139. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2140. // Update server certificates and client CA using PEM API while server running
  2141. ASSERT_TRUE(
  2142. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2143. // Connect with client certificate
  2144. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2145. cli.enable_server_certificate_verification(false);
  2146. cli.set_connection_timeout(30);
  2147. auto res = cli.Get("/test");
  2148. ASSERT_TRUE(res);
  2149. ASSERT_EQ(StatusCode::OK_200, res->status);
  2150. ASSERT_TRUE(handler_called);
  2151. EXPECT_EQ("ok", res->body);
  2152. }
  2153. #endif
  2154. TEST(ErrorHandlerTest, ContentLength) {
  2155. Server svr;
  2156. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2157. res.status = StatusCode::OK_200;
  2158. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2159. "text/html"); // <= Content-Length still 13
  2160. });
  2161. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2162. res.set_content("Hello World!\n", "text/plain");
  2163. res.status = 524;
  2164. });
  2165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2166. auto se = detail::scope_exit([&] {
  2167. svr.stop();
  2168. thread.join();
  2169. ASSERT_FALSE(svr.is_running());
  2170. });
  2171. svr.wait_until_ready();
  2172. {
  2173. Client cli(HOST, PORT);
  2174. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2175. ASSERT_TRUE(res);
  2176. EXPECT_EQ(StatusCode::OK_200, res->status);
  2177. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2178. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2179. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2180. }
  2181. }
  2182. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2183. TEST(ExceptionTest, WithoutExceptionHandler) {
  2184. Server svr;
  2185. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2186. throw std::runtime_error("exception...");
  2187. });
  2188. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2189. throw std::runtime_error("exception\r\n...");
  2190. });
  2191. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2192. auto se = detail::scope_exit([&] {
  2193. svr.stop();
  2194. listen_thread.join();
  2195. ASSERT_FALSE(svr.is_running());
  2196. });
  2197. svr.wait_until_ready();
  2198. Client cli("localhost", PORT);
  2199. {
  2200. auto res = cli.Get("/exception");
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2203. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2204. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2205. }
  2206. {
  2207. auto res = cli.Get("/unknown");
  2208. ASSERT_TRUE(res);
  2209. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2210. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2211. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2212. }
  2213. }
  2214. TEST(ExceptionTest, WithExceptionHandler) {
  2215. Server svr;
  2216. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2217. std::exception_ptr ep) {
  2218. EXPECT_FALSE(ep == nullptr);
  2219. try {
  2220. std::rethrow_exception(ep);
  2221. } catch (std::exception &e) {
  2222. EXPECT_EQ("abc", std::string(e.what()));
  2223. } catch (...) {}
  2224. res.status = StatusCode::InternalServerError_500;
  2225. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2226. "text/html"); // <= Content-Length still 13 at this point
  2227. });
  2228. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2229. res.set_content("Hello World!\n", "text/plain");
  2230. throw std::runtime_error("abc");
  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. for (size_t i = 0; i < 10; i++) {
  2240. Client cli(HOST, PORT);
  2241. for (size_t j = 0; j < 100; j++) {
  2242. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2243. ASSERT_TRUE(res);
  2244. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2245. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2246. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2247. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2248. }
  2249. cli.set_keep_alive(true);
  2250. for (size_t j = 0; j < 100; j++) {
  2251. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2252. ASSERT_TRUE(res);
  2253. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2254. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2255. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2256. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2257. }
  2258. }
  2259. }
  2260. TEST(ExceptionTest, AndErrorHandler) {
  2261. Server svr;
  2262. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2263. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2264. });
  2265. svr.set_exception_handler(
  2266. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2267. EXPECT_FALSE(ep == nullptr);
  2268. try {
  2269. std::rethrow_exception(ep);
  2270. } catch (std::exception &e) {
  2271. res.set_content(e.what(), "text/html");
  2272. } catch (...) {}
  2273. res.status = StatusCode::InternalServerError_500;
  2274. });
  2275. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2276. throw std::runtime_error("EXCEPTION");
  2277. });
  2278. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2279. res.set_content("ERROR", "text/html");
  2280. res.status = StatusCode::InternalServerError_500;
  2281. });
  2282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2283. auto se = detail::scope_exit([&] {
  2284. svr.stop();
  2285. thread.join();
  2286. ASSERT_FALSE(svr.is_running());
  2287. });
  2288. svr.wait_until_ready();
  2289. Client cli(HOST, PORT);
  2290. {
  2291. auto res = cli.Get("/exception");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2294. EXPECT_EQ("EXCEPTION", res->body);
  2295. }
  2296. {
  2297. auto res = cli.Get("/error");
  2298. ASSERT_TRUE(res);
  2299. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2300. EXPECT_EQ("ERROR", res->body);
  2301. }
  2302. {
  2303. auto res = cli.Get("/invalid");
  2304. ASSERT_TRUE(res);
  2305. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2306. EXPECT_EQ("NOT_FOUND", res->body);
  2307. }
  2308. }
  2309. #endif
  2310. TEST(NoContentTest, ContentLength) {
  2311. Server svr;
  2312. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2313. res.status = StatusCode::NoContent_204;
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. {
  2323. Client cli(HOST, PORT);
  2324. auto res = cli.Get("/hi");
  2325. ASSERT_TRUE(res);
  2326. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2327. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2328. }
  2329. }
  2330. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2331. #ifdef CPPHTTPLIB_SSL_ENABLED
  2332. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2333. ASSERT_TRUE(svr.is_valid());
  2334. #else
  2335. Server svr;
  2336. #endif
  2337. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2338. if (req.path == "/routing_handler") {
  2339. res.set_header("PRE_ROUTING", "on");
  2340. res.set_content("Routing Handler", "text/plain");
  2341. return httplib::Server::HandlerResponse::Handled;
  2342. }
  2343. return httplib::Server::HandlerResponse::Unhandled;
  2344. });
  2345. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2346. res.set_content("Error", "text/html");
  2347. });
  2348. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2349. if (req.path == "/routing_handler") {
  2350. res.set_header("POST_ROUTING", "on");
  2351. }
  2352. });
  2353. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2354. res.set_content("Hello World!\n", "text/plain");
  2355. });
  2356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2357. auto se = detail::scope_exit([&] {
  2358. svr.stop();
  2359. thread.join();
  2360. ASSERT_FALSE(svr.is_running());
  2361. });
  2362. svr.wait_until_ready();
  2363. {
  2364. #ifdef CPPHTTPLIB_SSL_ENABLED
  2365. SSLClient cli(HOST, PORT);
  2366. cli.enable_server_certificate_verification(false);
  2367. #else
  2368. Client cli(HOST, PORT);
  2369. #endif
  2370. auto res = cli.Get("/routing_handler");
  2371. ASSERT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::OK_200, res->status);
  2373. EXPECT_EQ("Routing Handler", res->body);
  2374. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2375. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2376. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2377. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2378. }
  2379. {
  2380. #ifdef CPPHTTPLIB_SSL_ENABLED
  2381. SSLClient cli(HOST, PORT);
  2382. cli.enable_server_certificate_verification(false);
  2383. #else
  2384. Client cli(HOST, PORT);
  2385. #endif
  2386. auto res = cli.Get("/hi");
  2387. ASSERT_TRUE(res);
  2388. EXPECT_EQ(StatusCode::OK_200, res->status);
  2389. EXPECT_EQ("Hello World!\n", res->body);
  2390. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2391. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2392. }
  2393. {
  2394. #ifdef CPPHTTPLIB_SSL_ENABLED
  2395. SSLClient cli(HOST, PORT);
  2396. cli.enable_server_certificate_verification(false);
  2397. #else
  2398. Client cli(HOST, PORT);
  2399. #endif
  2400. auto res = cli.Get("/aaa");
  2401. ASSERT_TRUE(res);
  2402. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2403. EXPECT_EQ("Error", res->body);
  2404. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2405. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2406. }
  2407. }
  2408. TEST(RequestHandlerTest, PreRequestHandler) {
  2409. auto route_path = "/user/:user";
  2410. Server svr;
  2411. svr.Get("/hi", [](const Request &, Response &res) {
  2412. res.set_content("hi", "text/plain");
  2413. });
  2414. svr.Get(route_path, [](const Request &req, Response &res) {
  2415. res.set_content(req.path_params.at("user"), "text/plain");
  2416. });
  2417. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2418. if (req.matched_route == route_path) {
  2419. auto user = req.path_params.at("user");
  2420. if (user != "john") {
  2421. res.status = StatusCode::Forbidden_403;
  2422. res.set_content("error", "text/html");
  2423. return Server::HandlerResponse::Handled;
  2424. }
  2425. }
  2426. return Server::HandlerResponse::Unhandled;
  2427. });
  2428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2429. auto se = detail::scope_exit([&] {
  2430. svr.stop();
  2431. thread.join();
  2432. ASSERT_FALSE(svr.is_running());
  2433. });
  2434. svr.wait_until_ready();
  2435. Client cli(HOST, PORT);
  2436. {
  2437. auto res = cli.Get("/hi");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(StatusCode::OK_200, res->status);
  2440. EXPECT_EQ("hi", res->body);
  2441. }
  2442. {
  2443. auto res = cli.Get("/user/john");
  2444. ASSERT_TRUE(res);
  2445. EXPECT_EQ(StatusCode::OK_200, res->status);
  2446. EXPECT_EQ("john", res->body);
  2447. }
  2448. {
  2449. auto res = cli.Get("/user/invalid-user");
  2450. ASSERT_TRUE(res);
  2451. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2452. EXPECT_EQ("error", res->body);
  2453. }
  2454. }
  2455. TEST(AnyTest, BasicOperations) {
  2456. // Default construction
  2457. httplib::any a;
  2458. EXPECT_FALSE(a.has_value());
  2459. // Value construction and any_cast (pointer form, noexcept)
  2460. httplib::any b(42);
  2461. EXPECT_TRUE(b.has_value());
  2462. auto *p = httplib::any_cast<int>(&b);
  2463. ASSERT_NE(nullptr, p);
  2464. EXPECT_EQ(42, *p);
  2465. // Type mismatch → nullptr
  2466. auto *q = httplib::any_cast<std::string>(&b);
  2467. EXPECT_EQ(nullptr, q);
  2468. // any_cast (value form) succeeds
  2469. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2470. // any_cast (value form) throws on type mismatch
  2471. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2472. // Copy
  2473. httplib::any c = b;
  2474. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2475. // Move
  2476. httplib::any d = std::move(c);
  2477. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2478. // Assignment with different type
  2479. b = std::string("hello");
  2480. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2481. // Reset
  2482. b.reset();
  2483. EXPECT_FALSE(b.has_value());
  2484. }
  2485. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2486. struct AuthCtx {
  2487. std::string user_id;
  2488. };
  2489. Server svr;
  2490. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2491. res.user_data["auth"] = AuthCtx{"alice"};
  2492. return Server::HandlerResponse::Unhandled;
  2493. });
  2494. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2495. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2496. ASSERT_NE(nullptr, ctx);
  2497. res.set_content("Hello " + ctx->user_id, "text/plain");
  2498. });
  2499. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2500. auto se = detail::scope_exit([&] {
  2501. svr.stop();
  2502. thread.join();
  2503. ASSERT_FALSE(svr.is_running());
  2504. });
  2505. svr.wait_until_ready();
  2506. Client cli(HOST, PORT);
  2507. auto res = cli.Get("/me");
  2508. ASSERT_TRUE(res);
  2509. EXPECT_EQ(StatusCode::OK_200, res->status);
  2510. EXPECT_EQ("Hello alice", res->body);
  2511. }
  2512. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2513. struct RoleCtx {
  2514. std::string role;
  2515. };
  2516. Server svr;
  2517. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2518. res.user_data["role"] = RoleCtx{"admin"};
  2519. return Server::HandlerResponse::Unhandled;
  2520. });
  2521. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2522. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2523. ASSERT_NE(nullptr, ctx);
  2524. res.set_content(ctx->role, "text/plain");
  2525. });
  2526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. Client cli(HOST, PORT);
  2534. auto res = cli.Get("/role");
  2535. ASSERT_TRUE(res);
  2536. EXPECT_EQ(StatusCode::OK_200, res->status);
  2537. EXPECT_EQ("admin", res->body);
  2538. }
  2539. TEST(InvalidFormatTest, StatusCode) {
  2540. Server svr;
  2541. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2542. res.set_content("Hello World!\n", "text/plain");
  2543. res.status = 9999; // Status should be a three-digit code...
  2544. });
  2545. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2546. auto se = detail::scope_exit([&] {
  2547. svr.stop();
  2548. thread.join();
  2549. ASSERT_FALSE(svr.is_running());
  2550. });
  2551. svr.wait_until_ready();
  2552. {
  2553. Client cli(HOST, PORT);
  2554. auto res = cli.Get("/hi");
  2555. ASSERT_FALSE(res);
  2556. }
  2557. }
  2558. TEST(URLFragmentTest, WithFragment) {
  2559. Server svr;
  2560. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2561. EXPECT_TRUE(req.target == "/hi");
  2562. });
  2563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2564. auto se = detail::scope_exit([&] {
  2565. svr.stop();
  2566. thread.join();
  2567. ASSERT_FALSE(svr.is_running());
  2568. });
  2569. svr.wait_until_ready();
  2570. {
  2571. Client cli(HOST, PORT);
  2572. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2573. EXPECT_TRUE(res);
  2574. EXPECT_EQ(StatusCode::OK_200, res->status);
  2575. res = cli.Get("/hi%23key1=val1=key2=val2");
  2576. EXPECT_TRUE(res);
  2577. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2578. }
  2579. }
  2580. TEST(HeaderWriter, SetHeaderWriter) {
  2581. Server svr;
  2582. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2583. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2584. return detail::write_headers(strm, hdrs);
  2585. });
  2586. svr.Get("/hi", [](const Request &req, Response &res) {
  2587. auto it = req.headers.find("CustomClientHeader");
  2588. EXPECT_TRUE(it != req.headers.end());
  2589. EXPECT_EQ(it->second, "CustomClientValue");
  2590. res.set_content("Hello World!\n", "text/plain");
  2591. });
  2592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2593. auto se = detail::scope_exit([&] {
  2594. svr.stop();
  2595. thread.join();
  2596. ASSERT_FALSE(svr.is_running());
  2597. });
  2598. svr.wait_until_ready();
  2599. {
  2600. Client cli(HOST, PORT);
  2601. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2602. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2603. return detail::write_headers(strm, hdrs);
  2604. });
  2605. auto res = cli.Get("/hi");
  2606. EXPECT_TRUE(res);
  2607. EXPECT_EQ(StatusCode::OK_200, res->status);
  2608. auto it = res->headers.find("CustomServerHeader");
  2609. EXPECT_TRUE(it != res->headers.end());
  2610. EXPECT_EQ(it->second, "CustomServerValue");
  2611. }
  2612. }
  2613. class ServerTest : public ::testing::Test {
  2614. protected:
  2615. ServerTest()
  2616. : cli_(HOST, PORT)
  2617. #ifdef CPPHTTPLIB_SSL_ENABLED
  2618. ,
  2619. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2620. #endif
  2621. {
  2622. #ifdef CPPHTTPLIB_SSL_ENABLED
  2623. cli_.enable_server_certificate_verification(false);
  2624. #endif
  2625. // Allow LARGE_DATA (100MB) responses
  2626. cli_.set_payload_max_length(200 * 1024 * 1024);
  2627. }
  2628. virtual void SetUp() {
  2629. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2630. svr_.set_payload_max_length(200 * 1024 * 1024);
  2631. svr_.set_mount_point("/", "./www");
  2632. svr_.set_mount_point("/mount", "./www2");
  2633. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2634. svr_.Get("/hi",
  2635. [&](const Request & /*req*/, Response &res) {
  2636. res.set_content("Hello World!", "text/plain");
  2637. })
  2638. .Get("/file_content",
  2639. [&](const Request & /*req*/, Response &res) {
  2640. res.set_file_content("./www/dir/test.html");
  2641. })
  2642. .Get("/file_content_with_content_type",
  2643. [&](const Request & /*req*/, Response &res) {
  2644. res.set_file_content("./www/file", "text/plain");
  2645. })
  2646. .Get("/invalid_file_content",
  2647. [&](const Request & /*req*/, Response &res) {
  2648. res.set_file_content("./www/dir/invalid_file_path");
  2649. })
  2650. .Get("/http_response_splitting",
  2651. [&](const Request & /*req*/, Response &res) {
  2652. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2653. EXPECT_EQ(0U, res.headers.size());
  2654. EXPECT_FALSE(res.has_header("a"));
  2655. res.set_header("a", "1\nSet-Cookie: a=1");
  2656. EXPECT_EQ(0U, res.headers.size());
  2657. EXPECT_FALSE(res.has_header("a"));
  2658. res.set_header("a", "1\rSet-Cookie: a=1");
  2659. EXPECT_EQ(0U, res.headers.size());
  2660. EXPECT_FALSE(res.has_header("a"));
  2661. res.set_header("a\r\nb", "0");
  2662. EXPECT_EQ(0U, res.headers.size());
  2663. EXPECT_FALSE(res.has_header("a"));
  2664. res.set_header("a\rb", "0");
  2665. EXPECT_EQ(0U, res.headers.size());
  2666. EXPECT_FALSE(res.has_header("a"));
  2667. res.set_header("a\nb", "0");
  2668. EXPECT_EQ(0U, res.headers.size());
  2669. EXPECT_FALSE(res.has_header("a"));
  2670. res.set_redirect("1\r\nSet-Cookie: a=1");
  2671. EXPECT_EQ(0U, res.headers.size());
  2672. EXPECT_FALSE(res.has_header("Location"));
  2673. })
  2674. .Get("/slow",
  2675. [&](const Request & /*req*/, Response &res) {
  2676. std::this_thread::sleep_for(std::chrono::seconds(2));
  2677. res.set_content("slow", "text/plain");
  2678. })
  2679. #if 0
  2680. .Post("/slowpost",
  2681. [&](const Request & /*req*/, Response &res) {
  2682. std::this_thread::sleep_for(std::chrono::seconds(2));
  2683. res.set_content("slow", "text/plain");
  2684. })
  2685. #endif
  2686. .Get("/remote_addr",
  2687. [&](const Request &req, Response &res) {
  2688. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2689. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2690. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2691. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2692. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2693. #endif
  2694. res.set_content(req.remote_addr, "text/plain");
  2695. })
  2696. .Get("/local_addr",
  2697. [&](const Request &req, Response &res) {
  2698. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2699. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2700. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2701. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2702. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2703. #endif
  2704. auto local_addr = req.local_addr;
  2705. auto local_port = std::to_string(req.local_port);
  2706. res.set_content(local_addr.append(":").append(local_port),
  2707. "text/plain");
  2708. })
  2709. .Get("/endwith%",
  2710. [&](const Request & /*req*/, Response &res) {
  2711. res.set_content("Hello World!", "text/plain");
  2712. })
  2713. .Get("/a\\+\\+b",
  2714. [&](const Request &req, Response &res) {
  2715. ASSERT_TRUE(req.has_param("a +b"));
  2716. auto val = req.get_param_value("a +b");
  2717. res.set_content(val, "text/plain");
  2718. })
  2719. .Get("/", [&](const Request & /*req*/,
  2720. Response &res) { res.set_redirect("/hi"); })
  2721. .Post("/1",
  2722. [](const Request & /*req*/, Response &res) {
  2723. res.set_redirect("/2", StatusCode::SeeOther_303);
  2724. })
  2725. .Get("/2",
  2726. [](const Request & /*req*/, Response &res) {
  2727. res.set_content("redirected.", "text/plain");
  2728. res.status = StatusCode::OK_200;
  2729. })
  2730. .Post("/person",
  2731. [&](const Request &req, Response &res) {
  2732. if (req.has_param("name") && req.has_param("note")) {
  2733. persons_[req.get_param_value("name")] =
  2734. req.get_param_value("note");
  2735. } else {
  2736. res.status = StatusCode::BadRequest_400;
  2737. }
  2738. })
  2739. .Put("/person",
  2740. [&](const Request &req, Response &res) {
  2741. if (req.has_param("name") && req.has_param("note")) {
  2742. persons_[req.get_param_value("name")] =
  2743. req.get_param_value("note");
  2744. } else {
  2745. res.status = StatusCode::BadRequest_400;
  2746. }
  2747. })
  2748. .Get("/person/(.*)",
  2749. [&](const Request &req, Response &res) {
  2750. string name = req.matches[1];
  2751. if (persons_.find(name) != persons_.end()) {
  2752. auto note = persons_[name];
  2753. res.set_content(note, "text/plain");
  2754. } else {
  2755. res.status = StatusCode::NotFound_404;
  2756. }
  2757. })
  2758. .Delete("/person",
  2759. [&](const Request &req, Response &res) {
  2760. if (req.has_param("name")) {
  2761. string name = req.get_param_value("name");
  2762. if (persons_.find(name) != persons_.end()) {
  2763. persons_.erase(name);
  2764. res.set_content("DELETED", "text/plain");
  2765. } else {
  2766. res.status = StatusCode::NotFound_404;
  2767. }
  2768. } else {
  2769. res.status = StatusCode::BadRequest_400;
  2770. }
  2771. })
  2772. .Post("/x-www-form-urlencoded-json",
  2773. [&](const Request &req, Response &res) {
  2774. auto json = req.get_param_value("json");
  2775. ASSERT_EQ(JSON_DATA, json);
  2776. res.set_content(json, "appliation/json");
  2777. res.status = StatusCode::OK_200;
  2778. })
  2779. .Get("/streamed-chunked",
  2780. [&](const Request & /*req*/, Response &res) {
  2781. res.set_chunked_content_provider(
  2782. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2783. sink.os << "123";
  2784. sink.os << "456";
  2785. sink.os << "789";
  2786. sink.done();
  2787. return true;
  2788. });
  2789. })
  2790. .Get("/streamed-chunked-with-prohibited-trailer",
  2791. [&](const Request & /*req*/, Response &res) {
  2792. auto i = new int(0);
  2793. // Declare both a prohibited trailer (Content-Length) and an
  2794. // allowed one
  2795. res.set_header("Trailer", "Content-Length, X-Allowed");
  2796. res.set_chunked_content_provider(
  2797. "text/plain",
  2798. [i](size_t /*offset*/, DataSink &sink) {
  2799. switch (*i) {
  2800. case 0: sink.os << "123"; break;
  2801. case 1: sink.os << "456"; break;
  2802. case 2: sink.os << "789"; break;
  2803. case 3: {
  2804. sink.done_with_trailer(
  2805. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2806. } break;
  2807. }
  2808. (*i)++;
  2809. return true;
  2810. },
  2811. [i](bool success) {
  2812. EXPECT_TRUE(success);
  2813. delete i;
  2814. });
  2815. })
  2816. .Get("/streamed-chunked2",
  2817. [&](const Request & /*req*/, Response &res) {
  2818. auto i = new int(0);
  2819. res.set_chunked_content_provider(
  2820. "text/plain",
  2821. [i](size_t /*offset*/, DataSink &sink) {
  2822. switch (*i) {
  2823. case 0: sink.os << "123"; break;
  2824. case 1: sink.os << "456"; break;
  2825. case 2: sink.os << "789"; break;
  2826. case 3: sink.done(); break;
  2827. }
  2828. (*i)++;
  2829. return true;
  2830. },
  2831. [i](bool success) {
  2832. EXPECT_TRUE(success);
  2833. delete i;
  2834. });
  2835. })
  2836. .Get("/streamed-chunked-with-trailer",
  2837. [&](const Request & /*req*/, Response &res) {
  2838. auto i = new int(0);
  2839. res.set_header("Trailer", "Dummy1, Dummy2");
  2840. res.set_chunked_content_provider(
  2841. "text/plain",
  2842. [i](size_t /*offset*/, DataSink &sink) {
  2843. switch (*i) {
  2844. case 0: sink.os << "123"; break;
  2845. case 1: sink.os << "456"; break;
  2846. case 2: sink.os << "789"; break;
  2847. case 3: {
  2848. sink.done_with_trailer(
  2849. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2850. } break;
  2851. }
  2852. (*i)++;
  2853. return true;
  2854. },
  2855. [i](bool success) {
  2856. EXPECT_TRUE(success);
  2857. delete i;
  2858. });
  2859. })
  2860. .Get("/streamed",
  2861. [&](const Request & /*req*/, Response &res) {
  2862. res.set_content_provider(
  2863. 6, "text/plain",
  2864. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2865. sink.os << (offset < 3 ? "a" : "b");
  2866. return true;
  2867. });
  2868. })
  2869. .Get("/streamed-with-range",
  2870. [&](const Request &req, Response &res) {
  2871. auto data = new std::string("abcdefg");
  2872. res.set_content_provider(
  2873. data->size(), "text/plain",
  2874. [data](size_t offset, size_t length, DataSink &sink) {
  2875. size_t DATA_CHUNK_SIZE = 4;
  2876. const auto &d = *data;
  2877. auto out_len =
  2878. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2879. auto ret =
  2880. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2881. EXPECT_TRUE(ret);
  2882. return true;
  2883. },
  2884. [data, &req](bool success) {
  2885. EXPECT_EQ(success, !req.has_param("error"));
  2886. delete data;
  2887. });
  2888. })
  2889. .Get("/streamed-cancel",
  2890. [&](const Request & /*req*/, Response &res) {
  2891. res.set_content_provider(
  2892. size_t(-1), "text/plain",
  2893. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2894. sink.os << "data_chunk";
  2895. return true;
  2896. });
  2897. })
  2898. .Get("/regex-with-delimiter",
  2899. [&](const Request &req, Response & /*res*/) {
  2900. ASSERT_TRUE(req.has_param("key"));
  2901. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2902. })
  2903. .Get("/with-range",
  2904. [&](const Request & /*req*/, Response &res) {
  2905. res.set_content("abcdefg", "text/plain");
  2906. })
  2907. .Get("/test-start-time",
  2908. [&](const Request &req, Response & /*res*/) {
  2909. EXPECT_NE(req.start_time_,
  2910. std::chrono::steady_clock::time_point::min());
  2911. })
  2912. .Get("/with-range-customized-response",
  2913. [&](const Request & /*req*/, Response &res) {
  2914. res.status = StatusCode::BadRequest_400;
  2915. res.set_content(JSON_DATA, "application/json");
  2916. })
  2917. .Post("/chunked",
  2918. [&](const Request &req, Response & /*res*/) {
  2919. EXPECT_EQ(req.body, "dechunked post body");
  2920. })
  2921. .Post("/large-chunked",
  2922. [&](const Request &req, Response & /*res*/) {
  2923. std::string expected(6 * 30 * 1024u, 'a');
  2924. EXPECT_EQ(req.body, expected);
  2925. })
  2926. .Post("/multipart",
  2927. [&](const Request &req, Response & /*res*/) {
  2928. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2929. req.form.get_field_count("text2") +
  2930. req.form.get_field_count("file3") +
  2931. req.form.get_field_count("file4"));
  2932. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2933. req.form.get_file_count("file2"));
  2934. ASSERT_TRUE(!req.form.has_file("???"));
  2935. ASSERT_TRUE(!req.form.has_field("???"));
  2936. ASSERT_TRUE(req.body.empty());
  2937. {
  2938. const auto &text = req.form.get_field("text1");
  2939. EXPECT_EQ("text default", text);
  2940. }
  2941. {
  2942. const auto &text = req.form.get_field("text2");
  2943. EXPECT_EQ("aωb", text);
  2944. }
  2945. {
  2946. const auto &file = req.form.get_file("file1");
  2947. EXPECT_EQ("hello.txt", file.filename);
  2948. EXPECT_EQ("text/plain", file.content_type);
  2949. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2950. }
  2951. {
  2952. const auto &file = req.form.get_file("file2");
  2953. EXPECT_EQ("world.json", file.filename);
  2954. EXPECT_EQ("application/json", file.content_type);
  2955. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2956. }
  2957. {
  2958. const auto &text = req.form.get_field("file3");
  2959. EXPECT_EQ(0u, text.size());
  2960. }
  2961. {
  2962. const auto &text = req.form.get_field("file4");
  2963. EXPECT_EQ(0u, text.size());
  2964. }
  2965. })
  2966. .Post("/multipart/multi_file_values",
  2967. [&](const Request &req, Response & /*res*/) {
  2968. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2969. req.form.get_field_count("multi_text1"));
  2970. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2971. ASSERT_TRUE(!req.form.has_file("???"));
  2972. ASSERT_TRUE(!req.form.has_field("???"));
  2973. ASSERT_TRUE(req.body.empty());
  2974. {
  2975. const auto &text = req.form.get_field("text");
  2976. EXPECT_EQ("default text", text);
  2977. }
  2978. {
  2979. const auto &text1_values = req.form.get_fields("multi_text1");
  2980. EXPECT_EQ(2u, text1_values.size());
  2981. EXPECT_EQ("aaaaa", text1_values[0]);
  2982. EXPECT_EQ("bbbbb", text1_values[1]);
  2983. }
  2984. {
  2985. const auto &file1_values = req.form.get_files("multi_file1");
  2986. EXPECT_EQ(2u, file1_values.size());
  2987. auto file1 = file1_values[0];
  2988. EXPECT_EQ(file1.filename, "hello.txt");
  2989. EXPECT_EQ(file1.content_type, "text/plain");
  2990. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2991. auto file2 = file1_values[1];
  2992. EXPECT_EQ(file2.filename, "world.json");
  2993. EXPECT_EQ(file2.content_type, "application/json");
  2994. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2995. }
  2996. })
  2997. .Post("/empty",
  2998. [&](const Request &req, Response &res) {
  2999. EXPECT_EQ(req.body, "");
  3000. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3001. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3002. res.set_content("empty", "text/plain");
  3003. })
  3004. .Post("/empty-no-content-type",
  3005. [&](const Request &req, Response &res) {
  3006. EXPECT_EQ(req.body, "");
  3007. EXPECT_FALSE(req.has_header("Content-Type"));
  3008. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3009. res.set_content("empty-no-content-type", "text/plain");
  3010. })
  3011. .Post("/path-only",
  3012. [&](const Request &req, Response &res) {
  3013. EXPECT_EQ(req.body, "");
  3014. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3015. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3016. res.set_content("path-only", "text/plain");
  3017. })
  3018. .Post("/path-headers-only",
  3019. [&](const Request &req, Response &res) {
  3020. EXPECT_EQ(req.body, "");
  3021. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3022. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3023. EXPECT_EQ("world", req.get_header_value("hello"));
  3024. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3025. res.set_content("path-headers-only", "text/plain");
  3026. })
  3027. .Post("/post-large",
  3028. [&](const Request &req, Response &res) {
  3029. EXPECT_EQ(req.body, LARGE_DATA);
  3030. res.set_content(req.body, "text/plain");
  3031. })
  3032. .Post("/post-loopback",
  3033. [&](const Request &, Response &res,
  3034. ContentReader const &content_reader) {
  3035. std::string body;
  3036. content_reader([&](const char *data, size_t data_length) {
  3037. body.append(data, data_length);
  3038. return true;
  3039. });
  3040. res.set_content(body, "text/plain");
  3041. })
  3042. .Put("/put-loopback",
  3043. [&](const Request &, Response &res,
  3044. ContentReader const &content_reader) {
  3045. std::string body;
  3046. content_reader([&](const char *data, size_t data_length) {
  3047. body.append(data, data_length);
  3048. return true;
  3049. });
  3050. res.set_content(body, "text/plain");
  3051. })
  3052. .Patch("/patch-loopback",
  3053. [&](const Request &, Response &res,
  3054. ContentReader const &content_reader) {
  3055. std::string body;
  3056. content_reader([&](const char *data, size_t data_length) {
  3057. body.append(data, data_length);
  3058. return true;
  3059. });
  3060. res.set_content(body, "text/plain");
  3061. })
  3062. .Put("/empty-no-content-type",
  3063. [&](const Request &req, Response &res) {
  3064. EXPECT_EQ(req.body, "");
  3065. EXPECT_FALSE(req.has_header("Content-Type"));
  3066. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3067. res.set_content("empty-no-content-type", "text/plain");
  3068. })
  3069. .Put("/put",
  3070. [&](const Request &req, Response &res) {
  3071. EXPECT_EQ(req.body, "PUT");
  3072. res.set_content(req.body, "text/plain");
  3073. })
  3074. .Put("/put-large",
  3075. [&](const Request &req, Response &res) {
  3076. EXPECT_EQ(req.body, LARGE_DATA);
  3077. res.set_content(req.body, "text/plain");
  3078. })
  3079. .Patch("/patch",
  3080. [&](const Request &req, Response &res) {
  3081. EXPECT_EQ(req.body, "PATCH");
  3082. res.set_content(req.body, "text/plain");
  3083. })
  3084. .Delete("/delete",
  3085. [&](const Request & /*req*/, Response &res) {
  3086. res.set_content("DELETE", "text/plain");
  3087. })
  3088. .Delete("/delete-body",
  3089. [&](const Request &req, Response &res) {
  3090. EXPECT_EQ(req.body, "content");
  3091. res.set_content(req.body, "text/plain");
  3092. })
  3093. .Options(R"(\*)",
  3094. [&](const Request & /*req*/, Response &res) {
  3095. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3096. })
  3097. .Get("/request-target",
  3098. [&](const Request &req, Response & /*res*/) {
  3099. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3100. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3101. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3102. })
  3103. .Get("/long-query-value",
  3104. [&](const Request &req, Response & /*res*/) {
  3105. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3106. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3107. })
  3108. .Get("/too-long-query-value",
  3109. [&](const Request &req, Response & /*res*/) {
  3110. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3111. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3112. })
  3113. .Get("/array-param",
  3114. [&](const Request &req, Response & /*res*/) {
  3115. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3116. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3117. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3118. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3119. })
  3120. .Post("/validate-no-multiple-headers",
  3121. [&](const Request &req, Response & /*res*/) {
  3122. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3123. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3124. })
  3125. .Post("/content_receiver",
  3126. [&](const Request &req, Response &res,
  3127. const ContentReader &content_reader) {
  3128. if (req.is_multipart_form_data()) {
  3129. std::vector<FormData> items;
  3130. content_reader(
  3131. [&](const FormData &file) {
  3132. items.push_back(file);
  3133. return true;
  3134. },
  3135. [&](const char *data, size_t data_length) {
  3136. items.back().content.append(data, data_length);
  3137. return true;
  3138. });
  3139. EXPECT_EQ(5u, items.size());
  3140. {
  3141. const auto &file = get_file_value(items, "text1");
  3142. EXPECT_TRUE(file.filename.empty());
  3143. EXPECT_EQ("text default", file.content);
  3144. }
  3145. {
  3146. const auto &file = get_file_value(items, "text2");
  3147. EXPECT_TRUE(file.filename.empty());
  3148. EXPECT_EQ("aωb", file.content);
  3149. }
  3150. {
  3151. const auto &file = get_file_value(items, "file1");
  3152. EXPECT_EQ("hello.txt", file.filename);
  3153. EXPECT_EQ("text/plain", file.content_type);
  3154. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3155. }
  3156. {
  3157. const auto &file = get_file_value(items, "file2");
  3158. EXPECT_EQ("world.json", file.filename);
  3159. EXPECT_EQ("application/json", file.content_type);
  3160. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3161. }
  3162. {
  3163. const auto &file = get_file_value(items, "file3");
  3164. EXPECT_TRUE(file.filename.empty());
  3165. EXPECT_EQ("application/octet-stream", file.content_type);
  3166. EXPECT_EQ(0u, file.content.size());
  3167. }
  3168. } else {
  3169. std::string body;
  3170. content_reader([&](const char *data, size_t data_length) {
  3171. EXPECT_EQ(7U, data_length);
  3172. body.append(data, data_length);
  3173. return true;
  3174. });
  3175. EXPECT_EQ(body, "content");
  3176. res.set_content(body, "text/plain");
  3177. }
  3178. })
  3179. .Put("/content_receiver",
  3180. [&](const Request & /*req*/, Response &res,
  3181. const ContentReader &content_reader) {
  3182. std::string body;
  3183. content_reader([&](const char *data, size_t data_length) {
  3184. body.append(data, data_length);
  3185. return true;
  3186. });
  3187. EXPECT_EQ(body, "content");
  3188. res.set_content(body, "text/plain");
  3189. })
  3190. .Patch("/content_receiver",
  3191. [&](const Request & /*req*/, Response &res,
  3192. const ContentReader &content_reader) {
  3193. std::string body;
  3194. content_reader([&](const char *data, size_t data_length) {
  3195. body.append(data, data_length);
  3196. return true;
  3197. });
  3198. EXPECT_EQ(body, "content");
  3199. res.set_content(body, "text/plain");
  3200. })
  3201. .Post("/query-string-and-body",
  3202. [&](const Request &req, Response & /*res*/) {
  3203. ASSERT_TRUE(req.has_param("key"));
  3204. EXPECT_EQ(req.get_param_value("key"), "value");
  3205. EXPECT_EQ(req.body, "content");
  3206. })
  3207. .Get("/last-request",
  3208. [&](const Request &req, Response & /*res*/) {
  3209. EXPECT_EQ("close", req.get_header_value("Connection"));
  3210. })
  3211. .Get(R"(/redirect/(\d+))",
  3212. [&](const Request &req, Response &res) {
  3213. auto num = std::stoi(req.matches[1]) + 1;
  3214. std::string url = "/redirect/" + std::to_string(num);
  3215. res.set_redirect(url);
  3216. })
  3217. .Post("/binary",
  3218. [&](const Request &req, Response &res) {
  3219. EXPECT_EQ(4U, req.body.size());
  3220. EXPECT_EQ("application/octet-stream",
  3221. req.get_header_value("Content-Type"));
  3222. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3223. res.set_content(req.body, "application/octet-stream");
  3224. })
  3225. .Put("/binary",
  3226. [&](const Request &req, Response &res) {
  3227. EXPECT_EQ(4U, req.body.size());
  3228. EXPECT_EQ("application/octet-stream",
  3229. req.get_header_value("Content-Type"));
  3230. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3231. res.set_content(req.body, "application/octet-stream");
  3232. })
  3233. .Patch("/binary",
  3234. [&](const Request &req, Response &res) {
  3235. EXPECT_EQ(4U, req.body.size());
  3236. EXPECT_EQ("application/octet-stream",
  3237. req.get_header_value("Content-Type"));
  3238. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3239. res.set_content(req.body, "application/octet-stream");
  3240. })
  3241. .Delete("/binary",
  3242. [&](const Request &req, Response &res) {
  3243. EXPECT_EQ(4U, req.body.size());
  3244. EXPECT_EQ("application/octet-stream",
  3245. req.get_header_value("Content-Type"));
  3246. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3247. res.set_content(req.body, "application/octet-stream");
  3248. })
  3249. .Get("/issue1772",
  3250. [&](const Request & /*req*/, Response &res) {
  3251. res.status = 401;
  3252. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3253. })
  3254. .Delete("/issue609",
  3255. [](const httplib::Request &, httplib::Response &res,
  3256. const httplib::ContentReader &) {
  3257. res.set_content("ok", "text/plain");
  3258. })
  3259. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3260. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3261. .Get("/compress",
  3262. [&](const Request & /*req*/, Response &res) {
  3263. res.set_content(
  3264. "12345678901234567890123456789012345678901234567890123456789"
  3265. "01234567890123456789012345678901234567890",
  3266. "text/plain");
  3267. })
  3268. .Get("/nocompress",
  3269. [&](const Request & /*req*/, Response &res) {
  3270. res.set_content(
  3271. "12345678901234567890123456789012345678901234567890123456789"
  3272. "01234567890123456789012345678901234567890",
  3273. "application/octet-stream");
  3274. })
  3275. .Post("/compress-multipart",
  3276. [&](const Request &req, Response & /*res*/) {
  3277. EXPECT_EQ(2u, req.form.fields.size());
  3278. ASSERT_TRUE(!req.form.has_field("???"));
  3279. {
  3280. const auto &text = req.form.get_field("key1");
  3281. EXPECT_EQ("test", text);
  3282. }
  3283. {
  3284. const auto &text = req.form.get_field("key2");
  3285. EXPECT_EQ("--abcdefg123", text);
  3286. }
  3287. })
  3288. #endif
  3289. ;
  3290. persons_["john"] = "programmer";
  3291. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3292. svr_.wait_until_ready();
  3293. }
  3294. virtual void TearDown() {
  3295. svr_.stop();
  3296. if (!request_threads_.empty()) {
  3297. std::this_thread::sleep_for(std::chrono::seconds(1));
  3298. for (auto &t : request_threads_) {
  3299. t.join();
  3300. }
  3301. }
  3302. t_.join();
  3303. }
  3304. map<string, string> persons_;
  3305. #ifdef CPPHTTPLIB_SSL_ENABLED
  3306. SSLClient cli_;
  3307. SSLServer svr_;
  3308. #else
  3309. Client cli_;
  3310. Server svr_;
  3311. #endif
  3312. thread t_;
  3313. std::vector<thread> request_threads_;
  3314. };
  3315. TEST_F(ServerTest, GetMethod200) {
  3316. auto res = cli_.Get("/hi");
  3317. ASSERT_TRUE(res);
  3318. EXPECT_EQ("HTTP/1.1", res->version);
  3319. EXPECT_EQ(StatusCode::OK_200, res->status);
  3320. EXPECT_EQ("OK", res->reason);
  3321. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3322. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3323. EXPECT_EQ("Hello World!", res->body);
  3324. }
  3325. TEST_F(ServerTest, GetEmptyFile) {
  3326. auto res = cli_.Get("/empty_file");
  3327. ASSERT_TRUE(res);
  3328. EXPECT_EQ(StatusCode::OK_200, res->status);
  3329. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3330. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3331. EXPECT_EQ("", res->body);
  3332. }
  3333. TEST_F(ServerTest, GetFileContent) {
  3334. auto res = cli_.Get("/file_content");
  3335. ASSERT_TRUE(res);
  3336. EXPECT_EQ(StatusCode::OK_200, res->status);
  3337. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3338. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3339. EXPECT_EQ("test.html", res->body);
  3340. }
  3341. TEST_F(ServerTest, GetFileContentWithRange) {
  3342. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3343. ASSERT_TRUE(res);
  3344. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3345. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3346. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3347. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3348. EXPECT_EQ("est", res->body);
  3349. }
  3350. TEST_F(ServerTest, GetFileContentWithContentType) {
  3351. auto res = cli_.Get("/file_content_with_content_type");
  3352. ASSERT_TRUE(res);
  3353. EXPECT_EQ(StatusCode::OK_200, res->status);
  3354. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3355. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3356. EXPECT_EQ("file\n", res->body);
  3357. }
  3358. TEST_F(ServerTest, GetInvalidFileContent) {
  3359. auto res = cli_.Get("/invalid_file_content");
  3360. ASSERT_TRUE(res);
  3361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3362. }
  3363. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3364. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3365. ASSERT_TRUE(res);
  3366. EXPECT_EQ("HTTP/1.1", res->version);
  3367. EXPECT_EQ(StatusCode::OK_200, res->status);
  3368. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3369. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3370. EXPECT_EQ("Hello World!", res->body);
  3371. }
  3372. TEST_F(ServerTest, GetMethod302) {
  3373. auto res = cli_.Get("/");
  3374. ASSERT_TRUE(res);
  3375. EXPECT_EQ(StatusCode::Found_302, res->status);
  3376. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3377. }
  3378. TEST_F(ServerTest, GetMethod302Redirect) {
  3379. cli_.set_follow_location(true);
  3380. auto res = cli_.Get("/");
  3381. ASSERT_TRUE(res);
  3382. EXPECT_EQ(StatusCode::OK_200, res->status);
  3383. EXPECT_EQ("Hello World!", res->body);
  3384. EXPECT_EQ("/hi", res->location);
  3385. }
  3386. TEST_F(ServerTest, GetMethod404) {
  3387. auto res = cli_.Get("/invalid");
  3388. ASSERT_TRUE(res);
  3389. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3390. }
  3391. TEST_F(ServerTest, HeadMethod200) {
  3392. auto res = cli_.Head("/hi");
  3393. ASSERT_TRUE(res);
  3394. EXPECT_EQ(StatusCode::OK_200, res->status);
  3395. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3396. EXPECT_TRUE(res->body.empty());
  3397. }
  3398. TEST_F(ServerTest, HeadMethod200Static) {
  3399. auto res = cli_.Head("/mount/dir/index.html");
  3400. ASSERT_TRUE(res);
  3401. EXPECT_EQ(StatusCode::OK_200, res->status);
  3402. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3403. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3404. EXPECT_TRUE(res->body.empty());
  3405. }
  3406. TEST_F(ServerTest, HeadMethod404) {
  3407. auto res = cli_.Head("/invalid");
  3408. ASSERT_TRUE(res);
  3409. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3410. EXPECT_TRUE(res->body.empty());
  3411. }
  3412. TEST_F(ServerTest, GetMethodPersonJohn) {
  3413. auto res = cli_.Get("/person/john");
  3414. ASSERT_TRUE(res);
  3415. EXPECT_EQ(StatusCode::OK_200, res->status);
  3416. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3417. EXPECT_EQ("programmer", res->body);
  3418. }
  3419. TEST_F(ServerTest, PostMethod1) {
  3420. auto res = cli_.Get("/person/john1");
  3421. ASSERT_TRUE(res);
  3422. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3423. res = cli_.Post("/person", "name=john1&note=coder",
  3424. "application/x-www-form-urlencoded");
  3425. ASSERT_TRUE(res);
  3426. ASSERT_EQ(StatusCode::OK_200, res->status);
  3427. res = cli_.Get("/person/john1");
  3428. ASSERT_TRUE(res);
  3429. ASSERT_EQ(StatusCode::OK_200, res->status);
  3430. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3431. ASSERT_EQ("coder", res->body);
  3432. }
  3433. TEST_F(ServerTest, PostMethod2) {
  3434. auto res = cli_.Get("/person/john2");
  3435. ASSERT_TRUE(res);
  3436. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3437. Params params;
  3438. params.emplace("name", "john2");
  3439. params.emplace("note", "coder");
  3440. res = cli_.Post("/person", params);
  3441. ASSERT_TRUE(res);
  3442. ASSERT_EQ(StatusCode::OK_200, res->status);
  3443. res = cli_.Get("/person/john2");
  3444. ASSERT_TRUE(res);
  3445. ASSERT_EQ(StatusCode::OK_200, res->status);
  3446. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3447. ASSERT_EQ("coder", res->body);
  3448. }
  3449. TEST_F(ServerTest, PutMethod3) {
  3450. auto res = cli_.Get("/person/john3");
  3451. ASSERT_TRUE(res);
  3452. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3453. Params params;
  3454. params.emplace("name", "john3");
  3455. params.emplace("note", "coder");
  3456. res = cli_.Put("/person", params);
  3457. ASSERT_TRUE(res);
  3458. ASSERT_EQ(StatusCode::OK_200, res->status);
  3459. res = cli_.Get("/person/john3");
  3460. ASSERT_TRUE(res);
  3461. ASSERT_EQ(StatusCode::OK_200, res->status);
  3462. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3463. ASSERT_EQ("coder", res->body);
  3464. }
  3465. TEST_F(ServerTest, DeleteMethod1) {
  3466. auto res = cli_.Get("/person/john4");
  3467. ASSERT_TRUE(res);
  3468. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3469. Params params;
  3470. params.emplace("name", "john4");
  3471. params.emplace("note", "coder");
  3472. res = cli_.Post("/person", params);
  3473. ASSERT_TRUE(res);
  3474. ASSERT_EQ(StatusCode::OK_200, res->status);
  3475. res = cli_.Get("/person/john4");
  3476. ASSERT_TRUE(res);
  3477. ASSERT_EQ(StatusCode::OK_200, res->status);
  3478. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3479. ASSERT_EQ("coder", res->body);
  3480. Params delete_params;
  3481. delete_params.emplace("name", "john4");
  3482. res = cli_.Delete("/person", delete_params);
  3483. ASSERT_TRUE(res);
  3484. ASSERT_EQ(StatusCode::OK_200, res->status);
  3485. ASSERT_EQ("DELETED", res->body);
  3486. res = cli_.Get("/person/john4");
  3487. ASSERT_TRUE(res);
  3488. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3489. }
  3490. TEST_F(ServerTest, DeleteMethod2) {
  3491. auto res = cli_.Get("/person/john5");
  3492. ASSERT_TRUE(res);
  3493. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3494. Params params;
  3495. params.emplace("name", "john5");
  3496. params.emplace("note", "developer");
  3497. res = cli_.Post("/person", params);
  3498. ASSERT_TRUE(res);
  3499. ASSERT_EQ(StatusCode::OK_200, res->status);
  3500. res = cli_.Get("/person/john5");
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3504. ASSERT_EQ("developer", res->body);
  3505. Params delete_params;
  3506. delete_params.emplace("name", "john5");
  3507. Headers headers;
  3508. headers.emplace("Custom-Header", "test-value");
  3509. res = cli_.Delete("/person", headers, delete_params);
  3510. ASSERT_TRUE(res);
  3511. ASSERT_EQ(StatusCode::OK_200, res->status);
  3512. ASSERT_EQ("DELETED", res->body);
  3513. res = cli_.Get("/person/john5");
  3514. ASSERT_TRUE(res);
  3515. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3516. }
  3517. TEST_F(ServerTest, DeleteMethod3) {
  3518. auto res = cli_.Get("/person/john6");
  3519. ASSERT_TRUE(res);
  3520. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3521. Params params;
  3522. params.emplace("name", "john6");
  3523. params.emplace("note", "tester");
  3524. res = cli_.Post("/person", params);
  3525. ASSERT_TRUE(res);
  3526. ASSERT_EQ(StatusCode::OK_200, res->status);
  3527. res = cli_.Get("/person/john6");
  3528. ASSERT_TRUE(res);
  3529. ASSERT_EQ(StatusCode::OK_200, res->status);
  3530. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3531. ASSERT_EQ("tester", res->body);
  3532. Params delete_params;
  3533. delete_params.emplace("name", "john6");
  3534. Headers headers;
  3535. headers.emplace("Custom-Header", "test-value");
  3536. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3537. ASSERT_TRUE(res);
  3538. ASSERT_EQ(StatusCode::OK_200, res->status);
  3539. ASSERT_EQ("DELETED", res->body);
  3540. res = cli_.Get("/person/john6");
  3541. ASSERT_TRUE(res);
  3542. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3543. }
  3544. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3545. Params params;
  3546. params.emplace("json", JSON_DATA);
  3547. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3548. ASSERT_TRUE(res);
  3549. ASSERT_EQ(StatusCode::OK_200, res->status);
  3550. ASSERT_EQ(JSON_DATA, res->body);
  3551. }
  3552. TEST_F(ServerTest, PostEmptyContent) {
  3553. auto res = cli_.Post("/empty", "", "text/plain");
  3554. ASSERT_TRUE(res);
  3555. ASSERT_EQ(StatusCode::OK_200, res->status);
  3556. ASSERT_EQ("empty", res->body);
  3557. }
  3558. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3559. auto res = cli_.Post("/empty-no-content-type");
  3560. ASSERT_TRUE(res);
  3561. ASSERT_EQ(StatusCode::OK_200, res->status);
  3562. ASSERT_EQ("empty-no-content-type", res->body);
  3563. }
  3564. TEST_F(ServerTest, PostPathOnly) {
  3565. auto res = cli_.Post("/path-only");
  3566. ASSERT_TRUE(res);
  3567. ASSERT_EQ(StatusCode::OK_200, res->status);
  3568. ASSERT_EQ("path-only", res->body);
  3569. }
  3570. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3571. auto res = cli_.Post("/path-headers-only",
  3572. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3573. ASSERT_TRUE(res);
  3574. ASSERT_EQ(StatusCode::OK_200, res->status);
  3575. ASSERT_EQ("path-headers-only", res->body);
  3576. }
  3577. TEST_F(ServerTest, PostLarge) {
  3578. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3579. ASSERT_TRUE(res);
  3580. ASSERT_EQ(StatusCode::OK_200, res->status);
  3581. EXPECT_EQ(LARGE_DATA, res->body);
  3582. }
  3583. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3584. auto res = cli_.Put("/empty-no-content-type");
  3585. ASSERT_TRUE(res);
  3586. ASSERT_EQ(StatusCode::OK_200, res->status);
  3587. ASSERT_EQ("empty-no-content-type", res->body);
  3588. }
  3589. TEST_F(ServerTest, GetMethodDir) {
  3590. auto res = cli_.Get("/dir/");
  3591. ASSERT_TRUE(res);
  3592. EXPECT_EQ(StatusCode::OK_200, res->status);
  3593. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3594. auto body = R"(<html>
  3595. <head>
  3596. </head>
  3597. <body>
  3598. <a href="/dir/test.html">Test</a>
  3599. <a href="/hi">hi</a>
  3600. </body>
  3601. </html>
  3602. )";
  3603. EXPECT_EQ(body, res->body);
  3604. }
  3605. TEST_F(ServerTest, GetMethodDirTest) {
  3606. auto res = cli_.Get("/dir/test.html");
  3607. ASSERT_TRUE(res);
  3608. EXPECT_EQ(StatusCode::OK_200, res->status);
  3609. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3610. EXPECT_EQ("test.html", res->body);
  3611. }
  3612. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3613. auto res = cli_.Get("/dir/../dir/test.html");
  3614. ASSERT_TRUE(res);
  3615. EXPECT_EQ(StatusCode::OK_200, res->status);
  3616. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3617. EXPECT_EQ("test.html", res->body);
  3618. }
  3619. TEST_F(ServerTest, GetMethodInvalidPath) {
  3620. auto res = cli_.Get("/dir/../test.html");
  3621. ASSERT_TRUE(res);
  3622. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3623. }
  3624. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3625. auto res = cli_.Get("/../www/dir/test.html");
  3626. ASSERT_TRUE(res);
  3627. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3628. }
  3629. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3630. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3631. ASSERT_TRUE(res);
  3632. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3633. }
  3634. TEST_F(ServerTest, GetMethodDirMountTest) {
  3635. auto res = cli_.Get("/mount/dir/test.html");
  3636. ASSERT_TRUE(res);
  3637. EXPECT_EQ(StatusCode::OK_200, res->status);
  3638. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3639. EXPECT_EQ("test.html", res->body);
  3640. }
  3641. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3642. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3643. ASSERT_TRUE(res);
  3644. EXPECT_EQ(StatusCode::OK_200, res->status);
  3645. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3646. EXPECT_EQ("test.html", res->body);
  3647. }
  3648. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3649. auto res = cli_.Get("/mount/dir/../test.html");
  3650. ASSERT_TRUE(res);
  3651. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3652. }
  3653. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3654. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3655. ASSERT_TRUE(res);
  3656. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3657. }
  3658. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3659. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3660. ASSERT_TRUE(res);
  3661. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3662. }
  3663. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3664. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3665. ASSERT_TRUE(res);
  3666. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3667. }
  3668. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3669. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3670. ASSERT_TRUE(res);
  3671. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3672. }
  3673. TEST_F(ServerTest, PostMethod303) {
  3674. auto res = cli_.Post("/1", "body", "text/plain");
  3675. ASSERT_TRUE(res);
  3676. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3677. EXPECT_EQ("/2", res->get_header_value("Location"));
  3678. }
  3679. TEST_F(ServerTest, PostMethod303Redirect) {
  3680. cli_.set_follow_location(true);
  3681. auto res = cli_.Post("/1", "body", "text/plain");
  3682. ASSERT_TRUE(res);
  3683. EXPECT_EQ(StatusCode::OK_200, res->status);
  3684. EXPECT_EQ("redirected.", res->body);
  3685. EXPECT_EQ("/2", res->location);
  3686. }
  3687. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3688. auto res = cli_.Get("/dir/test.abcde");
  3689. ASSERT_TRUE(res);
  3690. EXPECT_EQ(StatusCode::OK_200, res->status);
  3691. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3692. EXPECT_EQ("abcde", res->body);
  3693. }
  3694. TEST_F(ServerTest, StaticFileRange) {
  3695. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3696. ASSERT_TRUE(res);
  3697. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3698. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3699. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3700. EXPECT_EQ(true, res->has_header("Content-Range"));
  3701. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3702. EXPECT_EQ(std::string("cd"), res->body);
  3703. }
  3704. TEST_F(ServerTest, StaticFileRanges) {
  3705. auto res =
  3706. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3707. ASSERT_TRUE(res);
  3708. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3709. EXPECT_TRUE(
  3710. res->get_header_value("Content-Type")
  3711. .find(
  3712. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3713. 0);
  3714. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3715. }
  3716. TEST_F(ServerTest, StaticFileRangeHead) {
  3717. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3718. ASSERT_TRUE(res);
  3719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3720. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3721. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3722. EXPECT_EQ(true, res->has_header("Content-Range"));
  3723. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3724. }
  3725. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3726. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3727. ASSERT_TRUE(res);
  3728. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3729. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3730. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3731. EXPECT_EQ(true, res->has_header("Content-Range"));
  3732. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3733. res->get_header_value("Content-Range"));
  3734. EXPECT_EQ("LAST\n", res->body);
  3735. }
  3736. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3737. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3738. ASSERT_TRUE(res);
  3739. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3740. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3741. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3742. EXPECT_EQ(true, res->has_header("Content-Range"));
  3743. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3744. }
  3745. TEST_F(ServerTest, StaticFileBigFile) {
  3746. auto res = cli_.Get("/dir/1MB.txt");
  3747. ASSERT_TRUE(res);
  3748. EXPECT_EQ(StatusCode::OK_200, res->status);
  3749. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3750. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3751. }
  3752. TEST_F(ServerTest, InvalidBaseDirMount) {
  3753. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3754. }
  3755. TEST_F(ServerTest, Binary) {
  3756. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3757. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3758. "application/octet-stream");
  3759. ASSERT_TRUE(res);
  3760. ASSERT_EQ(StatusCode::OK_200, res->status);
  3761. ASSERT_EQ(4U, res->body.size());
  3762. res = cli_.Put("/binary", binary.data(), binary.size(),
  3763. "application/octet-stream");
  3764. ASSERT_TRUE(res);
  3765. ASSERT_EQ(StatusCode::OK_200, res->status);
  3766. ASSERT_EQ(4U, res->body.size());
  3767. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3768. "application/octet-stream");
  3769. ASSERT_TRUE(res);
  3770. ASSERT_EQ(StatusCode::OK_200, res->status);
  3771. ASSERT_EQ(4U, res->body.size());
  3772. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3773. "application/octet-stream");
  3774. ASSERT_TRUE(res);
  3775. ASSERT_EQ(StatusCode::OK_200, res->status);
  3776. ASSERT_EQ(4U, res->body.size());
  3777. }
  3778. TEST_F(ServerTest, BinaryString) {
  3779. auto binary = std::string("\x00\x01\x02\x03", 4);
  3780. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3781. ASSERT_TRUE(res);
  3782. ASSERT_EQ(StatusCode::OK_200, res->status);
  3783. ASSERT_EQ(4U, res->body.size());
  3784. res = cli_.Put("/binary", binary, "application/octet-stream");
  3785. ASSERT_TRUE(res);
  3786. ASSERT_EQ(StatusCode::OK_200, res->status);
  3787. ASSERT_EQ(4U, res->body.size());
  3788. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3789. ASSERT_TRUE(res);
  3790. ASSERT_EQ(StatusCode::OK_200, res->status);
  3791. ASSERT_EQ(4U, res->body.size());
  3792. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3793. ASSERT_TRUE(res);
  3794. ASSERT_EQ(StatusCode::OK_200, res->status);
  3795. ASSERT_EQ(4U, res->body.size());
  3796. }
  3797. TEST_F(ServerTest, EmptyRequest) {
  3798. auto res = cli_.Get("");
  3799. ASSERT_TRUE(!res);
  3800. EXPECT_EQ(Error::Connection, res.error());
  3801. }
  3802. TEST_F(ServerTest, LongRequest) {
  3803. std::string request;
  3804. for (size_t i = 0; i < 545; i++) {
  3805. request += "/TooLongRequest";
  3806. }
  3807. request += "OK";
  3808. auto res = cli_.Get(request.c_str());
  3809. ASSERT_TRUE(res);
  3810. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3811. }
  3812. TEST_F(ServerTest, TooLongRequest) {
  3813. std::string request;
  3814. for (size_t i = 0; i < 546; i++) {
  3815. request += "/TooLongRequest";
  3816. }
  3817. request += "_NG";
  3818. auto start = std::chrono::high_resolution_clock::now();
  3819. cli_.set_keep_alive(true);
  3820. auto res = cli_.Get(request.c_str());
  3821. auto end = std::chrono::high_resolution_clock::now();
  3822. auto elapsed =
  3823. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3824. .count();
  3825. ASSERT_TRUE(res);
  3826. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3827. EXPECT_LE(elapsed, 1000);
  3828. EXPECT_EQ("close", res->get_header_value("Connection"));
  3829. EXPECT_FALSE(cli_.is_socket_open());
  3830. }
  3831. TEST_F(ServerTest, AlmostTooLongRequest) {
  3832. // test for #2046 - URI length check shouldn't include other content on req
  3833. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3834. // leading /, space, HTTP/1.1)
  3835. std::string request =
  3836. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3837. auto res = cli_.Get(request.c_str());
  3838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3839. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3840. }
  3841. TEST_F(ServerTest, LongHeader) {
  3842. Request req;
  3843. req.method = "GET";
  3844. req.path = "/hi";
  3845. std::string host_and_port;
  3846. host_and_port += HOST;
  3847. host_and_port += ":";
  3848. host_and_port += std::to_string(PORT);
  3849. req.headers.emplace("Host", host_and_port.c_str());
  3850. req.headers.emplace("Accept", "*/*");
  3851. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3852. req.headers.emplace(
  3853. "Header-Name",
  3854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3882. "@@@@@@@@@@@@@@@@");
  3883. auto res = std::make_shared<Response>();
  3884. auto error = Error::Success;
  3885. auto ret = cli_.send(req, *res, error);
  3886. ASSERT_TRUE(ret);
  3887. EXPECT_EQ(StatusCode::OK_200, res->status);
  3888. }
  3889. TEST_F(ServerTest, LongQueryValue) {
  3890. auto start = std::chrono::high_resolution_clock::now();
  3891. cli_.set_keep_alive(true);
  3892. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3893. auto end = std::chrono::high_resolution_clock::now();
  3894. auto elapsed =
  3895. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3896. .count();
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3899. EXPECT_LE(elapsed, 1000);
  3900. EXPECT_EQ("close", res->get_header_value("Connection"));
  3901. EXPECT_FALSE(cli_.is_socket_open());
  3902. }
  3903. TEST_F(ServerTest, TooLongQueryValue) {
  3904. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3905. ASSERT_FALSE(res);
  3906. EXPECT_EQ(Error::Read, res.error());
  3907. }
  3908. TEST_F(ServerTest, TooLongHeader) {
  3909. Request req;
  3910. req.method = "GET";
  3911. req.path = "/hi";
  3912. std::string host_and_port;
  3913. host_and_port += HOST;
  3914. host_and_port += ":";
  3915. host_and_port += std::to_string(PORT);
  3916. req.headers.emplace("Host", host_and_port.c_str());
  3917. req.headers.emplace("Accept", "*/*");
  3918. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3919. req.headers.emplace(
  3920. "Header-Name",
  3921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3949. "@@@@@@@@@@@@@@@@@");
  3950. auto res = std::make_shared<Response>();
  3951. auto error = Error::Success;
  3952. auto ret = cli_.send(req, *res, error);
  3953. ASSERT_TRUE(ret);
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. }
  3956. TEST_F(ServerTest, HeaderCountAtLimit) {
  3957. // Test with headers just under the 100 limit
  3958. httplib::Headers headers;
  3959. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3960. // This should keep us just under the 100 header limit
  3961. for (int i = 0; i < 95; i++) {
  3962. std::string name = "X-Test-Header-" + std::to_string(i);
  3963. std::string value = "value" + std::to_string(i);
  3964. headers.emplace(name, value);
  3965. }
  3966. // This should work fine as we're under the limit
  3967. auto res = cli_.Get("/hi", headers);
  3968. EXPECT_TRUE(res);
  3969. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3970. }
  3971. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3972. // Test with many headers to exceed the 100 limit
  3973. httplib::Headers headers;
  3974. // Add 150 headers to definitely exceed the 100 limit
  3975. for (int i = 0; i < 150; i++) {
  3976. std::string name = "X-Test-Header-" + std::to_string(i);
  3977. std::string value = "value" + std::to_string(i);
  3978. headers.emplace(name, value);
  3979. }
  3980. // This should fail due to exceeding header count limit
  3981. cli_.set_keep_alive(true);
  3982. auto res = cli_.Get("/hi", headers);
  3983. // The server should respond with 400 Bad Request
  3984. ASSERT_TRUE(res);
  3985. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3986. EXPECT_EQ("close", res->get_header_value("Connection"));
  3987. EXPECT_FALSE(cli_.is_socket_open());
  3988. }
  3989. TEST_F(ServerTest, PercentEncoding) {
  3990. auto res = cli_.Get("/e%6edwith%");
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::OK_200, res->status);
  3993. }
  3994. TEST_F(ServerTest, PercentEncodingUnicode) {
  3995. auto res = cli_.Get("/e%u006edwith%");
  3996. ASSERT_TRUE(res);
  3997. EXPECT_EQ(StatusCode::OK_200, res->status);
  3998. }
  3999. TEST_F(ServerTest, InvalidPercentEncoding) {
  4000. auto res = cli_.Get("/%endwith%");
  4001. ASSERT_TRUE(res);
  4002. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4003. }
  4004. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4005. auto res = cli_.Get("/%uendwith%");
  4006. ASSERT_TRUE(res);
  4007. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4008. }
  4009. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4010. auto res = cli_.Get("/hello?aaa=bbb%");
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4013. }
  4014. TEST_F(ServerTest, PlusSignEncoding) {
  4015. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(StatusCode::OK_200, res->status);
  4018. EXPECT_EQ("a +b", res->body);
  4019. }
  4020. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4021. // This test simulates a potential DoS attack using many headers
  4022. // to verify our security fix prevents memory exhaustion
  4023. httplib::Headers attack_headers;
  4024. // Attempt to add many headers like an attacker would (200 headers to far
  4025. // exceed limit)
  4026. for (int i = 0; i < 200; i++) {
  4027. std::string name = "X-Attack-Header-" + std::to_string(i);
  4028. std::string value = "attack_payload_" + std::to_string(i);
  4029. attack_headers.emplace(name, value);
  4030. }
  4031. // Try to POST with excessive headers
  4032. cli_.set_keep_alive(true);
  4033. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4034. // Should either fail or return 400 Bad Request due to security limit
  4035. if (res) {
  4036. // If we get a response, it should be 400 Bad Request
  4037. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4038. } else {
  4039. // Request failed, which is the expected behavior for DoS protection
  4040. EXPECT_FALSE(res);
  4041. }
  4042. EXPECT_EQ("close", res->get_header_value("Connection"));
  4043. EXPECT_FALSE(cli_.is_socket_open());
  4044. }
  4045. TEST_F(ServerTest, MultipartFormData) {
  4046. UploadFormDataItems items = {
  4047. {"text1", "text default", "", ""},
  4048. {"text2", "aωb", "", ""},
  4049. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4050. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4051. {"file3", "", "", "application/octet-stream"},
  4052. {"file4", "", "", " application/json tmp-string "}};
  4053. auto res = cli_.Post("/multipart", items);
  4054. ASSERT_TRUE(res);
  4055. EXPECT_EQ(StatusCode::OK_200, res->status);
  4056. }
  4057. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4058. UploadFormDataItems items = {
  4059. {"text", "default text", "", ""},
  4060. {"multi_text1", "aaaaa", "", ""},
  4061. {"multi_text1", "bbbbb", "", ""},
  4062. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4063. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4064. "application/json"},
  4065. };
  4066. auto res = cli_.Post("/multipart/multi_file_values", items);
  4067. ASSERT_TRUE(res);
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. }
  4070. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4071. auto res = cli_.Get("/hi");
  4072. ASSERT_TRUE(res);
  4073. EXPECT_EQ(StatusCode::OK_200, res->status);
  4074. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4075. EXPECT_EQ("Hello World!", res->body);
  4076. }
  4077. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4078. Request req;
  4079. req.method = "POST";
  4080. req.path = "/chunked";
  4081. std::string host_and_port;
  4082. host_and_port += HOST;
  4083. host_and_port += ":";
  4084. host_and_port += std::to_string(PORT);
  4085. req.headers.emplace("Host", host_and_port.c_str());
  4086. req.headers.emplace("Accept", "*/*");
  4087. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4088. req.headers.emplace("Content-Type", "text/plain");
  4089. req.headers.emplace("Content-Length", "0");
  4090. req.headers.emplace(
  4091. "Transfer-Encoding",
  4092. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4093. // Client does not chunk, so make a chunked body manually.
  4094. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4095. auto res = std::make_shared<Response>();
  4096. auto error = Error::Success;
  4097. auto ret = cli_.send(req, *res, error);
  4098. ASSERT_TRUE(ret);
  4099. EXPECT_EQ(StatusCode::OK_200, res->status);
  4100. }
  4101. TEST_F(ServerTest, GetStreamed2) {
  4102. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4103. ASSERT_TRUE(res);
  4104. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4105. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4106. EXPECT_EQ(true, res->has_header("Content-Range"));
  4107. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4108. EXPECT_EQ(std::string("ab"), res->body);
  4109. }
  4110. TEST_F(ServerTest, GetStreamed) {
  4111. auto res = cli_.Get("/streamed");
  4112. ASSERT_TRUE(res);
  4113. EXPECT_EQ(StatusCode::OK_200, res->status);
  4114. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4115. EXPECT_EQ(std::string("aaabbb"), res->body);
  4116. }
  4117. TEST_F(ServerTest, GetStreamedWithRange1) {
  4118. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4121. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4122. EXPECT_EQ(true, res->has_header("Content-Range"));
  4123. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4124. EXPECT_EQ(std::string("def"), res->body);
  4125. }
  4126. TEST_F(ServerTest, GetStreamedWithRange2) {
  4127. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4128. ASSERT_TRUE(res);
  4129. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4130. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4131. EXPECT_EQ(true, res->has_header("Content-Range"));
  4132. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4133. EXPECT_EQ(std::string("bcdefg"), res->body);
  4134. }
  4135. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4136. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4139. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4140. EXPECT_EQ(true, res->has_header("Content-Range"));
  4141. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4142. EXPECT_EQ(std::string("efg"), res->body);
  4143. }
  4144. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4145. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4146. ASSERT_TRUE(res);
  4147. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4148. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4149. EXPECT_EQ(false, res->has_header("Content-Range"));
  4150. EXPECT_EQ(0U, res->body.size());
  4151. }
  4152. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4153. auto res = cli_.Get("/streamed-with-range",
  4154. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4155. "92233720368547758079223372036854775807"}});
  4156. ASSERT_TRUE(res);
  4157. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4158. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4159. EXPECT_EQ(false, res->has_header("Content-Range"));
  4160. EXPECT_EQ(0U, res->body.size());
  4161. }
  4162. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4163. auto res = cli_.Get(
  4164. "/with-range",
  4165. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4166. {"Accept-Encoding", ""}});
  4167. ASSERT_TRUE(res);
  4168. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4169. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4170. EXPECT_EQ(true, res->has_header("Content-Range"));
  4171. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4172. EXPECT_EQ(std::string("abcdefg"), res->body);
  4173. }
  4174. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4175. auto res = cli_.Get("/with-range", {
  4176. {"Range", "bytes=0-"},
  4177. {"Accept-Encoding", ""},
  4178. });
  4179. ASSERT_TRUE(res);
  4180. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4181. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4182. EXPECT_EQ(true, res->has_header("Content-Range"));
  4183. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4184. EXPECT_EQ(std::string("abcdefg"), res->body);
  4185. }
  4186. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4187. auto res =
  4188. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4189. ASSERT_TRUE(res);
  4190. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4191. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4192. EXPECT_EQ(false, res->has_header("Content-Range"));
  4193. EXPECT_EQ(267U, res->body.size());
  4194. // Check that both range contents are present
  4195. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4196. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4197. // Check that Content-Range headers are present for both ranges
  4198. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4199. std::string::npos);
  4200. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4201. std::string::npos);
  4202. }
  4203. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4204. Ranges ranges;
  4205. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4206. ranges.emplace_back(0, -1);
  4207. }
  4208. auto res =
  4209. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4210. ASSERT_TRUE(res);
  4211. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4212. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4213. EXPECT_EQ(false, res->has_header("Content-Range"));
  4214. EXPECT_EQ(0U, res->body.size());
  4215. }
  4216. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4217. auto res =
  4218. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4221. EXPECT_EQ(5U, res->body.size());
  4222. // Check that overlapping ranges are coalesced into a single range
  4223. EXPECT_EQ("bcdef", res->body);
  4224. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4225. // Should be single range, not multipart
  4226. EXPECT_TRUE(res->has_header("Content-Range"));
  4227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4228. }
  4229. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4230. auto res =
  4231. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4234. EXPECT_EQ(268U, res->body.size());
  4235. // Check that both range contents are present
  4236. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4237. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4238. // Check that Content-Range headers are present for both ranges
  4239. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4240. std::string::npos);
  4241. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4242. std::string::npos);
  4243. }
  4244. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4245. auto res =
  4246. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4247. ASSERT_TRUE(res);
  4248. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4249. EXPECT_EQ(269U, res->body.size());
  4250. // Check that both duplicate range contents are present
  4251. size_t first_abc = res->body.find("abc\r\n");
  4252. EXPECT_TRUE(first_abc != std::string::npos);
  4253. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4254. EXPECT_TRUE(second_abc != std::string::npos);
  4255. // Check that Content-Range headers are present for both ranges
  4256. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4257. EXPECT_TRUE(first_range != std::string::npos);
  4258. size_t second_range =
  4259. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4260. EXPECT_TRUE(second_range != std::string::npos);
  4261. }
  4262. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4263. auto res = cli_.Get("/streamed-with-range?error",
  4264. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4265. ASSERT_TRUE(res);
  4266. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4267. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4268. EXPECT_EQ(false, res->has_header("Content-Range"));
  4269. EXPECT_EQ(0U, res->body.size());
  4270. }
  4271. TEST_F(ServerTest, GetStreamedEndless) {
  4272. uint64_t offset = 0;
  4273. auto res = cli_.Get("/streamed-cancel",
  4274. [&](const char * /*data*/, uint64_t data_length) {
  4275. if (offset < 100) {
  4276. offset += data_length;
  4277. return true;
  4278. }
  4279. return false;
  4280. });
  4281. ASSERT_TRUE(!res);
  4282. EXPECT_EQ(Error::Canceled, res.error());
  4283. }
  4284. TEST_F(ServerTest, ClientStop) {
  4285. std::atomic_size_t count{4};
  4286. std::vector<std::thread> threads;
  4287. for (auto i = count.load(); i != 0; --i) {
  4288. threads.emplace_back([&]() {
  4289. auto res = cli_.Get("/streamed-cancel",
  4290. [&](const char *, uint64_t) { return true; });
  4291. --count;
  4292. ASSERT_TRUE(!res);
  4293. EXPECT_TRUE(res.error() == Error::Canceled ||
  4294. res.error() == Error::Read || res.error() == Error::Write);
  4295. });
  4296. }
  4297. std::this_thread::sleep_for(std::chrono::seconds(2));
  4298. while (count != 0) {
  4299. cli_.stop();
  4300. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4301. }
  4302. for (auto &t : threads) {
  4303. t.join();
  4304. }
  4305. }
  4306. TEST_F(ServerTest, GetWithRange1) {
  4307. auto res = cli_.Get("/with-range", {
  4308. make_range_header({{3, 5}}),
  4309. {"Accept-Encoding", ""},
  4310. });
  4311. ASSERT_TRUE(res);
  4312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4313. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4314. EXPECT_EQ(true, res->has_header("Content-Range"));
  4315. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4316. EXPECT_EQ(std::string("def"), res->body);
  4317. }
  4318. TEST_F(ServerTest, GetWithRange2) {
  4319. auto res = cli_.Get("/with-range", {
  4320. make_range_header({{1, -1}}),
  4321. {"Accept-Encoding", ""},
  4322. });
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4325. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4326. EXPECT_EQ(true, res->has_header("Content-Range"));
  4327. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4328. EXPECT_EQ(std::string("bcdefg"), res->body);
  4329. }
  4330. TEST_F(ServerTest, GetWithRange3) {
  4331. auto res = cli_.Get("/with-range", {
  4332. make_range_header({{0, 0}}),
  4333. {"Accept-Encoding", ""},
  4334. });
  4335. ASSERT_TRUE(res);
  4336. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4337. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4338. EXPECT_EQ(true, res->has_header("Content-Range"));
  4339. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4340. EXPECT_EQ(std::string("a"), res->body);
  4341. }
  4342. TEST_F(ServerTest, GetWithRange4) {
  4343. auto res = cli_.Get("/with-range", {
  4344. make_range_header({{-1, 2}}),
  4345. {"Accept-Encoding", ""},
  4346. });
  4347. ASSERT_TRUE(res);
  4348. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4349. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4350. EXPECT_EQ(true, res->has_header("Content-Range"));
  4351. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4352. EXPECT_EQ(std::string("fg"), res->body);
  4353. }
  4354. TEST_F(ServerTest, GetWithRange5) {
  4355. auto res = cli_.Get("/with-range", {
  4356. make_range_header({{0, 5}}),
  4357. {"Accept-Encoding", ""},
  4358. });
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4361. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4362. EXPECT_EQ(true, res->has_header("Content-Range"));
  4363. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4364. EXPECT_EQ(std::string("abcdef"), res->body);
  4365. }
  4366. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4367. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4370. }
  4371. TEST_F(ServerTest, GetWithRangeMultipart) {
  4372. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4373. ASSERT_TRUE(res);
  4374. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4375. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4376. EXPECT_EQ(false, res->has_header("Content-Range"));
  4377. EXPECT_EQ(267U, res->body.size());
  4378. }
  4379. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4380. auto res =
  4381. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4382. ASSERT_TRUE(res);
  4383. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4384. }
  4385. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4386. auto res = cli_.Get("/with-range-customized-response",
  4387. {{make_range_header({{1, 2}})}});
  4388. ASSERT_TRUE(res);
  4389. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4390. EXPECT_EQ(true, res->has_header("Content-Length"));
  4391. EXPECT_EQ(false, res->has_header("Content-Range"));
  4392. EXPECT_EQ(JSON_DATA, res->body);
  4393. }
  4394. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4395. auto res = cli_.Get("/with-range-customized-response",
  4396. {{make_range_header({{1, 2}, {4, 5}})}});
  4397. ASSERT_TRUE(res);
  4398. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4399. EXPECT_EQ(true, res->has_header("Content-Length"));
  4400. EXPECT_EQ(false, res->has_header("Content-Range"));
  4401. EXPECT_EQ(JSON_DATA, res->body);
  4402. }
  4403. TEST_F(ServerTest, Issue1772) {
  4404. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4405. ASSERT_TRUE(res);
  4406. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4407. }
  4408. TEST_F(ServerTest, Issue609) {
  4409. auto res = cli_.Delete("/issue609");
  4410. ASSERT_TRUE(res);
  4411. EXPECT_EQ(StatusCode::OK_200, res->status);
  4412. EXPECT_EQ(std::string("ok"), res->body);
  4413. }
  4414. TEST_F(ServerTest, GetStreamedChunked) {
  4415. auto res = cli_.Get("/streamed-chunked");
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::OK_200, res->status);
  4418. EXPECT_EQ(std::string("123456789"), res->body);
  4419. }
  4420. TEST_F(ServerTest, GetStreamedChunked2) {
  4421. auto res = cli_.Get("/streamed-chunked2");
  4422. ASSERT_TRUE(res);
  4423. EXPECT_EQ(StatusCode::OK_200, res->status);
  4424. EXPECT_EQ(std::string("123456789"), res->body);
  4425. }
  4426. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4427. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4428. ASSERT_TRUE(res);
  4429. EXPECT_EQ(StatusCode::OK_200, res->status);
  4430. EXPECT_EQ(std::string("123456789"), res->body);
  4431. EXPECT_TRUE(res->has_header("Trailer"));
  4432. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4433. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4434. // Trailers are now stored separately from headers (security fix)
  4435. EXPECT_EQ(2U, res->trailers.size());
  4436. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4437. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4438. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4439. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4440. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4441. // Verify trailers are NOT in headers (security verification)
  4442. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4443. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4444. }
  4445. TEST_F(ServerTest, LargeChunkedPost) {
  4446. Request req;
  4447. req.method = "POST";
  4448. req.path = "/large-chunked";
  4449. std::string host_and_port;
  4450. host_and_port += HOST;
  4451. host_and_port += ":";
  4452. host_and_port += std::to_string(PORT);
  4453. req.headers.emplace("Host", host_and_port.c_str());
  4454. req.headers.emplace("Accept", "*/*");
  4455. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4456. req.headers.emplace("Content-Type", "text/plain");
  4457. req.headers.emplace("Content-Length", "0");
  4458. req.headers.emplace("Transfer-Encoding", "chunked");
  4459. std::string long_string(30 * 1024u, 'a');
  4460. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4461. // Attempt to make a large enough post to exceed OS buffers, to test that
  4462. // the server handles short reads if the full chunk data isn't available.
  4463. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4464. auto res = std::make_shared<Response>();
  4465. auto error = Error::Success;
  4466. auto ret = cli_.send(req, *res, error);
  4467. ASSERT_TRUE(ret);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. }
  4470. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4471. auto res = cli_.Get("/remote_addr");
  4472. ASSERT_TRUE(res);
  4473. EXPECT_EQ(StatusCode::OK_200, res->status);
  4474. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4475. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4476. }
  4477. TEST_F(ServerTest, GetMethodLocalAddr) {
  4478. auto res = cli_.Get("/local_addr");
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::OK_200, res->status);
  4481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4482. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4483. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4484. }
  4485. TEST_F(ServerTest, HTTPResponseSplitting) {
  4486. auto res = cli_.Get("/http_response_splitting");
  4487. ASSERT_TRUE(res);
  4488. EXPECT_EQ(StatusCode::OK_200, res->status);
  4489. }
  4490. TEST_F(ServerTest, SlowRequest) {
  4491. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4492. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4493. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4494. }
  4495. #if 0
  4496. TEST_F(ServerTest, SlowPost) {
  4497. char buffer[64 * 1024];
  4498. memset(buffer, 0x42, sizeof(buffer));
  4499. auto res = cli_.Post(
  4500. "/slowpost", 64 * 1024 * 1024,
  4501. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4502. auto ret = sink.write(buffer, sizeof(buffer));
  4503. EXPECT_TRUE(ret);
  4504. return true;
  4505. },
  4506. "text/plain");
  4507. ASSERT_TRUE(res);
  4508. EXPECT_EQ(StatusCode::OK_200, res->status);
  4509. }
  4510. TEST_F(ServerTest, SlowPostFail) {
  4511. char buffer[64 * 1024];
  4512. memset(buffer, 0x42, sizeof(buffer));
  4513. cli_.set_write_timeout(std::chrono::seconds(0));
  4514. auto res = cli_.Post(
  4515. "/slowpost", 64 * 1024 * 1024,
  4516. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4517. sink.write(buffer, sizeof(buffer));
  4518. return true;
  4519. },
  4520. "text/plain");
  4521. ASSERT_TRUE(!res);
  4522. EXPECT_EQ(Error::Write, res.error());
  4523. }
  4524. #endif
  4525. TEST_F(ServerTest, Put) {
  4526. auto res = cli_.Put("/put", "PUT", "text/plain");
  4527. ASSERT_TRUE(res);
  4528. EXPECT_EQ(StatusCode::OK_200, res->status);
  4529. EXPECT_EQ("PUT", res->body);
  4530. }
  4531. TEST_F(ServerTest, PutWithContentProvider) {
  4532. auto res = cli_.Put(
  4533. "/put", 3,
  4534. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4535. sink.os << "PUT";
  4536. return true;
  4537. },
  4538. "text/plain");
  4539. ASSERT_TRUE(res);
  4540. EXPECT_EQ(StatusCode::OK_200, res->status);
  4541. EXPECT_EQ("PUT", res->body);
  4542. }
  4543. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4544. auto res = cli_.Post(
  4545. "/post", 42,
  4546. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4547. return false;
  4548. },
  4549. "text/plain");
  4550. ASSERT_TRUE(!res);
  4551. EXPECT_EQ(Error::Canceled, res.error());
  4552. }
  4553. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4554. auto res = cli_.Put(
  4555. "/put",
  4556. [](size_t /*offset*/, DataSink &sink) {
  4557. sink.os << "PUT";
  4558. sink.done();
  4559. return true;
  4560. },
  4561. "text/plain");
  4562. ASSERT_TRUE(res);
  4563. EXPECT_EQ(StatusCode::OK_200, res->status);
  4564. EXPECT_EQ("PUT", res->body);
  4565. }
  4566. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4567. auto res = cli_.Post(
  4568. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4569. "text/plain");
  4570. ASSERT_TRUE(!res);
  4571. EXPECT_EQ(Error::Canceled, res.error());
  4572. }
  4573. TEST_F(ServerTest, PostLoopBack) {
  4574. std::string body;
  4575. auto res = cli_.Post(
  4576. "/post-loopback", 9,
  4577. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4578. EXPECT_EQ(9u, length);
  4579. sink.write("123", 3);
  4580. sink.write("456", 3);
  4581. sink.write("789", 3);
  4582. return true;
  4583. },
  4584. "text/plain",
  4585. [&body](const char *data, size_t data_length) {
  4586. body.append(data, data_length);
  4587. return true;
  4588. });
  4589. ASSERT_TRUE(res);
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ("123456789", body);
  4592. }
  4593. TEST_F(ServerTest, PutLoopBack) {
  4594. std::string body;
  4595. auto res = cli_.Put(
  4596. "/put-loopback", 9,
  4597. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4598. EXPECT_EQ(9u, length);
  4599. sink.write("123", 3);
  4600. sink.write("456", 3);
  4601. sink.write("789", 3);
  4602. return true;
  4603. },
  4604. "text/plain",
  4605. [&body](const char *data, size_t data_length) {
  4606. body.append(data, data_length);
  4607. return true;
  4608. });
  4609. ASSERT_TRUE(res);
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. EXPECT_EQ("123456789", body);
  4612. }
  4613. TEST_F(ServerTest, PatchLoopBack) {
  4614. std::string body;
  4615. auto res = cli_.Patch(
  4616. "/patch-loopback", 9,
  4617. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4618. EXPECT_EQ(9u, length);
  4619. sink.write("123", 3);
  4620. sink.write("456", 3);
  4621. sink.write("789", 3);
  4622. return true;
  4623. },
  4624. "text/plain",
  4625. [&body](const char *data, size_t data_length) {
  4626. body.append(data, data_length);
  4627. return true;
  4628. });
  4629. ASSERT_TRUE(res);
  4630. EXPECT_EQ(StatusCode::OK_200, res->status);
  4631. EXPECT_EQ("123456789", body);
  4632. }
  4633. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4634. std::string body;
  4635. auto res = cli_.Post(
  4636. "/post-loopback",
  4637. [](size_t /*offset*/, DataSink &sink) {
  4638. sink.write("123", 3);
  4639. sink.write("456", 3);
  4640. sink.write("789", 3);
  4641. sink.done();
  4642. return true;
  4643. },
  4644. "text/plain",
  4645. [&body](const char *data, size_t data_length) {
  4646. body.append(data, data_length);
  4647. return true;
  4648. });
  4649. ASSERT_TRUE(res);
  4650. EXPECT_EQ(StatusCode::OK_200, res->status);
  4651. EXPECT_EQ("123456789", body);
  4652. }
  4653. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4654. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4655. cli_.set_compress(true);
  4656. auto res = cli_.Put(
  4657. "/put", 3,
  4658. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4659. sink.os << "PUT";
  4660. return true;
  4661. },
  4662. "text/plain");
  4663. ASSERT_TRUE(res);
  4664. EXPECT_EQ(StatusCode::OK_200, res->status);
  4665. EXPECT_EQ("PUT", res->body);
  4666. }
  4667. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4668. cli_.set_compress(true);
  4669. auto res = cli_.Post(
  4670. "/post", 42,
  4671. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4672. return false;
  4673. },
  4674. "text/plain");
  4675. ASSERT_TRUE(!res);
  4676. EXPECT_EQ(Error::Canceled, res.error());
  4677. }
  4678. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4679. cli_.set_compress(true);
  4680. auto res = cli_.Put(
  4681. "/put",
  4682. [](size_t /*offset*/, DataSink &sink) {
  4683. sink.os << "PUT";
  4684. sink.done();
  4685. return true;
  4686. },
  4687. "text/plain");
  4688. ASSERT_TRUE(res);
  4689. EXPECT_EQ(StatusCode::OK_200, res->status);
  4690. EXPECT_EQ("PUT", res->body);
  4691. }
  4692. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4693. cli_.set_compress(true);
  4694. auto res = cli_.Post(
  4695. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4696. "text/plain");
  4697. ASSERT_TRUE(!res);
  4698. EXPECT_EQ(Error::Canceled, res.error());
  4699. }
  4700. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4701. cli_.set_compress(true);
  4702. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. EXPECT_EQ(LARGE_DATA, res->body);
  4706. }
  4707. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4708. #ifdef CPPHTTPLIB_SSL_ENABLED
  4709. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4710. Client cli(s.c_str());
  4711. cli.enable_server_certificate_verification(false);
  4712. #else
  4713. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4714. Client cli(s.c_str());
  4715. #endif
  4716. cli.set_compress(true);
  4717. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4718. ASSERT_TRUE(res);
  4719. EXPECT_EQ(StatusCode::OK_200, res->status);
  4720. EXPECT_EQ(LARGE_DATA, res->body);
  4721. // The compressed size should be less than a 10th of the original. May vary
  4722. // depending on the zlib library.
  4723. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4724. static_cast<uint64_t>(10 * 1024 * 1024));
  4725. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4726. }
  4727. TEST_F(ServerTest, PutContentWithDeflate) {
  4728. cli_.set_compress(false);
  4729. Headers headers;
  4730. headers.emplace("Content-Encoding", "deflate");
  4731. // PUT in deflate format:
  4732. auto res = cli_.Put("/put", headers,
  4733. "\170\234\013\010\015\001\0\001\361\0\372", "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, GetStreamedChunkedWithGzip) {
  4739. Headers headers;
  4740. headers.emplace("Accept-Encoding", "gzip, deflate");
  4741. auto res = cli_.Get("/streamed-chunked", headers);
  4742. ASSERT_TRUE(res);
  4743. EXPECT_EQ(StatusCode::OK_200, res->status);
  4744. EXPECT_EQ(std::string("123456789"), res->body);
  4745. }
  4746. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4747. Headers headers;
  4748. headers.emplace("Accept-Encoding", "gzip, deflate");
  4749. auto res = cli_.Get("/streamed-chunked2", headers);
  4750. ASSERT_TRUE(res);
  4751. EXPECT_EQ(StatusCode::OK_200, res->status);
  4752. EXPECT_EQ(std::string("123456789"), res->body);
  4753. }
  4754. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4755. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4756. ASSERT_TRUE(res);
  4757. EXPECT_EQ(StatusCode::OK_200, res->status);
  4758. }
  4759. TEST(GzipDecompressor, ChunkedDecompression) {
  4760. std::string data;
  4761. for (size_t i = 0; i < 32 * 1024; ++i) {
  4762. data.push_back(static_cast<char>('a' + i % 26));
  4763. }
  4764. std::string compressed_data;
  4765. {
  4766. httplib::detail::gzip_compressor compressor;
  4767. bool result = compressor.compress(
  4768. data.data(), data.size(),
  4769. /*last=*/true,
  4770. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4771. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4772. compressed_data_size);
  4773. return true;
  4774. });
  4775. ASSERT_TRUE(result);
  4776. }
  4777. std::string decompressed_data;
  4778. {
  4779. httplib::detail::gzip_decompressor decompressor;
  4780. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4781. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4782. size_t chunk_size = 130;
  4783. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4784. chunk_begin += chunk_size) {
  4785. size_t current_chunk_size =
  4786. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4787. bool result = decompressor.decompress(
  4788. compressed_data.data() + chunk_begin, current_chunk_size,
  4789. [&](const char *decompressed_data_chunk,
  4790. size_t decompressed_data_chunk_size) {
  4791. decompressed_data.insert(decompressed_data.size(),
  4792. decompressed_data_chunk,
  4793. decompressed_data_chunk_size);
  4794. return true;
  4795. });
  4796. ASSERT_TRUE(result);
  4797. }
  4798. }
  4799. ASSERT_EQ(data, decompressed_data);
  4800. }
  4801. TEST(GzipDecompressor, DeflateDecompression) {
  4802. std::string original_text = "Raw deflate without gzip";
  4803. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4804. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4805. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4806. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4807. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4808. std::string decompressed_data;
  4809. {
  4810. httplib::detail::gzip_decompressor decompressor;
  4811. bool result = decompressor.decompress(
  4812. compressed_data.data(), compressed_data.size(),
  4813. [&](const char *decompressed_data_chunk,
  4814. size_t decompressed_data_chunk_size) {
  4815. decompressed_data.insert(decompressed_data.size(),
  4816. decompressed_data_chunk,
  4817. decompressed_data_chunk_size);
  4818. return true;
  4819. });
  4820. ASSERT_TRUE(result);
  4821. }
  4822. ASSERT_EQ(original_text, decompressed_data);
  4823. }
  4824. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4825. std::string original_text = "Raw deflate without gzip";
  4826. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4827. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4828. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4829. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4830. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4831. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4832. std::string decompressed_data;
  4833. {
  4834. httplib::detail::gzip_decompressor decompressor;
  4835. bool result = decompressor.decompress(
  4836. compressed_data.data(), compressed_data.size(),
  4837. [&](const char *decompressed_data_chunk,
  4838. size_t decompressed_data_chunk_size) {
  4839. decompressed_data.insert(decompressed_data.size(),
  4840. decompressed_data_chunk,
  4841. decompressed_data_chunk_size);
  4842. return true;
  4843. });
  4844. ASSERT_TRUE(result);
  4845. }
  4846. ASSERT_EQ(original_text, decompressed_data);
  4847. }
  4848. #ifdef _WIN32
  4849. TEST(GzipDecompressor, LargeRandomData) {
  4850. // prepare large random data that is difficult to be compressed and is
  4851. // expected to have large size even when compressed
  4852. std::random_device seed_gen;
  4853. std::mt19937 random(seed_gen());
  4854. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4855. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4856. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4857. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4858. // compress data over 4GiB
  4859. std::string compressed_data;
  4860. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4861. httplib::detail::gzip_compressor compressor;
  4862. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4863. data.size() * sizeof(std::uint32_t), true,
  4864. [&](const char *data, size_t size) {
  4865. compressed_data.insert(
  4866. compressed_data.size(), data, size);
  4867. return true;
  4868. });
  4869. ASSERT_TRUE(result);
  4870. // FIXME: compressed data size is expected to be greater than 4GiB,
  4871. // but there is no guarantee
  4872. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4873. // decompress data over 4GiB
  4874. std::string decompressed_data;
  4875. decompressed_data.reserve(data_size);
  4876. httplib::detail::gzip_decompressor decompressor;
  4877. result = decompressor.decompress(
  4878. compressed_data.data(), compressed_data.size(),
  4879. [&](const char *data, size_t size) {
  4880. decompressed_data.insert(decompressed_data.size(), data, size);
  4881. return true;
  4882. });
  4883. ASSERT_TRUE(result);
  4884. // compare
  4885. ASSERT_EQ(data_size, decompressed_data.size());
  4886. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4887. 0);
  4888. }
  4889. #endif
  4890. #endif
  4891. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4892. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4893. Headers headers;
  4894. headers.emplace("Accept-Encoding", "br");
  4895. auto res = cli_.Get("/streamed-chunked", headers);
  4896. ASSERT_TRUE(res);
  4897. EXPECT_EQ(StatusCode::OK_200, res->status);
  4898. EXPECT_EQ(std::string("123456789"), res->body);
  4899. }
  4900. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4901. Headers headers;
  4902. headers.emplace("Accept-Encoding", "br");
  4903. auto res = cli_.Get("/streamed-chunked2", headers);
  4904. ASSERT_TRUE(res);
  4905. EXPECT_EQ(StatusCode::OK_200, res->status);
  4906. EXPECT_EQ(std::string("123456789"), res->body);
  4907. }
  4908. #endif
  4909. TEST_F(ServerTest, Patch) {
  4910. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4911. ASSERT_TRUE(res);
  4912. EXPECT_EQ(StatusCode::OK_200, res->status);
  4913. EXPECT_EQ("PATCH", res->body);
  4914. }
  4915. TEST_F(ServerTest, Delete) {
  4916. auto res = cli_.Delete("/delete");
  4917. ASSERT_TRUE(res);
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. EXPECT_EQ("DELETE", res->body);
  4920. }
  4921. TEST_F(ServerTest, DeleteContentReceiver) {
  4922. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4923. ASSERT_TRUE(res);
  4924. EXPECT_EQ(StatusCode::OK_200, res->status);
  4925. EXPECT_EQ("content", res->body);
  4926. }
  4927. TEST_F(ServerTest, Options) {
  4928. auto res = cli_.Options("*");
  4929. ASSERT_TRUE(res);
  4930. EXPECT_EQ(StatusCode::OK_200, res->status);
  4931. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4932. EXPECT_TRUE(res->body.empty());
  4933. }
  4934. TEST_F(ServerTest, URL) {
  4935. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4936. ASSERT_TRUE(res);
  4937. EXPECT_EQ(StatusCode::OK_200, res->status);
  4938. }
  4939. TEST_F(ServerTest, ArrayParam) {
  4940. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4941. ASSERT_TRUE(res);
  4942. EXPECT_EQ(StatusCode::OK_200, res->status);
  4943. }
  4944. TEST_F(ServerTest, NoMultipleHeaders) {
  4945. Headers headers = {{"Content-Length", "5"}};
  4946. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4947. "text/plain");
  4948. ASSERT_TRUE(res);
  4949. EXPECT_EQ(StatusCode::OK_200, res->status);
  4950. }
  4951. TEST_F(ServerTest, PostContentReceiver) {
  4952. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4953. ASSERT_TRUE(res);
  4954. ASSERT_EQ(StatusCode::OK_200, res->status);
  4955. ASSERT_EQ("content", res->body);
  4956. }
  4957. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4958. UploadFormDataItems items = {
  4959. {"text1", "text default", "", ""},
  4960. {"text2", "aωb", "", ""},
  4961. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4962. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4963. {"file3", "", "", "application/octet-stream"},
  4964. };
  4965. auto res = cli_.Post("/content_receiver", items);
  4966. ASSERT_TRUE(res);
  4967. EXPECT_EQ(StatusCode::OK_200, res->status);
  4968. }
  4969. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4970. UploadFormDataItems items = {
  4971. {"text1", "text default", "", ""},
  4972. {"text2", "aωb", "", ""},
  4973. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4974. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4975. {"file3", "", "", "application/octet-stream"},
  4976. };
  4977. auto boundary = std::string("+++++");
  4978. std::string body;
  4979. for (const auto &item : items) {
  4980. body += "--" + boundary + "\r\n";
  4981. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4982. if (!item.filename.empty()) {
  4983. body += "; filename=\"" + item.filename + "\"";
  4984. }
  4985. body += "\r\n";
  4986. if (!item.content_type.empty()) {
  4987. body += "Content-Type: " + item.content_type + "\r\n";
  4988. }
  4989. body += "\r\n";
  4990. body += item.content + "\r\n";
  4991. }
  4992. body += "--" + boundary + "--\r\n";
  4993. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4994. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4995. ASSERT_TRUE(res);
  4996. EXPECT_EQ(StatusCode::OK_200, res->status);
  4997. }
  4998. TEST_F(ServerTest, PostContentReceiverGzip) {
  4999. cli_.set_compress(true);
  5000. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5001. ASSERT_TRUE(res);
  5002. ASSERT_EQ(StatusCode::OK_200, res->status);
  5003. ASSERT_EQ("content", res->body);
  5004. }
  5005. TEST_F(ServerTest, PutContentReceiver) {
  5006. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5007. ASSERT_TRUE(res);
  5008. ASSERT_EQ(StatusCode::OK_200, res->status);
  5009. ASSERT_EQ("content", res->body);
  5010. }
  5011. TEST_F(ServerTest, PatchContentReceiver) {
  5012. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5013. ASSERT_TRUE(res);
  5014. ASSERT_EQ(StatusCode::OK_200, res->status);
  5015. ASSERT_EQ("content", res->body);
  5016. }
  5017. template <typename ClientType>
  5018. void TestWithHeadersAndContentReceiver(
  5019. ClientType &cli,
  5020. std::function<Result(ClientType &, const std::string &, const Headers &,
  5021. const std::string &, const std::string &,
  5022. ContentReceiver, DownloadProgress)>
  5023. request_func) {
  5024. Headers headers;
  5025. headers.emplace("X-Custom-Header", "test-value");
  5026. std::string received_body;
  5027. auto res = request_func(
  5028. cli, "/content_receiver", headers, "content", "application/json",
  5029. [&](const char *data, size_t data_length) {
  5030. received_body.append(data, data_length);
  5031. return true;
  5032. },
  5033. nullptr);
  5034. ASSERT_TRUE(res);
  5035. EXPECT_EQ(StatusCode::OK_200, res->status);
  5036. EXPECT_EQ("content", received_body);
  5037. }
  5038. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5039. #ifdef CPPHTTPLIB_SSL_ENABLED
  5040. using ClientT = SSLClient;
  5041. #else
  5042. using ClientT = Client;
  5043. #endif
  5044. TestWithHeadersAndContentReceiver<ClientT>(
  5045. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5046. const std::string &body, const std::string &content_type,
  5047. ContentReceiver receiver, DownloadProgress progress) {
  5048. return cli.Post(path, headers, body, content_type, receiver, progress);
  5049. });
  5050. }
  5051. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5052. #ifdef CPPHTTPLIB_SSL_ENABLED
  5053. using ClientT = SSLClient;
  5054. #else
  5055. using ClientT = Client;
  5056. #endif
  5057. TestWithHeadersAndContentReceiver<ClientT>(
  5058. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5059. const std::string &body, const std::string &content_type,
  5060. ContentReceiver receiver, DownloadProgress progress) {
  5061. return cli.Put(path, headers, body, content_type, receiver, progress);
  5062. });
  5063. }
  5064. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5065. #ifdef CPPHTTPLIB_SSL_ENABLED
  5066. using ClientT = SSLClient;
  5067. #else
  5068. using ClientT = Client;
  5069. #endif
  5070. TestWithHeadersAndContentReceiver<ClientT>(
  5071. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5072. const std::string &body, const std::string &content_type,
  5073. ContentReceiver receiver, DownloadProgress progress) {
  5074. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5075. });
  5076. }
  5077. template <typename ClientType>
  5078. void TestWithHeadersAndContentReceiverWithProgress(
  5079. ClientType &cli,
  5080. std::function<Result(ClientType &, const std::string &, const Headers &,
  5081. const std::string &, const std::string &,
  5082. ContentReceiver, DownloadProgress)>
  5083. request_func) {
  5084. Headers headers;
  5085. headers.emplace("X-Test-Header", "progress-test");
  5086. std::string received_body;
  5087. auto progress_called = false;
  5088. auto res = request_func(
  5089. cli, "/content_receiver", headers, "content", "text/plain",
  5090. [&](const char *data, size_t data_length) {
  5091. received_body.append(data, data_length);
  5092. return true;
  5093. },
  5094. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5095. progress_called = true;
  5096. return true;
  5097. });
  5098. ASSERT_TRUE(res);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. EXPECT_EQ("content", received_body);
  5101. EXPECT_TRUE(progress_called);
  5102. }
  5103. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5104. #ifdef CPPHTTPLIB_SSL_ENABLED
  5105. using ClientT = SSLClient;
  5106. #else
  5107. using ClientT = Client;
  5108. #endif
  5109. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5110. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5111. const std::string &body, const std::string &content_type,
  5112. ContentReceiver receiver, DownloadProgress progress) {
  5113. return cli.Post(path, headers, body, content_type, receiver, progress);
  5114. });
  5115. }
  5116. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5117. #ifdef CPPHTTPLIB_SSL_ENABLED
  5118. using ClientT = SSLClient;
  5119. #else
  5120. using ClientT = Client;
  5121. #endif
  5122. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5123. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5124. const std::string &body, const std::string &content_type,
  5125. ContentReceiver receiver, DownloadProgress progress) {
  5126. return cli.Put(path, headers, body, content_type, receiver, progress);
  5127. });
  5128. }
  5129. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5130. #ifdef CPPHTTPLIB_SSL_ENABLED
  5131. using ClientT = SSLClient;
  5132. #else
  5133. using ClientT = Client;
  5134. #endif
  5135. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5136. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5137. const std::string &body, const std::string &content_type,
  5138. ContentReceiver receiver, DownloadProgress progress) {
  5139. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5140. });
  5141. }
  5142. template <typename ClientType>
  5143. void TestWithHeadersAndContentReceiverError(
  5144. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5145. const Headers &, const std::string &,
  5146. const std::string &, ContentReceiver)>
  5147. request_func) {
  5148. Headers headers;
  5149. headers.emplace("X-Error-Test", "true");
  5150. std::string received_body;
  5151. auto receiver_failed = false;
  5152. auto res =
  5153. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5154. [&](const char *data, size_t data_length) {
  5155. received_body.append(data, data_length);
  5156. receiver_failed = true;
  5157. return false;
  5158. });
  5159. ASSERT_FALSE(res);
  5160. EXPECT_TRUE(receiver_failed);
  5161. }
  5162. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5163. #ifdef CPPHTTPLIB_SSL_ENABLED
  5164. using ClientT = SSLClient;
  5165. #else
  5166. using ClientT = Client;
  5167. #endif
  5168. TestWithHeadersAndContentReceiverError<ClientT>(
  5169. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5170. const std::string &body, const std::string &content_type,
  5171. ContentReceiver receiver) {
  5172. return cli.Post(path, headers, body, content_type, receiver);
  5173. });
  5174. }
  5175. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5176. #ifdef CPPHTTPLIB_SSL_ENABLED
  5177. using ClientT = SSLClient;
  5178. #else
  5179. using ClientT = Client;
  5180. #endif
  5181. TestWithHeadersAndContentReceiverError<ClientT>(
  5182. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5183. const std::string &body, const std::string &content_type,
  5184. ContentReceiver receiver) {
  5185. return cli.Put(path, headers, body, content_type, receiver);
  5186. });
  5187. }
  5188. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5189. #ifdef CPPHTTPLIB_SSL_ENABLED
  5190. using ClientT = SSLClient;
  5191. #else
  5192. using ClientT = Client;
  5193. #endif
  5194. TestWithHeadersAndContentReceiverError<ClientT>(
  5195. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5196. const std::string &body, const std::string &content_type,
  5197. ContentReceiver receiver) {
  5198. return cli.Patch(path, headers, body, content_type, receiver);
  5199. });
  5200. }
  5201. TEST_F(ServerTest, PostQueryStringAndBody) {
  5202. auto res =
  5203. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5204. ASSERT_TRUE(res);
  5205. ASSERT_EQ(StatusCode::OK_200, res->status);
  5206. }
  5207. TEST_F(ServerTest, HTTP2Magic) {
  5208. Request req;
  5209. req.method = "PRI";
  5210. req.path = "*";
  5211. req.body = "SM";
  5212. auto res = std::make_shared<Response>();
  5213. auto error = Error::Success;
  5214. auto ret = cli_.send(req, *res, error);
  5215. ASSERT_TRUE(ret);
  5216. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5217. }
  5218. TEST_F(ServerTest, KeepAlive) {
  5219. auto res = cli_.Get("/hi");
  5220. ASSERT_TRUE(res);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5223. EXPECT_EQ("Hello World!", res->body);
  5224. res = cli_.Get("/hi");
  5225. ASSERT_TRUE(res);
  5226. EXPECT_EQ(StatusCode::OK_200, res->status);
  5227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5228. EXPECT_EQ("Hello World!", res->body);
  5229. res = cli_.Get("/hi");
  5230. ASSERT_TRUE(res);
  5231. EXPECT_EQ(StatusCode::OK_200, res->status);
  5232. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5233. EXPECT_EQ("Hello World!", res->body);
  5234. res = cli_.Get("/not-exist");
  5235. ASSERT_TRUE(res);
  5236. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5237. res = cli_.Post("/empty", "", "text/plain");
  5238. ASSERT_TRUE(res);
  5239. EXPECT_EQ(StatusCode::OK_200, res->status);
  5240. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5241. EXPECT_EQ("empty", res->body);
  5242. EXPECT_EQ("close", res->get_header_value("Connection"));
  5243. res = cli_.Post(
  5244. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5245. "text/plain");
  5246. ASSERT_TRUE(res);
  5247. EXPECT_EQ(StatusCode::OK_200, res->status);
  5248. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5249. EXPECT_EQ("empty", res->body);
  5250. cli_.set_keep_alive(false);
  5251. res = cli_.Get("/last-request");
  5252. ASSERT_TRUE(res);
  5253. EXPECT_EQ(StatusCode::OK_200, res->status);
  5254. EXPECT_EQ("close", res->get_header_value("Connection"));
  5255. }
  5256. TEST_F(ServerTest, TooManyRedirect) {
  5257. cli_.set_follow_location(true);
  5258. auto res = cli_.Get("/redirect/0");
  5259. ASSERT_TRUE(!res);
  5260. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5261. }
  5262. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5263. Request req;
  5264. req.method = "FOOBAR";
  5265. req.path = "/hi";
  5266. cli_.set_keep_alive(true);
  5267. auto res = cli_.send(req);
  5268. ASSERT_TRUE(res);
  5269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5270. EXPECT_EQ("close", res->get_header_value("Connection"));
  5271. EXPECT_FALSE(cli_.is_socket_open());
  5272. }
  5273. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5274. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5275. TEST_F(ServerTest, Gzip) {
  5276. Headers headers;
  5277. headers.emplace("Accept-Encoding", "gzip, deflate");
  5278. auto res = cli_.Get("/compress", headers);
  5279. ASSERT_TRUE(res);
  5280. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5282. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5283. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5284. "7890123456789012345678901234567890",
  5285. res->body);
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. }
  5288. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5289. Headers headers;
  5290. headers.emplace("Accept-Encoding", "");
  5291. auto res = cli_.Get("/compress", headers);
  5292. ASSERT_TRUE(res);
  5293. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5295. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5296. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5297. "7890123456789012345678901234567890",
  5298. res->body);
  5299. EXPECT_EQ(StatusCode::OK_200, res->status);
  5300. }
  5301. TEST_F(ServerTest, GzipWithContentReceiver) {
  5302. Headers headers;
  5303. headers.emplace("Accept-Encoding", "gzip, deflate");
  5304. std::string body;
  5305. auto res = cli_.Get("/compress", headers,
  5306. [&](const char *data, uint64_t data_length) {
  5307. EXPECT_EQ(100U, data_length);
  5308. body.append(data, data_length);
  5309. return true;
  5310. });
  5311. ASSERT_TRUE(res);
  5312. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5313. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5314. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5315. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5316. "7890123456789012345678901234567890",
  5317. body);
  5318. EXPECT_EQ(StatusCode::OK_200, res->status);
  5319. }
  5320. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5321. Headers headers;
  5322. headers.emplace("Accept-Encoding", "gzip, deflate");
  5323. cli_.set_decompress(false);
  5324. auto res = cli_.Get("/compress", headers);
  5325. ASSERT_TRUE(res);
  5326. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5327. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5328. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5329. EXPECT_EQ(33U, res->body.size());
  5330. EXPECT_EQ(StatusCode::OK_200, res->status);
  5331. }
  5332. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5333. Headers headers;
  5334. headers.emplace("Accept-Encoding", "");
  5335. std::string body;
  5336. auto res = cli_.Get("/compress", headers,
  5337. [&](const char *data, uint64_t data_length) {
  5338. EXPECT_EQ(100U, data_length);
  5339. body.append(data, data_length);
  5340. return true;
  5341. });
  5342. ASSERT_TRUE(res);
  5343. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5344. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5345. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5346. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5347. "7890123456789012345678901234567890",
  5348. body);
  5349. EXPECT_EQ(StatusCode::OK_200, res->status);
  5350. }
  5351. TEST_F(ServerTest, NoGzip) {
  5352. Headers headers;
  5353. headers.emplace("Accept-Encoding", "gzip, deflate");
  5354. auto res = cli_.Get("/nocompress", headers);
  5355. ASSERT_TRUE(res);
  5356. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5357. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5358. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5359. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5360. "7890123456789012345678901234567890",
  5361. res->body);
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. }
  5364. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5365. Headers headers;
  5366. headers.emplace("Accept-Encoding", "gzip, deflate");
  5367. std::string body;
  5368. auto res = cli_.Get("/nocompress", headers,
  5369. [&](const char *data, uint64_t data_length) {
  5370. EXPECT_EQ(100U, data_length);
  5371. body.append(data, data_length);
  5372. return true;
  5373. });
  5374. ASSERT_TRUE(res);
  5375. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5376. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5377. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5378. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5379. "7890123456789012345678901234567890",
  5380. body);
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. }
  5383. TEST_F(ServerTest, MultipartFormDataGzip) {
  5384. UploadFormDataItems items = {
  5385. {"key1", "test", "", ""},
  5386. {"key2", "--abcdefg123", "", ""},
  5387. };
  5388. cli_.set_compress(true);
  5389. auto res = cli_.Post("/compress-multipart", items);
  5390. ASSERT_TRUE(res);
  5391. EXPECT_EQ(StatusCode::OK_200, res->status);
  5392. }
  5393. #endif
  5394. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5395. TEST_F(ServerTest, Brotli) {
  5396. Headers headers;
  5397. headers.emplace("Accept-Encoding", "br");
  5398. auto res = cli_.Get("/compress", headers);
  5399. ASSERT_TRUE(res);
  5400. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5402. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5404. "7890123456789012345678901234567890",
  5405. res->body);
  5406. EXPECT_EQ(StatusCode::OK_200, res->status);
  5407. }
  5408. #endif
  5409. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5410. TEST_F(ServerTest, Zstd) {
  5411. Headers headers;
  5412. headers.emplace("Accept-Encoding", "zstd");
  5413. auto res = cli_.Get("/compress", headers);
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5416. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5417. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5418. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5419. "7890123456789012345678901234567890",
  5420. res->body);
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. }
  5423. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5424. Headers headers;
  5425. headers.emplace("Accept-Encoding", "");
  5426. auto res = cli_.Get("/compress", headers);
  5427. ASSERT_TRUE(res);
  5428. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5429. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5431. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5432. "7890123456789012345678901234567890",
  5433. res->body);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. }
  5436. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "zstd");
  5439. std::string body;
  5440. auto res = cli_.Get("/compress", headers,
  5441. [&](const char *data, uint64_t data_length) {
  5442. EXPECT_EQ(100U, data_length);
  5443. body.append(data, data_length);
  5444. return true;
  5445. });
  5446. ASSERT_TRUE(res);
  5447. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5448. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5449. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5450. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5451. "7890123456789012345678901234567890",
  5452. body);
  5453. EXPECT_EQ(StatusCode::OK_200, res->status);
  5454. }
  5455. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5456. Headers headers;
  5457. headers.emplace("Accept-Encoding", "zstd");
  5458. cli_.set_decompress(false);
  5459. auto res = cli_.Get("/compress", headers);
  5460. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5461. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5462. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5463. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5467. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5468. EXPECT_EQ(StatusCode::OK_200, res->status);
  5469. ASSERT_EQ(26U, res->body.size());
  5470. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5471. 0);
  5472. }
  5473. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5474. Headers headers;
  5475. headers.emplace("Accept-Encoding", "");
  5476. std::string body;
  5477. auto res = cli_.Get("/compress", headers,
  5478. [&](const char *data, uint64_t data_length) {
  5479. EXPECT_EQ(100U, data_length);
  5480. body.append(data, data_length);
  5481. return true;
  5482. });
  5483. ASSERT_TRUE(res);
  5484. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5485. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5486. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5487. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5488. "7890123456789012345678901234567890",
  5489. body);
  5490. EXPECT_EQ(StatusCode::OK_200, res->status);
  5491. }
  5492. TEST_F(ServerTest, NoZstd) {
  5493. Headers headers;
  5494. headers.emplace("Accept-Encoding", "zstd");
  5495. auto res = cli_.Get("/nocompress", headers);
  5496. ASSERT_TRUE(res);
  5497. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5498. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5499. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5500. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5501. "7890123456789012345678901234567890",
  5502. res->body);
  5503. EXPECT_EQ(StatusCode::OK_200, res->status);
  5504. }
  5505. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5506. Headers headers;
  5507. headers.emplace("Accept-Encoding", "zstd");
  5508. std::string body;
  5509. auto res = cli_.Get("/nocompress", headers,
  5510. [&](const char *data, uint64_t data_length) {
  5511. EXPECT_EQ(100U, data_length);
  5512. body.append(data, data_length);
  5513. return true;
  5514. });
  5515. ASSERT_TRUE(res);
  5516. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5517. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5518. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5519. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5520. "7890123456789012345678901234567890",
  5521. body);
  5522. EXPECT_EQ(StatusCode::OK_200, res->status);
  5523. }
  5524. // TODO: How to enable zstd ??
  5525. TEST_F(ServerTest, MultipartFormDataZstd) {
  5526. UploadFormDataItems items = {
  5527. {"key1", "test", "", ""},
  5528. {"key2", "--abcdefg123", "", ""},
  5529. };
  5530. Headers headers;
  5531. headers.emplace("Accept-Encoding", "zstd");
  5532. cli_.set_compress(true);
  5533. auto res = cli_.Post("/compress-multipart", headers, items);
  5534. ASSERT_TRUE(res);
  5535. EXPECT_EQ(StatusCode::OK_200, res->status);
  5536. }
  5537. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5538. Headers headers;
  5539. headers.emplace("Accept-Encoding", "zstd");
  5540. cli_.set_compress(true);
  5541. auto res = cli_.Put(
  5542. "/put", headers, 3,
  5543. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5544. sink.os << "PUT";
  5545. return true;
  5546. },
  5547. "text/plain");
  5548. ASSERT_TRUE(res);
  5549. EXPECT_EQ(StatusCode::OK_200, res->status);
  5550. EXPECT_EQ("PUT", res->body);
  5551. }
  5552. // Pre-compression logging tests
  5553. TEST_F(ServerTest, PreCompressionLogging) {
  5554. // Test data for compression (matches the actual /compress endpoint content)
  5555. const std::string test_content =
  5556. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5557. "3456789012345678901234567890";
  5558. // Variables to capture logging data
  5559. std::string pre_compression_body;
  5560. std::string pre_compression_content_type;
  5561. std::string pre_compression_content_encoding;
  5562. std::string post_compression_body;
  5563. std::string post_compression_content_type;
  5564. std::string post_compression_content_encoding;
  5565. // Set up pre-compression logger
  5566. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5567. const Response &res) {
  5568. pre_compression_body = res.body;
  5569. pre_compression_content_type = res.get_header_value("Content-Type");
  5570. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5571. });
  5572. // Set up post-compression logger
  5573. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5574. post_compression_body = res.body;
  5575. post_compression_content_type = res.get_header_value("Content-Type");
  5576. post_compression_content_encoding =
  5577. res.get_header_value("Content-Encoding");
  5578. });
  5579. // Test with gzip compression
  5580. Headers headers;
  5581. headers.emplace("Accept-Encoding", "gzip");
  5582. auto res = cli_.Get("/compress", headers);
  5583. // Verify response was compressed
  5584. ASSERT_TRUE(res);
  5585. EXPECT_EQ(StatusCode::OK_200, res->status);
  5586. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5587. // Verify pre-compression logger captured uncompressed content
  5588. EXPECT_EQ(test_content, pre_compression_body);
  5589. EXPECT_EQ("text/plain", pre_compression_content_type);
  5590. EXPECT_TRUE(pre_compression_content_encoding
  5591. .empty()); // No encoding header before compression
  5592. // Verify post-compression logger captured compressed content
  5593. EXPECT_NE(test_content,
  5594. post_compression_body); // Should be different after compression
  5595. EXPECT_EQ("text/plain", post_compression_content_type);
  5596. EXPECT_EQ("gzip", post_compression_content_encoding);
  5597. // Verify compressed content is smaller
  5598. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5599. }
  5600. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5601. const std::string test_content =
  5602. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5603. "3456789012345678901234567890";
  5604. std::string pre_compression_body;
  5605. std::string post_compression_body;
  5606. svr_.set_pre_compression_logger(
  5607. [&](const Request & /*req*/, const Response &res) {
  5608. pre_compression_body = res.body;
  5609. });
  5610. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5611. post_compression_body = res.body;
  5612. });
  5613. Headers headers;
  5614. headers.emplace("Accept-Encoding", "br");
  5615. auto res = cli_.Get("/compress", headers);
  5616. ASSERT_TRUE(res);
  5617. EXPECT_EQ(StatusCode::OK_200, res->status);
  5618. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5619. // Verify pre-compression content is uncompressed
  5620. EXPECT_EQ(test_content, pre_compression_body);
  5621. // Verify post-compression content is compressed
  5622. EXPECT_NE(test_content, post_compression_body);
  5623. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5624. }
  5625. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5626. const std::string test_content =
  5627. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5628. "3456789012345678901234567890";
  5629. std::string pre_compression_body;
  5630. std::string post_compression_body;
  5631. svr_.set_pre_compression_logger(
  5632. [&](const Request & /*req*/, const Response &res) {
  5633. pre_compression_body = res.body;
  5634. });
  5635. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5636. post_compression_body = res.body;
  5637. });
  5638. // Request without compression (use /nocompress endpoint)
  5639. Headers headers;
  5640. auto res = cli_.Get("/nocompress", headers);
  5641. ASSERT_TRUE(res);
  5642. EXPECT_EQ(StatusCode::OK_200, res->status);
  5643. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5644. // Pre-compression logger should not be called when no compression is applied
  5645. EXPECT_TRUE(
  5646. pre_compression_body.empty()); // Pre-compression logger not called
  5647. EXPECT_EQ(
  5648. test_content,
  5649. post_compression_body); // Post-compression logger captures final content
  5650. }
  5651. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5652. const std::string test_content =
  5653. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5654. "3456789012345678901234567890";
  5655. std::string pre_compression_body;
  5656. bool pre_logger_called = false;
  5657. // Set only pre-compression logger
  5658. svr_.set_pre_compression_logger(
  5659. [&](const Request & /*req*/, const Response &res) {
  5660. pre_compression_body = res.body;
  5661. pre_logger_called = true;
  5662. });
  5663. Headers headers;
  5664. headers.emplace("Accept-Encoding", "gzip");
  5665. auto res = cli_.Get("/compress", headers);
  5666. ASSERT_TRUE(res);
  5667. EXPECT_EQ(StatusCode::OK_200, res->status);
  5668. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5669. // Verify pre-compression logger was called
  5670. EXPECT_TRUE(pre_logger_called);
  5671. EXPECT_EQ(test_content, pre_compression_body);
  5672. }
  5673. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5674. {
  5675. // Test with Expect: 100-continue header - success case
  5676. // Server returns 100 Continue, client sends body, server returns 200 OK
  5677. Request req;
  5678. req.method = "POST";
  5679. req.path = "/post-large";
  5680. req.set_header("Expect", "100-continue");
  5681. req.body = LARGE_DATA;
  5682. Response res;
  5683. auto error = Error::Success;
  5684. cli_.set_keep_alive(true);
  5685. auto ret = cli_.send(req, res, error);
  5686. EXPECT_TRUE(ret);
  5687. EXPECT_EQ(StatusCode::OK_200, res.status);
  5688. EXPECT_EQ(LARGE_DATA, res.body);
  5689. }
  5690. {
  5691. // Test with Expect: 100-continue header - error case
  5692. // Client should not send the body when server returns an error
  5693. Request req;
  5694. req.method = "POST";
  5695. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5696. req.set_header("Expect", "100-continue");
  5697. req.body = LARGE_DATA;
  5698. Response res;
  5699. auto error = Error::Success;
  5700. auto start = std::chrono::high_resolution_clock::now();
  5701. cli_.set_keep_alive(true);
  5702. auto ret = cli_.send(req, res, error);
  5703. auto end = std::chrono::high_resolution_clock::now();
  5704. auto elapsed =
  5705. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5706. .count();
  5707. // With Expect: 100-continue, request completes successfully but with error
  5708. EXPECT_TRUE(ret);
  5709. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5710. EXPECT_EQ("close", res.get_header_value("Connection"));
  5711. EXPECT_FALSE(cli_.is_socket_open());
  5712. EXPECT_LE(elapsed, 200);
  5713. }
  5714. {
  5715. // Send an extra GET request to ensure error recovery without hanging
  5716. Request req;
  5717. req.method = "GET";
  5718. req.path = "/hi";
  5719. auto start = std::chrono::high_resolution_clock::now();
  5720. auto res = cli_.send(req);
  5721. auto end = std::chrono::high_resolution_clock::now();
  5722. auto elapsed =
  5723. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5724. .count();
  5725. ASSERT_TRUE(res);
  5726. EXPECT_EQ(StatusCode::OK_200, res->status);
  5727. EXPECT_EQ("Hello World!", res->body);
  5728. EXPECT_LE(elapsed, 500);
  5729. }
  5730. }
  5731. TEST(ZstdDecompressor, ChunkedDecompression) {
  5732. std::string data;
  5733. for (size_t i = 0; i < 32 * 1024; ++i) {
  5734. data.push_back(static_cast<char>('a' + i % 26));
  5735. }
  5736. std::string compressed_data;
  5737. {
  5738. httplib::detail::zstd_compressor compressor;
  5739. bool result = compressor.compress(
  5740. data.data(), data.size(),
  5741. /*last=*/true,
  5742. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5743. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5744. compressed_data_size);
  5745. return true;
  5746. });
  5747. ASSERT_TRUE(result);
  5748. }
  5749. std::string decompressed_data;
  5750. {
  5751. httplib::detail::zstd_decompressor decompressor;
  5752. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5753. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5754. size_t chunk_size = 130;
  5755. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5756. chunk_begin += chunk_size) {
  5757. size_t current_chunk_size =
  5758. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5759. bool result = decompressor.decompress(
  5760. compressed_data.data() + chunk_begin, current_chunk_size,
  5761. [&](const char *decompressed_data_chunk,
  5762. size_t decompressed_data_chunk_size) {
  5763. decompressed_data.insert(decompressed_data.size(),
  5764. decompressed_data_chunk,
  5765. decompressed_data_chunk_size);
  5766. return true;
  5767. });
  5768. ASSERT_TRUE(result);
  5769. }
  5770. }
  5771. ASSERT_EQ(data, decompressed_data);
  5772. }
  5773. TEST(ZstdDecompressor, Decompress) {
  5774. std::string original_text = "Compressed with ZSTD";
  5775. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5776. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5777. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5778. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5779. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5780. std::string decompressed_data;
  5781. {
  5782. httplib::detail::zstd_decompressor decompressor;
  5783. bool result = decompressor.decompress(
  5784. compressed_data.data(), compressed_data.size(),
  5785. [&](const char *decompressed_data_chunk,
  5786. size_t decompressed_data_chunk_size) {
  5787. decompressed_data.insert(decompressed_data.size(),
  5788. decompressed_data_chunk,
  5789. decompressed_data_chunk_size);
  5790. return true;
  5791. });
  5792. ASSERT_TRUE(result);
  5793. }
  5794. ASSERT_EQ(original_text, decompressed_data);
  5795. }
  5796. #endif
  5797. // Sends a raw request to a server listening at HOST:PORT.
  5798. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5799. std::string *resp = nullptr) {
  5800. auto error = Error::Success;
  5801. auto client_sock = detail::create_client_socket(
  5802. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5803. /*connection_timeout_sec=*/5, 0,
  5804. /*read_timeout_sec=*/5, 0,
  5805. /*write_timeout_sec=*/5, 0, std::string(), error);
  5806. if (client_sock == INVALID_SOCKET) { return false; }
  5807. auto ret = detail::process_client_socket(
  5808. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5809. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5810. if (req.size() !=
  5811. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5812. return false;
  5813. }
  5814. char buf[512];
  5815. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5816. while (line_reader.getline()) {
  5817. if (resp) { *resp += line_reader.ptr(); }
  5818. }
  5819. return true;
  5820. });
  5821. detail::close_socket(client_sock);
  5822. return ret;
  5823. }
  5824. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5825. Server svr;
  5826. std::string header_value;
  5827. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5828. header_value = req.get_header_value("foo");
  5829. res.set_content("ok", "text/plain");
  5830. });
  5831. thread t = thread([&] { svr.listen(HOST, PORT); });
  5832. auto se = detail::scope_exit([&] {
  5833. svr.stop();
  5834. t.join();
  5835. ASSERT_FALSE(svr.is_running());
  5836. });
  5837. svr.wait_until_ready();
  5838. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5839. // like characters are not treated the same - use vertical tab and escape.
  5840. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5841. "foo: \t \v bar \x1B\t \r\n"
  5842. "Connection: close\r\n"
  5843. "\r\n";
  5844. std::string res;
  5845. ASSERT_TRUE(send_request(5, req, &res));
  5846. EXPECT_EQ(header_value, "");
  5847. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5848. }
  5849. // Sends a raw request and verifies that there isn't a crash or exception.
  5850. static void test_raw_request(const std::string &req,
  5851. std::string *out = nullptr) {
  5852. Server svr;
  5853. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5854. res.set_content("ok", "text/plain");
  5855. });
  5856. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5857. res.set_content("ok", "text/plain");
  5858. });
  5859. svr.Get("/header_field_value_check",
  5860. [&](const Request & /*req*/, Response &res) {
  5861. res.set_content("ok", "text/plain");
  5862. });
  5863. // Server read timeout must be longer than the client read timeout for the
  5864. // bug to reproduce, probably to force the server to process a request
  5865. // without a trailing blank line.
  5866. const time_t client_read_timeout_sec = 1;
  5867. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5868. bool listen_thread_ok = false;
  5869. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5870. auto se = detail::scope_exit([&] {
  5871. svr.stop();
  5872. t.join();
  5873. ASSERT_FALSE(svr.is_running());
  5874. EXPECT_TRUE(listen_thread_ok);
  5875. });
  5876. svr.wait_until_ready();
  5877. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5878. }
  5879. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5880. // A certain header line causes an exception if the header property is parsed
  5881. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5882. test_raw_request(
  5883. "GET /hi HTTP/1.1\r\n"
  5884. " : "
  5885. " "
  5886. " ");
  5887. }
  5888. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5889. // A certain header line causes an exception if the header property *name* is
  5890. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5891. // greedy matcher and requires backtracking when there are a lot of ":"
  5892. // characters.
  5893. // This occurs with libc++ but not libstdc++.
  5894. test_raw_request(
  5895. "GET /hi HTTP/1.1\r\n"
  5896. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5897. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5898. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5899. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5900. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5901. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5902. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5903. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5904. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5905. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5906. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5907. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5908. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5909. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5910. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5911. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5912. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5913. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5914. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5915. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5916. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5917. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5918. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5919. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5920. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5921. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5922. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5923. "&&&%%%");
  5924. }
  5925. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5926. // Make sure this doesn't crash the server.
  5927. // In a previous version of the header line regex, the "\r" rendered the line
  5928. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5929. // a new position where the leading white space ended and the field value
  5930. // began.
  5931. // The crash occurs with libc++ but not libstdc++.
  5932. test_raw_request("GET /hi HTTP/1.1\r\n"
  5933. "a:" +
  5934. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5935. "\r\n"
  5936. "\r\n");
  5937. }
  5938. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5939. std::string out;
  5940. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5941. "Content-Type: text/plain\r\n"
  5942. "Transfer-Encoding: chunked\r\n"
  5943. "\r\n"
  5944. "nothex\r\n",
  5945. &out);
  5946. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5947. }
  5948. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5949. std::string out;
  5950. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5951. "Content-Type: text/plain\r\n"
  5952. "Transfer-Encoding: chunked\r\n"
  5953. "\r\n"
  5954. "3\r\n"
  5955. "xyz\r\n"
  5956. "NaN\r\n",
  5957. &out);
  5958. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5959. }
  5960. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5961. std::string out;
  5962. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5963. "Content-Type: text/plain\r\n"
  5964. "Transfer-Encoding: chunked\r\n"
  5965. "\r\n"
  5966. // Length is too large for 64 bits.
  5967. "1ffffffffffffffff\r\n"
  5968. "xyz\r\n",
  5969. &out);
  5970. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5971. }
  5972. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5973. test_raw_request("GET /hi HTTP/1.1\r\n"
  5974. "Content-Type: text/plain\r\n\r");
  5975. }
  5976. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5977. std::string out;
  5978. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5979. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5980. }
  5981. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5982. Server svr;
  5983. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5984. EXPECT_TRUE(!req.remote_addr.empty());
  5985. });
  5986. thread t = thread([&] { svr.listen(HOST, PORT); });
  5987. auto se = detail::scope_exit([&] {
  5988. svr.stop();
  5989. t.join();
  5990. ASSERT_FALSE(svr.is_running());
  5991. });
  5992. svr.wait_until_ready();
  5993. // Send an invalid request line to trigger Bad Request
  5994. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5995. std::string out;
  5996. ASSERT_TRUE(send_request(5, bad_req, &out));
  5997. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5998. }
  5999. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6000. std::string out;
  6001. std::string request(
  6002. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6003. test_raw_request(request, &out);
  6004. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6005. }
  6006. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6007. std::string out;
  6008. std::string request(
  6009. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6010. test_raw_request(request, &out);
  6011. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6012. }
  6013. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6014. std::string out;
  6015. std::string request(
  6016. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6017. test_raw_request(request, &out);
  6018. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6019. }
  6020. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6021. std::string out;
  6022. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6023. "Test: \r\n\r\n",
  6024. &out);
  6025. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6026. }
  6027. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6028. Server svr;
  6029. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6030. res.set_header("Cache-Control", "no-cache");
  6031. res.set_chunked_content_provider(
  6032. "text/event-stream", [](size_t offset, DataSink &sink) {
  6033. std::string s = "data:";
  6034. s += std::to_string(offset);
  6035. s += "\n\n";
  6036. auto ret = sink.write(s.data(), s.size());
  6037. EXPECT_TRUE(ret);
  6038. std::this_thread::sleep_for(std::chrono::seconds(1));
  6039. return true;
  6040. });
  6041. });
  6042. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6043. svr.wait_until_ready();
  6044. Client client(HOST, PORT);
  6045. const Headers headers = {{"Accept", "text/event-stream"}};
  6046. auto get_thread = std::thread([&client, &headers]() {
  6047. auto res = client.Get(
  6048. "/events", headers,
  6049. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6050. });
  6051. auto se = detail::scope_exit([&] {
  6052. svr.stop();
  6053. get_thread.join();
  6054. listen_thread.join();
  6055. ASSERT_FALSE(svr.is_running());
  6056. });
  6057. // Give GET time to get a few messages.
  6058. std::this_thread::sleep_for(std::chrono::seconds(2));
  6059. }
  6060. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6061. httplib::Server svr;
  6062. svr.Post("/hi",
  6063. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6064. res.status = StatusCode::OK_200;
  6065. });
  6066. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6067. svr.wait_until_ready();
  6068. Client cli(HOST, PORT);
  6069. auto res = cli.Post("/hi", "data", "text/plain");
  6070. ASSERT_TRUE(res);
  6071. EXPECT_EQ(StatusCode::OK_200, res->status);
  6072. svr.stop();
  6073. thread.join();
  6074. ASSERT_FALSE(svr.is_running());
  6075. res = cli.Post("/hi", "data", "text/plain");
  6076. ASSERT_FALSE(res);
  6077. }
  6078. TEST(ServerStopTest, ListenFailure) {
  6079. Server svr;
  6080. auto t = thread([&]() {
  6081. auto ret = svr.listen("????", PORT);
  6082. EXPECT_FALSE(ret);
  6083. });
  6084. svr.wait_until_ready();
  6085. svr.stop();
  6086. t.join();
  6087. }
  6088. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6089. TEST(ServerStopTest, Decommision) {
  6090. Server svr;
  6091. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6092. for (int i = 0; i < 4; i++) {
  6093. auto is_even = !(i % 2);
  6094. std::thread t{[&] {
  6095. try {
  6096. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6097. if (is_even) {
  6098. throw std::runtime_error("Some thing that happens to go wrong.");
  6099. }
  6100. svr.listen(HOST, PORT);
  6101. } catch (...) { svr.decommission(); }
  6102. }};
  6103. svr.wait_until_ready();
  6104. // Server is up
  6105. {
  6106. Client cli(HOST, PORT);
  6107. auto res = cli.Get("/hi");
  6108. if (is_even) {
  6109. EXPECT_FALSE(res);
  6110. } else {
  6111. EXPECT_TRUE(res);
  6112. EXPECT_EQ("hi...", res->body);
  6113. }
  6114. }
  6115. svr.stop();
  6116. t.join();
  6117. // Server is down...
  6118. {
  6119. Client cli(HOST, PORT);
  6120. auto res = cli.Get("/hi");
  6121. EXPECT_FALSE(res);
  6122. }
  6123. }
  6124. }
  6125. #endif
  6126. // Helper function for string body upload progress tests
  6127. template <typename SetupHandler, typename ClientCall>
  6128. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6129. ClientCall &&client_call,
  6130. const string &body) {
  6131. Server svr;
  6132. setup_handler(svr);
  6133. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6134. auto se = detail::scope_exit([&] {
  6135. svr.stop();
  6136. t.join();
  6137. });
  6138. svr.wait_until_ready();
  6139. Client cli(HOST, PORT);
  6140. vector<uint64_t> progress_values;
  6141. bool progress_called = false;
  6142. auto res =
  6143. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6144. progress_values.push_back(current);
  6145. progress_called = true;
  6146. return true;
  6147. });
  6148. ASSERT_TRUE(res);
  6149. EXPECT_EQ(200, res->status);
  6150. EXPECT_TRUE(progress_called);
  6151. }
  6152. TEST(UploadProgressTest, PostStringBodyBasic) {
  6153. TestStringBodyUploadProgress(
  6154. [](Server &svr) {
  6155. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6156. res.set_content("received", "text/plain");
  6157. });
  6158. },
  6159. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6160. return cli.Post("/test", body, "text/plain", progress_callback);
  6161. },
  6162. "test data for upload progress");
  6163. }
  6164. TEST(UploadProgressTest, PutStringBodyBasic) {
  6165. TestStringBodyUploadProgress(
  6166. [](Server &svr) {
  6167. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6168. res.set_content("put received", "text/plain");
  6169. });
  6170. },
  6171. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6172. return cli.Put("/test", body, "text/plain", progress_callback);
  6173. },
  6174. "put test data for upload progress");
  6175. }
  6176. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6177. TestStringBodyUploadProgress(
  6178. [](Server &svr) {
  6179. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6180. res.set_content("patch received", "text/plain");
  6181. });
  6182. },
  6183. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6184. return cli.Patch("/test", body, "text/plain", progress_callback);
  6185. },
  6186. "patch test data for upload progress");
  6187. }
  6188. // Helper function for content provider upload progress tests
  6189. template <typename SetupHandler, typename ClientCall>
  6190. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6191. ClientCall &&client_call) {
  6192. Server svr;
  6193. setup_handler(svr);
  6194. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6195. auto se = detail::scope_exit([&] {
  6196. svr.stop();
  6197. t.join();
  6198. });
  6199. svr.wait_until_ready();
  6200. Client cli(HOST, PORT);
  6201. vector<uint64_t> progress_values;
  6202. auto res =
  6203. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6204. progress_values.push_back(current);
  6205. return true;
  6206. });
  6207. ASSERT_TRUE(res);
  6208. EXPECT_EQ(200, res->status);
  6209. EXPECT_FALSE(progress_values.empty());
  6210. }
  6211. TEST(UploadProgressTest, PostContentProviderProgress) {
  6212. TestContentProviderUploadProgress(
  6213. [](Server &svr) {
  6214. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6215. res.set_content("provider received", "text/plain");
  6216. });
  6217. },
  6218. [](Client &cli, UploadProgress progress_callback) {
  6219. return cli.Post(
  6220. "/test", 10,
  6221. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6222. sink.os << "test data";
  6223. return true;
  6224. },
  6225. "text/plain", progress_callback);
  6226. });
  6227. }
  6228. // Helper function for multipart upload progress tests
  6229. template <typename SetupHandler, typename ClientCall>
  6230. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6231. ClientCall &&client_call,
  6232. const string &endpoint) {
  6233. Server svr;
  6234. setup_handler(svr);
  6235. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6236. auto se = detail::scope_exit([&] {
  6237. svr.stop();
  6238. t.join();
  6239. });
  6240. svr.wait_until_ready();
  6241. Client cli(HOST, PORT);
  6242. vector<uint64_t> progress_values;
  6243. UploadFormDataItems items = {
  6244. {"field1", "value1", "", ""},
  6245. {"field2", "longer value for progress tracking test", "", ""},
  6246. {"file1", "file content data for upload progress", "test.txt",
  6247. "text/plain"}};
  6248. auto res = client_call(cli, endpoint, items,
  6249. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6250. progress_values.push_back(current);
  6251. return true;
  6252. });
  6253. ASSERT_TRUE(res);
  6254. EXPECT_EQ(200, res->status);
  6255. EXPECT_FALSE(progress_values.empty());
  6256. }
  6257. TEST(UploadProgressTest, PostMultipartProgress) {
  6258. TestMultipartUploadProgress(
  6259. [](Server &svr) {
  6260. svr.Post("/multipart", [](const Request &req, Response &res) {
  6261. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6262. res.set_content("multipart received", "text/plain");
  6263. });
  6264. },
  6265. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6266. UploadProgress progress_callback) {
  6267. return cli.Post(endpoint, items, progress_callback);
  6268. },
  6269. "/multipart");
  6270. }
  6271. // Helper function for basic download progress tests
  6272. template <typename SetupHandler, typename ClientCall>
  6273. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6274. ClientCall &&client_call, const string &endpoint,
  6275. size_t expected_content_size) {
  6276. Server svr;
  6277. setup_handler(svr);
  6278. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6279. auto se = detail::scope_exit([&] {
  6280. svr.stop();
  6281. t.join();
  6282. });
  6283. svr.wait_until_ready();
  6284. Client cli(HOST, PORT);
  6285. vector<uint64_t> progress_values;
  6286. auto res = client_call(cli, endpoint,
  6287. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6288. progress_values.push_back(current);
  6289. return true;
  6290. });
  6291. ASSERT_TRUE(res);
  6292. EXPECT_EQ(200, res->status);
  6293. EXPECT_FALSE(progress_values.empty());
  6294. EXPECT_EQ(expected_content_size, res->body.size());
  6295. }
  6296. TEST(DownloadProgressTest, GetBasic) {
  6297. TestBasicDownloadProgress(
  6298. [](Server &svr) {
  6299. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6300. string content(1000, 'D');
  6301. res.set_content(content, "text/plain");
  6302. });
  6303. },
  6304. [](Client &cli, const string &endpoint,
  6305. DownloadProgress progress_callback) {
  6306. return cli.Get(endpoint, progress_callback);
  6307. },
  6308. "/download", 1000u);
  6309. }
  6310. // Helper function for content receiver download progress tests
  6311. template <typename SetupHandler, typename ClientCall>
  6312. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6313. ClientCall &&client_call,
  6314. const string &endpoint,
  6315. size_t expected_content_size) {
  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. string received_body;
  6327. auto res = client_call(
  6328. cli, endpoint,
  6329. [&](const char *data, size_t data_length) -> bool {
  6330. received_body.append(data, data_length);
  6331. return true;
  6332. },
  6333. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6334. progress_values.push_back(current);
  6335. return true;
  6336. });
  6337. ASSERT_TRUE(res);
  6338. EXPECT_EQ(200, res->status);
  6339. EXPECT_FALSE(progress_values.empty());
  6340. EXPECT_EQ(expected_content_size, received_body.size());
  6341. EXPECT_TRUE(res->body.empty());
  6342. }
  6343. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6344. TestContentReceiverDownloadProgress(
  6345. [](Server &svr) {
  6346. svr.Get("/download-receiver",
  6347. [](const Request & /*req*/, Response &res) {
  6348. string content(2000, 'R');
  6349. res.set_content(content, "text/plain");
  6350. });
  6351. },
  6352. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6353. DownloadProgress progress_callback) {
  6354. return cli.Get(endpoint, content_receiver, progress_callback);
  6355. },
  6356. "/download-receiver", 2000u);
  6357. }
  6358. TEST(StreamingTest, NoContentLengthStreaming) {
  6359. Server svr;
  6360. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6361. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6362. if (offset < 6) {
  6363. sink.os << (offset < 3 ? "a" : "b");
  6364. } else {
  6365. sink.done();
  6366. }
  6367. return true;
  6368. });
  6369. });
  6370. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6371. auto listen_se = detail::scope_exit([&] {
  6372. svr.stop();
  6373. listen_thread.join();
  6374. ASSERT_FALSE(svr.is_running());
  6375. });
  6376. svr.wait_until_ready();
  6377. Client client(HOST, PORT);
  6378. auto get_thread = std::thread([&client]() {
  6379. std::string s;
  6380. auto res =
  6381. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6382. s += std::string(data, len);
  6383. return true;
  6384. });
  6385. ASSERT_TRUE(res);
  6386. EXPECT_EQ(StatusCode::OK_200, res->status);
  6387. EXPECT_EQ("aaabbb", s);
  6388. });
  6389. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6390. // Give GET time to get a few messages.
  6391. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6392. }
  6393. TEST(MountTest, Unmount) {
  6394. Server svr;
  6395. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6396. auto se = detail::scope_exit([&] {
  6397. svr.stop();
  6398. listen_thread.join();
  6399. ASSERT_FALSE(svr.is_running());
  6400. });
  6401. svr.wait_until_ready();
  6402. Client cli("localhost", PORT);
  6403. svr.set_mount_point("/mount2", "./www2");
  6404. auto res = cli.Get("/");
  6405. ASSERT_TRUE(res);
  6406. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6407. res = cli.Get("/mount2/dir/test.html");
  6408. ASSERT_TRUE(res);
  6409. EXPECT_EQ(StatusCode::OK_200, res->status);
  6410. svr.set_mount_point("/", "./www");
  6411. res = cli.Get("/dir/");
  6412. ASSERT_TRUE(res);
  6413. EXPECT_EQ(StatusCode::OK_200, res->status);
  6414. svr.remove_mount_point("/");
  6415. res = cli.Get("/dir/");
  6416. ASSERT_TRUE(res);
  6417. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6418. svr.remove_mount_point("/mount2");
  6419. res = cli.Get("/mount2/dir/test.html");
  6420. ASSERT_TRUE(res);
  6421. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6422. }
  6423. TEST(MountTest, Redicect) {
  6424. Server svr;
  6425. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6426. auto se = detail::scope_exit([&] {
  6427. svr.stop();
  6428. listen_thread.join();
  6429. ASSERT_FALSE(svr.is_running());
  6430. });
  6431. svr.set_mount_point("/", "./www");
  6432. svr.wait_until_ready();
  6433. Client cli("localhost", PORT);
  6434. auto res = cli.Get("/dir/");
  6435. ASSERT_TRUE(res);
  6436. EXPECT_EQ(StatusCode::OK_200, res->status);
  6437. res = cli.Get("/dir");
  6438. ASSERT_TRUE(res);
  6439. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6440. res = cli.Get("/file");
  6441. ASSERT_TRUE(res);
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. res = cli.Get("/file/");
  6444. ASSERT_TRUE(res);
  6445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6446. cli.set_follow_location(true);
  6447. res = cli.Get("/dir");
  6448. ASSERT_TRUE(res);
  6449. EXPECT_EQ(StatusCode::OK_200, res->status);
  6450. }
  6451. TEST(MountTest, MultibytesPathName) {
  6452. Server svr;
  6453. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6454. auto se = detail::scope_exit([&] {
  6455. svr.stop();
  6456. listen_thread.join();
  6457. ASSERT_FALSE(svr.is_running());
  6458. });
  6459. svr.set_mount_point("/", "./www");
  6460. svr.wait_until_ready();
  6461. Client cli("localhost", PORT);
  6462. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6463. ASSERT_TRUE(res);
  6464. EXPECT_EQ(StatusCode::OK_200, res->status);
  6465. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6466. }
  6467. TEST(KeepAliveTest, ReadTimeout) {
  6468. Server svr;
  6469. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6470. std::this_thread::sleep_for(std::chrono::seconds(2));
  6471. res.set_content("a", "text/plain");
  6472. });
  6473. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6474. res.set_content("b", "text/plain");
  6475. });
  6476. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6477. auto se = detail::scope_exit([&] {
  6478. svr.stop();
  6479. listen_thread.join();
  6480. ASSERT_FALSE(svr.is_running());
  6481. });
  6482. svr.wait_until_ready();
  6483. Client cli("localhost", PORT);
  6484. cli.set_keep_alive(true);
  6485. cli.set_read_timeout(std::chrono::seconds(1));
  6486. auto resa = cli.Get("/a");
  6487. ASSERT_FALSE(resa);
  6488. EXPECT_EQ(Error::Read, resa.error());
  6489. auto resb = cli.Get("/b");
  6490. ASSERT_TRUE(resb);
  6491. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6492. EXPECT_EQ("b", resb->body);
  6493. }
  6494. TEST(KeepAliveTest, MaxCount) {
  6495. size_t keep_alive_max_count = 3;
  6496. Server svr;
  6497. svr.set_keep_alive_max_count(keep_alive_max_count);
  6498. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6499. res.set_content("Hello World!", "text/plain");
  6500. });
  6501. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6502. auto se = detail::scope_exit([&] {
  6503. svr.stop();
  6504. listen_thread.join();
  6505. ASSERT_FALSE(svr.is_running());
  6506. });
  6507. svr.wait_until_ready();
  6508. Client cli(HOST, PORT);
  6509. cli.set_keep_alive(true);
  6510. for (size_t i = 0; i < 5; i++) {
  6511. auto result = cli.Get("/hi");
  6512. ASSERT_TRUE(result);
  6513. EXPECT_EQ(StatusCode::OK_200, result->status);
  6514. if (i == keep_alive_max_count - 1) {
  6515. EXPECT_EQ("close", result->get_header_value("Connection"));
  6516. } else {
  6517. EXPECT_FALSE(result->has_header("Connection"));
  6518. }
  6519. }
  6520. }
  6521. TEST(KeepAliveTest, Issue1041) {
  6522. Server svr;
  6523. svr.set_keep_alive_timeout(3);
  6524. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6525. res.set_content("Hello World!", "text/plain");
  6526. });
  6527. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6528. auto se = detail::scope_exit([&] {
  6529. svr.stop();
  6530. listen_thread.join();
  6531. ASSERT_FALSE(svr.is_running());
  6532. });
  6533. svr.wait_until_ready();
  6534. Client cli(HOST, PORT);
  6535. cli.set_keep_alive(true);
  6536. auto result = cli.Get("/hi");
  6537. ASSERT_TRUE(result);
  6538. EXPECT_EQ(StatusCode::OK_200, result->status);
  6539. std::this_thread::sleep_for(std::chrono::seconds(5));
  6540. result = cli.Get("/hi");
  6541. ASSERT_TRUE(result);
  6542. EXPECT_EQ(StatusCode::OK_200, result->status);
  6543. }
  6544. TEST(KeepAliveTest, Issue1959) {
  6545. Server svr;
  6546. svr.set_keep_alive_timeout(5);
  6547. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6548. res.set_content("a", "text/plain");
  6549. });
  6550. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6551. auto se = detail::scope_exit([&] {
  6552. if (!svr.is_running()) return;
  6553. svr.stop();
  6554. listen_thread.join();
  6555. ASSERT_FALSE(svr.is_running());
  6556. });
  6557. svr.wait_until_ready();
  6558. Client cli("localhost", PORT);
  6559. cli.set_keep_alive(true);
  6560. using namespace std::chrono;
  6561. auto start = steady_clock::now();
  6562. cli.Get("/a");
  6563. svr.stop();
  6564. listen_thread.join();
  6565. auto end = steady_clock::now();
  6566. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6567. EXPECT_LT(elapsed, 5000);
  6568. }
  6569. #ifdef CPPHTTPLIB_SSL_ENABLED
  6570. TEST(KeepAliveTest, SSLClientReconnection) {
  6571. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6572. ASSERT_TRUE(svr.is_valid());
  6573. svr.set_keep_alive_timeout(1);
  6574. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6575. res.set_content("Hello World!", "text/plain");
  6576. });
  6577. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6578. auto se = detail::scope_exit([&] {
  6579. svr.stop();
  6580. listen_thread.join();
  6581. ASSERT_FALSE(svr.is_running());
  6582. });
  6583. svr.wait_until_ready();
  6584. SSLClient cli(HOST, PORT);
  6585. cli.enable_server_certificate_verification(false);
  6586. cli.set_keep_alive(true);
  6587. auto result = cli.Get("/hi");
  6588. ASSERT_TRUE(result);
  6589. EXPECT_EQ(StatusCode::OK_200, result->status);
  6590. result = cli.Get("/hi");
  6591. ASSERT_TRUE(result);
  6592. EXPECT_EQ(StatusCode::OK_200, result->status);
  6593. std::this_thread::sleep_for(std::chrono::seconds(2));
  6594. // Recoonect
  6595. result = cli.Get("/hi");
  6596. ASSERT_TRUE(result);
  6597. EXPECT_EQ(StatusCode::OK_200, result->status);
  6598. result = cli.Get("/hi");
  6599. ASSERT_TRUE(result);
  6600. EXPECT_EQ(StatusCode::OK_200, result->status);
  6601. }
  6602. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6603. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6604. ASSERT_TRUE(svr.is_valid());
  6605. svr.set_keep_alive_timeout(1);
  6606. std::string content = "reconnect";
  6607. svr.Post("/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. SSLClient cli(HOST, PORT);
  6618. cli.enable_server_certificate_verification(false);
  6619. cli.set_keep_alive(true);
  6620. auto result = cli.Post(
  6621. "/hi", content.size(),
  6622. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6623. sink.write(content.c_str(), content.size());
  6624. return true;
  6625. },
  6626. "text/plain");
  6627. ASSERT_TRUE(result);
  6628. EXPECT_EQ(200, result->status);
  6629. std::this_thread::sleep_for(std::chrono::seconds(2));
  6630. // Recoonect
  6631. result = cli.Post(
  6632. "/hi", content.size(),
  6633. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6634. sink.write(content.c_str(), content.size());
  6635. return true;
  6636. },
  6637. "text/plain");
  6638. ASSERT_TRUE(result);
  6639. EXPECT_EQ(200, result->status);
  6640. result = cli.Post(
  6641. "/hi", content.size(),
  6642. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6643. sink.write(content.c_str(), content.size());
  6644. return true;
  6645. },
  6646. "text/plain");
  6647. ASSERT_TRUE(result);
  6648. EXPECT_EQ(200, result->status);
  6649. }
  6650. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6651. using namespace httplib::tls;
  6652. {
  6653. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6654. ASSERT_TRUE(svr.is_valid());
  6655. svr.Get("/sni", [&](const Request &req, Response &res) {
  6656. std::string expected = req.sni();
  6657. EXPECT_EQ(expected, req.get_param_value("expected"));
  6658. res.set_content("ok", "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. {
  6668. SSLClient cli("localhost", PORT);
  6669. cli.enable_server_certificate_verification(false);
  6670. auto res = cli.Get("/sni?expected=localhost");
  6671. ASSERT_TRUE(res);
  6672. }
  6673. {
  6674. SSLClient cli("::1", PORT);
  6675. cli.enable_server_certificate_verification(false);
  6676. auto res = cli.Get("/sni?expected=");
  6677. // NOTE: This may fail if the server is listening on IPv4 only
  6678. // (e.g., when localhost resolves to 127.0.0.1 only)
  6679. if (res) {
  6680. EXPECT_EQ(StatusCode::OK_200, res->status);
  6681. } else {
  6682. EXPECT_EQ(Error::Connection, res.error());
  6683. }
  6684. }
  6685. }
  6686. }
  6687. #endif
  6688. TEST(ClientProblemDetectionTest, ContentProvider) {
  6689. Server svr;
  6690. size_t content_length = 1024 * 1024;
  6691. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6692. res.set_content_provider(
  6693. content_length, "text/plain",
  6694. [&](size_t offset, size_t length, DataSink &sink) {
  6695. auto out_len = std::min(length, static_cast<size_t>(1024));
  6696. std::string out(out_len, '@');
  6697. sink.write(out.data(), out_len);
  6698. return offset < 4096;
  6699. },
  6700. [](bool success) { ASSERT_FALSE(success); });
  6701. });
  6702. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6703. res.set_content_provider(
  6704. 0, "text/plain",
  6705. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6706. EXPECT_TRUE(false);
  6707. return true;
  6708. },
  6709. [](bool success) { ASSERT_FALSE(success); });
  6710. });
  6711. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6712. auto se = detail::scope_exit([&] {
  6713. svr.stop();
  6714. listen_thread.join();
  6715. ASSERT_FALSE(svr.is_running());
  6716. });
  6717. svr.wait_until_ready();
  6718. Client cli("localhost", PORT);
  6719. {
  6720. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6721. size_t /*data_length*/) { return false; });
  6722. ASSERT_FALSE(res);
  6723. }
  6724. {
  6725. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6726. size_t /*data_length*/) { return false; });
  6727. ASSERT_TRUE(res);
  6728. }
  6729. }
  6730. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6731. Server svr;
  6732. svr.set_error_handler([](Request const &, Response &res) -> void {
  6733. res.set_chunked_content_provider(
  6734. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6735. sink.os << "hello";
  6736. sink.os << "world";
  6737. sink.done();
  6738. return true;
  6739. });
  6740. });
  6741. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6742. auto se = detail::scope_exit([&] {
  6743. svr.stop();
  6744. listen_thread.join();
  6745. ASSERT_FALSE(svr.is_running());
  6746. });
  6747. svr.wait_until_ready();
  6748. Client cli("localhost", PORT);
  6749. auto res = cli.Get("/");
  6750. ASSERT_TRUE(res);
  6751. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6752. EXPECT_EQ("helloworld", res->body);
  6753. }
  6754. TEST(LongPollingTest, ClientCloseDetection) {
  6755. Server svr;
  6756. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6757. res.set_chunked_content_provider(
  6758. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6759. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6760. sink.os << "hello";
  6761. auto count = 10;
  6762. while (count > 0 && sink.is_writable()) {
  6763. this_thread::sleep_for(chrono::milliseconds(10));
  6764. count--;
  6765. }
  6766. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6767. return true;
  6768. });
  6769. });
  6770. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6771. auto se = detail::scope_exit([&] {
  6772. svr.stop();
  6773. listen_thread.join();
  6774. ASSERT_FALSE(svr.is_running());
  6775. });
  6776. svr.wait_until_ready();
  6777. Client cli("localhost", PORT);
  6778. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6779. EXPECT_EQ("hello", string(data, data_length));
  6780. return false; // close the socket immediately.
  6781. });
  6782. ASSERT_FALSE(res);
  6783. }
  6784. TEST(GetWithParametersTest, GetWithParameters) {
  6785. Server svr;
  6786. svr.Get("/", [&](const Request &req, Response &) {
  6787. EXPECT_EQ("world", req.get_param_value("hello"));
  6788. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6789. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6790. });
  6791. svr.Get("/params", [&](const Request &req, Response &) {
  6792. EXPECT_EQ("world", req.get_param_value("hello"));
  6793. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6794. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6795. });
  6796. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6797. EXPECT_EQ("resource-id", req.matches[1]);
  6798. EXPECT_EQ("foo", req.get_param_value("param1"));
  6799. EXPECT_EQ("bar", req.get_param_value("param2"));
  6800. });
  6801. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6802. EXPECT_EQ("user-id", req.path_params.at("id"));
  6803. EXPECT_EQ("foo", req.get_param_value("param1"));
  6804. EXPECT_EQ("bar", req.get_param_value("param2"));
  6805. });
  6806. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6807. auto se = detail::scope_exit([&] {
  6808. svr.stop();
  6809. listen_thread.join();
  6810. ASSERT_FALSE(svr.is_running());
  6811. });
  6812. svr.wait_until_ready();
  6813. {
  6814. Client cli(HOST, PORT);
  6815. Params params;
  6816. params.emplace("hello", "world");
  6817. params.emplace("hello2", "world2");
  6818. params.emplace("hello3", "world3");
  6819. auto res = cli.Get("/", params, Headers{});
  6820. ASSERT_TRUE(res);
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. }
  6823. {
  6824. Client cli(HOST, PORT);
  6825. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6826. ASSERT_TRUE(res);
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. }
  6829. {
  6830. Client cli(HOST, PORT);
  6831. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6832. ASSERT_TRUE(res);
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. }
  6835. {
  6836. Client cli(HOST, PORT);
  6837. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6838. ASSERT_TRUE(res);
  6839. EXPECT_EQ(StatusCode::OK_200, res->status);
  6840. }
  6841. }
  6842. TEST(GetWithParametersTest, GetWithParameters2) {
  6843. Server svr;
  6844. svr.Get("/", [&](const Request &req, Response &res) {
  6845. auto text = req.get_param_value("hello");
  6846. res.set_content(text, "text/plain");
  6847. });
  6848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6849. auto se = detail::scope_exit([&] {
  6850. svr.stop();
  6851. listen_thread.join();
  6852. ASSERT_FALSE(svr.is_running());
  6853. });
  6854. svr.wait_until_ready();
  6855. Client cli("localhost", PORT);
  6856. Params params;
  6857. params.emplace("hello", "world");
  6858. std::string body;
  6859. auto res = cli.Get("/", params, Headers{},
  6860. [&](const char *data, size_t data_length) {
  6861. body.append(data, data_length);
  6862. return true;
  6863. });
  6864. ASSERT_TRUE(res);
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. EXPECT_EQ("world", body);
  6867. }
  6868. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6869. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6870. auto host = "httpcan.org";
  6871. auto path = std::string{"/range/32"};
  6872. #else
  6873. auto host = "nghttp2.org";
  6874. auto path = std::string{"/httpbin/range/32"};
  6875. #endif
  6876. #ifdef CPPHTTPLIB_SSL_ENABLED
  6877. SSLClient cli(host);
  6878. #else
  6879. Client cli(host);
  6880. #endif
  6881. cli.set_default_headers({make_range_header({{1, 10}})});
  6882. cli.set_connection_timeout(5);
  6883. {
  6884. auto res = cli.Get(path);
  6885. ASSERT_TRUE(res);
  6886. EXPECT_EQ("bcdefghijk", res->body);
  6887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6888. }
  6889. {
  6890. auto res = cli.Get(path);
  6891. ASSERT_TRUE(res);
  6892. EXPECT_EQ("bcdefghijk", res->body);
  6893. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6894. }
  6895. }
  6896. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6897. Server svr;
  6898. svr.set_default_headers({{"Hello", "World"}});
  6899. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6900. res.set_content("ok", "text/plain");
  6901. });
  6902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6903. auto se = detail::scope_exit([&] {
  6904. svr.stop();
  6905. listen_thread.join();
  6906. ASSERT_FALSE(svr.is_running());
  6907. });
  6908. svr.wait_until_ready();
  6909. Client cli("localhost", PORT);
  6910. auto res = cli.Get("/");
  6911. ASSERT_TRUE(res);
  6912. EXPECT_EQ(StatusCode::OK_200, res->status);
  6913. EXPECT_EQ("ok", res->body);
  6914. EXPECT_EQ("World", res->get_header_value("Hello"));
  6915. }
  6916. #ifdef CPPHTTPLIB_SSL_ENABLED
  6917. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6919. ASSERT_TRUE(svr.is_valid());
  6920. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6921. std::this_thread::sleep_for(std::chrono::seconds(2));
  6922. res.set_content("a", "text/plain");
  6923. });
  6924. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6925. res.set_content("b", "text/plain");
  6926. });
  6927. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6928. auto se = detail::scope_exit([&] {
  6929. svr.stop();
  6930. listen_thread.join();
  6931. ASSERT_FALSE(svr.is_running());
  6932. });
  6933. svr.wait_until_ready();
  6934. SSLClient cli("localhost", PORT);
  6935. cli.enable_server_certificate_verification(false);
  6936. cli.set_keep_alive(true);
  6937. cli.set_read_timeout(std::chrono::seconds(1));
  6938. auto resa = cli.Get("/a");
  6939. ASSERT_TRUE(!resa);
  6940. EXPECT_EQ(Error::Read, resa.error());
  6941. auto resb = cli.Get("/b");
  6942. ASSERT_TRUE(resb);
  6943. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6944. EXPECT_EQ("b", resb->body);
  6945. }
  6946. #endif
  6947. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6948. protected:
  6949. ServerTestWithAI_PASSIVE()
  6950. : cli_(HOST, PORT)
  6951. #ifdef CPPHTTPLIB_SSL_ENABLED
  6952. ,
  6953. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6954. #endif
  6955. {
  6956. #ifdef CPPHTTPLIB_SSL_ENABLED
  6957. cli_.enable_server_certificate_verification(false);
  6958. #endif
  6959. }
  6960. virtual void SetUp() {
  6961. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6962. res.set_content("Hello World!", "text/plain");
  6963. });
  6964. t_ = thread(
  6965. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6966. svr_.wait_until_ready();
  6967. }
  6968. virtual void TearDown() {
  6969. svr_.stop();
  6970. t_.join();
  6971. }
  6972. #ifdef CPPHTTPLIB_SSL_ENABLED
  6973. SSLClient cli_;
  6974. SSLServer svr_;
  6975. #else
  6976. Client cli_;
  6977. Server svr_;
  6978. #endif
  6979. thread t_;
  6980. };
  6981. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6982. auto res = cli_.Get("/hi");
  6983. ASSERT_TRUE(res);
  6984. EXPECT_EQ(StatusCode::OK_200, res->status);
  6985. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6986. EXPECT_EQ("Hello World!", res->body);
  6987. }
  6988. class ServerUpDownTest : public ::testing::Test {
  6989. protected:
  6990. ServerUpDownTest() : cli_(HOST, PORT) {}
  6991. virtual void SetUp() {
  6992. t_ = thread([&]() {
  6993. svr_.bind_to_any_port(HOST);
  6994. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6995. ASSERT_TRUE(svr_.listen_after_bind());
  6996. });
  6997. svr_.wait_until_ready();
  6998. }
  6999. virtual void TearDown() {
  7000. svr_.stop();
  7001. t_.join();
  7002. }
  7003. Client cli_;
  7004. Server svr_;
  7005. thread t_;
  7006. };
  7007. TEST_F(ServerUpDownTest, QuickStartStop) {
  7008. // Should not crash, especially when run with
  7009. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7010. }
  7011. class PayloadMaxLengthTest : public ::testing::Test {
  7012. protected:
  7013. PayloadMaxLengthTest()
  7014. : cli_(HOST, PORT)
  7015. #ifdef CPPHTTPLIB_SSL_ENABLED
  7016. ,
  7017. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7018. #endif
  7019. {
  7020. #ifdef CPPHTTPLIB_SSL_ENABLED
  7021. cli_.enable_server_certificate_verification(false);
  7022. #endif
  7023. }
  7024. virtual void SetUp() {
  7025. svr_.set_payload_max_length(8);
  7026. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7027. res.set_content("test", "text/plain");
  7028. });
  7029. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7030. svr_.wait_until_ready();
  7031. }
  7032. virtual void TearDown() {
  7033. svr_.stop();
  7034. t_.join();
  7035. }
  7036. #ifdef CPPHTTPLIB_SSL_ENABLED
  7037. SSLClient cli_;
  7038. SSLServer svr_;
  7039. #else
  7040. Client cli_;
  7041. Server svr_;
  7042. #endif
  7043. thread t_;
  7044. };
  7045. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7046. auto res = cli_.Post("/test", "123456789", "text/plain");
  7047. ASSERT_TRUE(res);
  7048. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7049. res = cli_.Post("/test", "12345678", "text/plain");
  7050. ASSERT_TRUE(res);
  7051. EXPECT_EQ(StatusCode::OK_200, res->status);
  7052. }
  7053. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7054. // Test chunked encoding with payload exceeding the 8-byte limit
  7055. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7056. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7057. ASSERT_TRUE(res);
  7058. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7059. }
  7060. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7061. // Test chunked encoding with payload within the 8-byte limit
  7062. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7063. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7064. ASSERT_TRUE(res);
  7065. EXPECT_EQ(StatusCode::OK_200, res->status);
  7066. }
  7067. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7068. // Test using send_request to send chunked data exceeding payload limit
  7069. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7070. "Host: " +
  7071. std::string(HOST) + ":" + std::to_string(PORT) +
  7072. "\r\n"
  7073. "Transfer-Encoding: chunked\r\n"
  7074. "Connection: close\r\n"
  7075. "\r\n"
  7076. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7077. "0123456789\r\n"
  7078. "0\r\n" // End chunk
  7079. "\r\n";
  7080. std::string response;
  7081. bool result = send_request(1, chunked_request, &response);
  7082. if (!result) {
  7083. // If send_request fails, it might be because the server closed the
  7084. // connection due to payload limit enforcement, which is acceptable
  7085. SUCCEED()
  7086. << "Server rejected oversized chunked request (connection closed)";
  7087. } else {
  7088. // If we got a response, check if it's an error response or connection was
  7089. // closed early Short response length indicates connection was closed due to
  7090. // payload limit
  7091. if (response.length() <= 10) {
  7092. SUCCEED() << "Server closed connection for oversized chunked request";
  7093. } else {
  7094. // Check for error status codes
  7095. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7096. response.find("Payload Too Large") != std::string::npos ||
  7097. response.find("400") != std::string::npos);
  7098. }
  7099. }
  7100. }
  7101. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7102. // Test request without Content-Length header exceeding payload limit
  7103. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7104. "Host: " +
  7105. std::string(HOST) + ":" +
  7106. std::to_string(PORT) +
  7107. "\r\n"
  7108. "Connection: close\r\n"
  7109. "\r\n";
  7110. // Add payload exceeding the 8-byte limit
  7111. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7112. request_without_content_length += large_payload;
  7113. std::string response;
  7114. bool result = send_request(1, request_without_content_length, &response);
  7115. if (!result) {
  7116. // If send_request fails, server likely closed connection due to payload
  7117. // limit
  7118. SUCCEED() << "Server rejected oversized request without Content-Length "
  7119. "(connection closed)";
  7120. } else {
  7121. // Check if server responded with error or closed connection early
  7122. if (response.length() <= 10) {
  7123. SUCCEED() << "Server closed connection for oversized request without "
  7124. "Content-Length";
  7125. } else {
  7126. // Check for error status codes
  7127. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7128. response.find("Payload Too Large") != std::string::npos ||
  7129. response.find("400") != std::string::npos);
  7130. }
  7131. }
  7132. }
  7133. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7134. // Test request without Content-Length header within payload limit
  7135. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7136. "Host: " +
  7137. std::string(HOST) + ":" +
  7138. std::to_string(PORT) +
  7139. "\r\n"
  7140. "Connection: close\r\n"
  7141. "\r\n";
  7142. // Add payload within the 8-byte limit
  7143. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7144. request_without_content_length += small_payload;
  7145. std::string response;
  7146. bool result = send_request(1, request_without_content_length, &response);
  7147. // For requests without Content-Length, the server may have different behavior
  7148. // The key is that it should not reject due to payload limit for small
  7149. // payloads
  7150. if (result) {
  7151. // Check for any HTTP response (success or error, but not connection closed)
  7152. if (response.length() > 10) {
  7153. SUCCEED()
  7154. << "Server processed request without Content-Length within limit";
  7155. } else {
  7156. // Short response might indicate connection closed, which is acceptable
  7157. SUCCEED() << "Server closed connection for request without "
  7158. "Content-Length (acceptable behavior)";
  7159. }
  7160. } else {
  7161. // Connection failure might be due to protocol requirements
  7162. SUCCEED() << "Connection issue with request without Content-Length "
  7163. "(environment-specific)";
  7164. }
  7165. }
  7166. class LargePayloadMaxLengthTest : public ::testing::Test {
  7167. protected:
  7168. LargePayloadMaxLengthTest()
  7169. : cli_(HOST, PORT)
  7170. #ifdef CPPHTTPLIB_SSL_ENABLED
  7171. ,
  7172. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7173. #endif
  7174. {
  7175. #ifdef CPPHTTPLIB_SSL_ENABLED
  7176. cli_.enable_server_certificate_verification(false);
  7177. #endif
  7178. }
  7179. virtual void SetUp() {
  7180. // Set 10MB payload limit
  7181. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7182. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7183. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7184. res.set_content("Large payload test", "text/plain");
  7185. });
  7186. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7187. svr_.wait_until_ready();
  7188. }
  7189. virtual void TearDown() {
  7190. svr_.stop();
  7191. t_.join();
  7192. }
  7193. #ifdef CPPHTTPLIB_SSL_ENABLED
  7194. SSLClient cli_;
  7195. SSLServer svr_;
  7196. #else
  7197. Client cli_;
  7198. Server svr_;
  7199. #endif
  7200. thread t_;
  7201. };
  7202. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7203. // Test chunked encoding with payload within 10MB limit
  7204. std::string medium_payload(5 * 1024 * 1024,
  7205. 'A'); // 5MB payload, within 10MB limit
  7206. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7207. ASSERT_TRUE(res);
  7208. EXPECT_EQ(StatusCode::OK_200, res->status);
  7209. }
  7210. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7211. // Test chunked encoding with payload exceeding 10MB limit
  7212. std::string large_payload(12 * 1024 * 1024,
  7213. 'B'); // 12MB payload, exceeds 10MB limit
  7214. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7215. // Server may either return 413 or close the connection
  7216. if (res) {
  7217. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7218. } else {
  7219. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7220. }
  7221. }
  7222. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7223. // Test request without Content-Length header within 10MB limit
  7224. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7225. "Host: " +
  7226. std::string(HOST) + ":" +
  7227. std::to_string(PORT) +
  7228. "\r\n"
  7229. "Connection: close\r\n"
  7230. "\r\n";
  7231. // Add 1MB payload (within 10MB limit)
  7232. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7233. request_without_content_length += medium_payload;
  7234. std::string response;
  7235. bool result = send_request(5, request_without_content_length, &response);
  7236. if (result) {
  7237. // Should get a proper HTTP response for payloads within limit
  7238. if (response.length() > 10) {
  7239. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7240. "10MB limit";
  7241. } else {
  7242. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7243. "Content-Length)";
  7244. }
  7245. } else {
  7246. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7247. }
  7248. }
  7249. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7250. // Test request without Content-Length header exceeding 10MB limit
  7251. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7252. "Host: " +
  7253. std::string(HOST) + ":" +
  7254. std::to_string(PORT) +
  7255. "\r\n"
  7256. "Connection: close\r\n"
  7257. "\r\n";
  7258. // Add 12MB payload (exceeds 10MB limit)
  7259. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7260. request_without_content_length += large_payload;
  7261. std::string response;
  7262. bool result = send_request(10, request_without_content_length, &response);
  7263. if (!result) {
  7264. // Server should close connection due to payload limit
  7265. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7266. "(connection closed)";
  7267. } else {
  7268. // Check for error response
  7269. if (response.length() <= 10) {
  7270. SUCCEED()
  7271. << "Server closed connection for 12MB request exceeding 10MB limit";
  7272. } else {
  7273. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7274. response.find("Payload Too Large") != std::string::npos ||
  7275. response.find("400") != std::string::npos);
  7276. }
  7277. }
  7278. }
  7279. // Regression test for DoS vulnerability: a malicious server sending a response
  7280. // without Content-Length header must not cause unbounded memory consumption on
  7281. // the client side. The client should stop reading after a reasonable limit,
  7282. // similar to the server-side set_payload_max_length protection.
  7283. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7284. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7285. #ifndef _WIN32
  7286. signal(SIGPIPE, SIG_IGN);
  7287. #endif
  7288. auto server_thread = std::thread([] {
  7289. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7290. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7291. default_socket_options(srv);
  7292. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7293. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7294. sockaddr_in addr{};
  7295. addr.sin_family = AF_INET;
  7296. addr.sin_port = htons(PORT + 2);
  7297. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7298. int opt = 1;
  7299. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7300. #ifdef _WIN32
  7301. reinterpret_cast<const char *>(&opt),
  7302. #else
  7303. &opt,
  7304. #endif
  7305. sizeof(opt));
  7306. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7307. ::listen(srv, 1);
  7308. sockaddr_in cli_addr{};
  7309. socklen_t cli_len = sizeof(cli_addr);
  7310. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7311. if (cli != INVALID_SOCKET) {
  7312. char buf[4096];
  7313. ::recv(cli, buf, sizeof(buf), 0);
  7314. // Malicious response: no Content-Length, no chunked encoding
  7315. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7316. "Connection: close\r\n"
  7317. "\r\n";
  7318. ::send(cli,
  7319. #ifdef _WIN32
  7320. static_cast<const char *>(response_header.c_str()),
  7321. static_cast<int>(response_header.size()),
  7322. #else
  7323. response_header.c_str(), response_header.size(),
  7324. #endif
  7325. 0);
  7326. // Send 10MB of data
  7327. std::string chunk(64 * 1024, 'A');
  7328. size_t total_sent = 0;
  7329. while (total_sent < MALICIOUS_DATA_SIZE) {
  7330. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7331. auto sent = ::send(cli,
  7332. #ifdef _WIN32
  7333. static_cast<const char *>(chunk.c_str()),
  7334. static_cast<int>(to_send),
  7335. #else
  7336. chunk.c_str(), to_send,
  7337. #endif
  7338. 0);
  7339. if (sent <= 0) break;
  7340. total_sent += static_cast<size_t>(sent);
  7341. }
  7342. detail::close_socket(cli);
  7343. }
  7344. detail::close_socket(srv);
  7345. });
  7346. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7347. size_t total_read = 0;
  7348. {
  7349. Client cli("127.0.0.1", PORT + 2);
  7350. cli.set_read_timeout(5, 0);
  7351. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7352. auto stream = cli.open_stream("GET", "/malicious");
  7353. ASSERT_TRUE(stream.is_valid());
  7354. char buffer[64 * 1024];
  7355. ssize_t n;
  7356. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7357. total_read += static_cast<size_t>(n);
  7358. }
  7359. } // StreamHandle and Client destroyed here, closing the socket
  7360. server_thread.join();
  7361. // With set_payload_max_length, the client must stop reading before consuming
  7362. // all 10MB. The read loop should be cut off at or near the configured limit.
  7363. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7364. << "Client read " << total_read << " bytes, exceeding the configured "
  7365. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7366. }
  7367. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7368. // the entire response body without truncation.
  7369. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7370. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7371. #ifndef _WIN32
  7372. signal(SIGPIPE, SIG_IGN);
  7373. #endif
  7374. auto server_thread = std::thread([] {
  7375. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7376. default_socket_options(srv);
  7377. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7378. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7379. sockaddr_in addr{};
  7380. addr.sin_family = AF_INET;
  7381. addr.sin_port = htons(PORT + 2);
  7382. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7383. int opt = 1;
  7384. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7385. #ifdef _WIN32
  7386. reinterpret_cast<const char *>(&opt),
  7387. #else
  7388. &opt,
  7389. #endif
  7390. sizeof(opt));
  7391. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7392. ::listen(srv, 1);
  7393. sockaddr_in cli_addr{};
  7394. socklen_t cli_len = sizeof(cli_addr);
  7395. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7396. if (cli != INVALID_SOCKET) {
  7397. char buf[4096];
  7398. ::recv(cli, buf, sizeof(buf), 0);
  7399. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7400. "Connection: close\r\n"
  7401. "\r\n";
  7402. ::send(cli,
  7403. #ifdef _WIN32
  7404. static_cast<const char *>(response_header.c_str()),
  7405. static_cast<int>(response_header.size()),
  7406. #else
  7407. response_header.c_str(), response_header.size(),
  7408. #endif
  7409. 0);
  7410. std::string chunk(64 * 1024, 'A');
  7411. size_t total_sent = 0;
  7412. while (total_sent < DATA_SIZE) {
  7413. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7414. auto sent = ::send(cli,
  7415. #ifdef _WIN32
  7416. static_cast<const char *>(chunk.c_str()),
  7417. static_cast<int>(to_send),
  7418. #else
  7419. chunk.c_str(), to_send,
  7420. #endif
  7421. 0);
  7422. if (sent <= 0) break;
  7423. total_sent += static_cast<size_t>(sent);
  7424. }
  7425. #ifdef _WIN32
  7426. ::shutdown(cli, SD_SEND);
  7427. #else
  7428. ::shutdown(cli, SHUT_WR);
  7429. #endif
  7430. // Drain until the client closes its end, ensuring all data is delivered
  7431. char drain[1024];
  7432. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7433. detail::close_socket(cli);
  7434. }
  7435. detail::close_socket(srv);
  7436. });
  7437. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7438. size_t total_read = 0;
  7439. {
  7440. Client cli("127.0.0.1", PORT + 2);
  7441. cli.set_read_timeout(5, 0);
  7442. cli.set_payload_max_length(0); // 0 means no limit
  7443. auto stream = cli.open_stream("GET", "/data");
  7444. ASSERT_TRUE(stream.is_valid());
  7445. char buffer[64 * 1024];
  7446. ssize_t n;
  7447. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7448. total_read += static_cast<size_t>(n);
  7449. }
  7450. }
  7451. server_thread.join();
  7452. EXPECT_EQ(total_read, DATA_SIZE)
  7453. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7454. << " bytes without truncation, but only read " << total_read << " bytes.";
  7455. }
  7456. // Verify that content_receiver bypasses the default payload_max_length,
  7457. // allowing streaming downloads larger than 100MB without requiring an explicit
  7458. // set_payload_max_length call.
  7459. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7460. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7461. #ifndef _WIN32
  7462. signal(SIGPIPE, SIG_IGN);
  7463. #endif
  7464. auto server_thread = std::thread([] {
  7465. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7466. default_socket_options(srv);
  7467. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7468. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7469. sockaddr_in addr{};
  7470. addr.sin_family = AF_INET;
  7471. addr.sin_port = htons(PORT + 2);
  7472. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7473. int opt = 1;
  7474. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7475. #ifdef _WIN32
  7476. reinterpret_cast<const char *>(&opt),
  7477. #else
  7478. &opt,
  7479. #endif
  7480. sizeof(opt));
  7481. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7482. ::listen(srv, 1);
  7483. sockaddr_in cli_addr{};
  7484. socklen_t cli_len = sizeof(cli_addr);
  7485. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7486. if (cli != INVALID_SOCKET) {
  7487. char buf[4096];
  7488. ::recv(cli, buf, sizeof(buf), 0);
  7489. // Response with Content-Length larger than default 100MB limit
  7490. auto content_length = std::to_string(DATA_SIZE);
  7491. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7492. "Content-Length: " +
  7493. content_length +
  7494. "\r\n"
  7495. "Connection: close\r\n"
  7496. "\r\n";
  7497. ::send(cli,
  7498. #ifdef _WIN32
  7499. static_cast<const char *>(response_header.c_str()),
  7500. static_cast<int>(response_header.size()),
  7501. #else
  7502. response_header.c_str(), response_header.size(),
  7503. #endif
  7504. 0);
  7505. std::string chunk(64 * 1024, 'A');
  7506. size_t total_sent = 0;
  7507. while (total_sent < DATA_SIZE) {
  7508. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7509. auto sent = ::send(cli,
  7510. #ifdef _WIN32
  7511. static_cast<const char *>(chunk.c_str()),
  7512. static_cast<int>(to_send),
  7513. #else
  7514. chunk.c_str(), to_send,
  7515. #endif
  7516. 0);
  7517. if (sent <= 0) break;
  7518. total_sent += static_cast<size_t>(sent);
  7519. }
  7520. detail::close_socket(cli);
  7521. }
  7522. detail::close_socket(srv);
  7523. });
  7524. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7525. size_t total_received = 0;
  7526. {
  7527. Client cli("127.0.0.1", PORT + 2);
  7528. cli.set_read_timeout(10, 0);
  7529. // Do NOT call set_payload_max_length — use the default 100MB limit
  7530. auto res =
  7531. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7532. total_received += data_length;
  7533. return true;
  7534. });
  7535. ASSERT_TRUE(res);
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. }
  7538. server_thread.join();
  7539. EXPECT_EQ(total_received, DATA_SIZE)
  7540. << "With content_receiver, the client should read all " << DATA_SIZE
  7541. << " bytes despite the default 100MB payload_max_length, but only read "
  7542. << total_received << " bytes.";
  7543. }
  7544. // Verify that an explicit set_payload_max_length smaller than the response is
  7545. // enforced even when a content_receiver is used.
  7546. TEST(ClientVulnerabilityTest,
  7547. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7548. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7549. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7550. #ifndef _WIN32
  7551. signal(SIGPIPE, SIG_IGN);
  7552. #endif
  7553. auto server_thread = std::thread([] {
  7554. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7555. default_socket_options(srv);
  7556. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7557. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7558. sockaddr_in addr{};
  7559. addr.sin_family = AF_INET;
  7560. addr.sin_port = htons(PORT + 2);
  7561. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7562. int opt = 1;
  7563. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7564. #ifdef _WIN32
  7565. reinterpret_cast<const char *>(&opt),
  7566. #else
  7567. &opt,
  7568. #endif
  7569. sizeof(opt));
  7570. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7571. ::listen(srv, 1);
  7572. sockaddr_in cli_addr{};
  7573. socklen_t cli_len = sizeof(cli_addr);
  7574. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7575. if (cli != INVALID_SOCKET) {
  7576. char buf[4096];
  7577. ::recv(cli, buf, sizeof(buf), 0);
  7578. auto content_length = std::to_string(DATA_SIZE);
  7579. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7580. "Content-Length: " +
  7581. content_length +
  7582. "\r\n"
  7583. "Connection: close\r\n"
  7584. "\r\n";
  7585. ::send(cli,
  7586. #ifdef _WIN32
  7587. static_cast<const char *>(response_header.c_str()),
  7588. static_cast<int>(response_header.size()),
  7589. #else
  7590. response_header.c_str(), response_header.size(),
  7591. #endif
  7592. 0);
  7593. std::string chunk(64 * 1024, 'A');
  7594. size_t total_sent = 0;
  7595. while (total_sent < DATA_SIZE) {
  7596. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7597. auto sent = ::send(cli,
  7598. #ifdef _WIN32
  7599. static_cast<const char *>(chunk.c_str()),
  7600. static_cast<int>(to_send),
  7601. #else
  7602. chunk.c_str(), to_send,
  7603. #endif
  7604. 0);
  7605. if (sent <= 0) break;
  7606. total_sent += static_cast<size_t>(sent);
  7607. }
  7608. detail::close_socket(cli);
  7609. }
  7610. detail::close_socket(srv);
  7611. });
  7612. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7613. size_t total_received = 0;
  7614. {
  7615. Client cli("127.0.0.1", PORT + 2);
  7616. cli.set_read_timeout(10, 0);
  7617. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7618. auto res =
  7619. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7620. total_received += data_length;
  7621. return true;
  7622. });
  7623. // Should fail because 200MB exceeds the explicit 150MB limit
  7624. EXPECT_FALSE(res);
  7625. }
  7626. server_thread.join();
  7627. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7628. << "Client with content_receiver should respect the explicit "
  7629. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7630. << total_received << " bytes.";
  7631. }
  7632. // Verify that an explicit set_payload_max_length larger than the response
  7633. // allows the content_receiver to read all data successfully.
  7634. TEST(ClientVulnerabilityTest,
  7635. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7636. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7637. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7638. #ifndef _WIN32
  7639. signal(SIGPIPE, SIG_IGN);
  7640. #endif
  7641. auto server_thread = std::thread([] {
  7642. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7643. default_socket_options(srv);
  7644. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7645. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7646. sockaddr_in addr{};
  7647. addr.sin_family = AF_INET;
  7648. addr.sin_port = htons(PORT + 2);
  7649. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7650. int opt = 1;
  7651. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7652. #ifdef _WIN32
  7653. reinterpret_cast<const char *>(&opt),
  7654. #else
  7655. &opt,
  7656. #endif
  7657. sizeof(opt));
  7658. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7659. ::listen(srv, 1);
  7660. sockaddr_in cli_addr{};
  7661. socklen_t cli_len = sizeof(cli_addr);
  7662. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7663. if (cli != INVALID_SOCKET) {
  7664. char buf[4096];
  7665. ::recv(cli, buf, sizeof(buf), 0);
  7666. auto content_length = std::to_string(DATA_SIZE);
  7667. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7668. "Content-Length: " +
  7669. content_length +
  7670. "\r\n"
  7671. "Connection: close\r\n"
  7672. "\r\n";
  7673. ::send(cli,
  7674. #ifdef _WIN32
  7675. static_cast<const char *>(response_header.c_str()),
  7676. static_cast<int>(response_header.size()),
  7677. #else
  7678. response_header.c_str(), response_header.size(),
  7679. #endif
  7680. 0);
  7681. std::string chunk(64 * 1024, 'A');
  7682. size_t total_sent = 0;
  7683. while (total_sent < DATA_SIZE) {
  7684. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7685. auto sent = ::send(cli,
  7686. #ifdef _WIN32
  7687. static_cast<const char *>(chunk.c_str()),
  7688. static_cast<int>(to_send),
  7689. #else
  7690. chunk.c_str(), to_send,
  7691. #endif
  7692. 0);
  7693. if (sent <= 0) break;
  7694. total_sent += static_cast<size_t>(sent);
  7695. }
  7696. #ifdef _WIN32
  7697. ::shutdown(cli, SD_SEND);
  7698. #else
  7699. ::shutdown(cli, SHUT_WR);
  7700. #endif
  7701. char drain[1024];
  7702. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7703. detail::close_socket(cli);
  7704. }
  7705. detail::close_socket(srv);
  7706. });
  7707. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7708. size_t total_received = 0;
  7709. {
  7710. Client cli("127.0.0.1", PORT + 2);
  7711. cli.set_read_timeout(10, 0);
  7712. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7713. auto res =
  7714. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7715. total_received += data_length;
  7716. return true;
  7717. });
  7718. ASSERT_TRUE(res);
  7719. EXPECT_EQ(StatusCode::OK_200, res->status);
  7720. }
  7721. server_thread.join();
  7722. EXPECT_EQ(total_received, DATA_SIZE)
  7723. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7724. << " bytes (larger than " << DATA_SIZE
  7725. << " bytes response), content_receiver should read all data, but only "
  7726. "read "
  7727. << total_received << " bytes.";
  7728. }
  7729. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7730. // Regression test for "zip bomb" attack on the client side: a malicious server
  7731. // sends a small gzip-compressed response that decompresses to a huge payload.
  7732. // The client must enforce payload_max_length on the decompressed size.
  7733. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7734. constexpr size_t DECOMPRESSED_SIZE =
  7735. 10 * 1024 * 1024; // 10MB after decompression
  7736. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7737. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7738. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7739. std::string compressed;
  7740. {
  7741. httplib::detail::gzip_compressor compressor;
  7742. bool ok =
  7743. compressor.compress(uncompressed.data(), uncompressed.size(),
  7744. /*last=*/true, [&](const char *buf, size_t len) {
  7745. compressed.append(buf, len);
  7746. return true;
  7747. });
  7748. ASSERT_TRUE(ok);
  7749. }
  7750. // Sanity: compressed data should be much smaller than the decompressed size
  7751. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7752. #ifndef _WIN32
  7753. signal(SIGPIPE, SIG_IGN);
  7754. #endif
  7755. // Set up the listening socket in the main thread so the server is guaranteed
  7756. // to be ready before the client connects (eliminates race condition).
  7757. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7758. default_socket_options(srv);
  7759. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7760. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7761. sockaddr_in addr{};
  7762. addr.sin_family = AF_INET;
  7763. addr.sin_port = htons(PORT + 3);
  7764. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7765. int opt = 1;
  7766. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7767. #ifdef _WIN32
  7768. reinterpret_cast<const char *>(&opt),
  7769. #else
  7770. &opt,
  7771. #endif
  7772. sizeof(opt));
  7773. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7774. ASSERT_EQ(0, ::listen(srv, 1));
  7775. auto server_thread = std::thread([&compressed, srv] {
  7776. sockaddr_in cli_addr{};
  7777. socklen_t cli_len = sizeof(cli_addr);
  7778. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7779. if (cli != INVALID_SOCKET) {
  7780. // Read the full HTTP request (until \r\n\r\n)
  7781. char buf[4096];
  7782. size_t total = 0;
  7783. while (total < sizeof(buf)) {
  7784. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7785. if (n <= 0) break;
  7786. total += static_cast<size_t>(n);
  7787. // Check for end of headers
  7788. if (total >= 4) {
  7789. std::string req(buf, total);
  7790. if (req.find("\r\n\r\n") != std::string::npos) break;
  7791. }
  7792. }
  7793. // Malicious response: gzip-compressed body, no Content-Length
  7794. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7795. "Content-Encoding: gzip\r\n"
  7796. "Connection: close\r\n"
  7797. "\r\n";
  7798. ::send(cli,
  7799. #ifdef _WIN32
  7800. static_cast<const char *>(response_header.c_str()),
  7801. static_cast<int>(response_header.size()),
  7802. #else
  7803. response_header.c_str(), response_header.size(),
  7804. #endif
  7805. 0);
  7806. // Send the compressed payload (small on the wire, huge when decompressed)
  7807. size_t total_sent = 0;
  7808. while (total_sent < compressed.size()) {
  7809. auto to_send = std::min(compressed.size() - total_sent,
  7810. static_cast<size_t>(64 * 1024));
  7811. auto sent =
  7812. ::send(cli,
  7813. #ifdef _WIN32
  7814. static_cast<const char *>(compressed.c_str() + total_sent),
  7815. static_cast<int>(to_send),
  7816. #else
  7817. compressed.c_str() + total_sent, to_send,
  7818. #endif
  7819. 0);
  7820. if (sent <= 0) break;
  7821. total_sent += static_cast<size_t>(sent);
  7822. }
  7823. detail::close_socket(cli);
  7824. }
  7825. });
  7826. auto se = detail::scope_exit([&] {
  7827. detail::close_socket(srv);
  7828. server_thread.join();
  7829. });
  7830. size_t total_decompressed = 0;
  7831. {
  7832. Client cli("127.0.0.1", PORT + 3);
  7833. cli.set_read_timeout(5, 0);
  7834. cli.set_decompress(true);
  7835. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7836. auto stream = cli.open_stream("GET", "/zipbomb");
  7837. ASSERT_TRUE(stream.is_valid());
  7838. char buffer[64 * 1024];
  7839. ssize_t n;
  7840. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7841. total_decompressed += static_cast<size_t>(n);
  7842. }
  7843. }
  7844. // The decompressed size must be capped by payload_max_length. Without
  7845. // protection, the client would decompress the full 10MB from a tiny
  7846. // compressed payload, enabling a zip bomb DoS attack.
  7847. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7848. << "Client decompressed " << total_decompressed
  7849. << " bytes from a gzip response. The decompressed size should be "
  7850. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7851. }
  7852. #endif
  7853. TEST(HostAndPortPropertiesTest, NoSSL) {
  7854. httplib::Client cli("www.google.com", 1234);
  7855. ASSERT_EQ("www.google.com", cli.host());
  7856. ASSERT_EQ(1234, cli.port());
  7857. }
  7858. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7859. httplib::Client cli("www.google.com:1234");
  7860. ASSERT_EQ("www.google.com", cli.host());
  7861. ASSERT_EQ(1234, cli.port());
  7862. }
  7863. #ifdef CPPHTTPLIB_SSL_ENABLED
  7864. TEST(HostAndPortPropertiesTest, SSL) {
  7865. httplib::SSLClient cli("www.google.com");
  7866. ASSERT_EQ("www.google.com", cli.host());
  7867. ASSERT_EQ(443, cli.port());
  7868. }
  7869. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  7870. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7871. std::string cert;
  7872. read_file(CA_CERT_FILE, cert);
  7873. httplib::SSLClient httplib_client("www.google.com");
  7874. // Load CA store first time
  7875. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7876. // Load CA store second time (update)
  7877. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7878. // Verify client is still valid and can make connections
  7879. httplib_client.enable_server_certificate_verification(true);
  7880. auto res = httplib_client.Get("/");
  7881. ASSERT_TRUE(res);
  7882. // Google may return 200 or 301 depending on various factors
  7883. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7884. res->status == StatusCode::MovedPermanently_301);
  7885. }
  7886. TEST(SSLClientTest, ServerNameIndication_Online) {
  7887. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7888. auto host = "httpcan.org";
  7889. auto path = std::string{"/get"};
  7890. #else
  7891. auto host = "nghttp2.org";
  7892. auto path = std::string{"/httpbin/get"};
  7893. #endif
  7894. SSLClient cli(host, 443);
  7895. auto res = cli.Get(path);
  7896. ASSERT_TRUE(res);
  7897. ASSERT_EQ(StatusCode::OK_200, res->status);
  7898. }
  7899. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7900. // Use a site that will cause SSL verification failure due to self-signed cert
  7901. SSLClient cli("self-signed.badssl.com", 443);
  7902. cli.enable_server_certificate_verification(true);
  7903. auto res = cli.Get("/");
  7904. ASSERT_TRUE(!res);
  7905. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7906. // Verify backend error is captured for SSLServerVerification
  7907. // This occurs when certificate verification fails
  7908. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7909. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7910. EXPECT_NE(0UL, res.ssl_backend_error());
  7911. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7912. // For OpenSSL, ssl_error is 0 for verification errors
  7913. EXPECT_EQ(0, res.ssl_error());
  7914. #if !defined(_WIN32) || \
  7915. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7916. // On non-Windows or when Windows Schannel is disabled, the error comes
  7917. // from OpenSSL's verification
  7918. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7919. res.ssl_backend_error());
  7920. #endif
  7921. #endif
  7922. }
  7923. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7924. // Use a site where hostname doesn't match the certificate
  7925. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7926. SSLClient cli("wrong.host.badssl.com", 443);
  7927. cli.enable_server_certificate_verification(true);
  7928. cli.enable_server_hostname_verification(true);
  7929. auto res = cli.Get("/");
  7930. ASSERT_TRUE(!res);
  7931. // The error type depends on when hostname verification occurs:
  7932. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7933. // - Mbed TLS: SSLServerVerification (during handshake)
  7934. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7935. res.error() == Error::SSLServerVerification);
  7936. // Verify backend error is captured for hostname verification failure
  7937. EXPECT_NE(0UL, res.ssl_backend_error());
  7938. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7939. // For OpenSSL, ssl_error is 0 for verification errors
  7940. EXPECT_EQ(0, res.ssl_error());
  7941. #if !defined(_WIN32) || \
  7942. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7943. // On non-Windows or when Windows Schannel is disabled, the error comes
  7944. // from OpenSSL's hostname verification
  7945. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7946. res.ssl_backend_error());
  7947. #endif
  7948. #endif
  7949. }
  7950. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  7951. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7952. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  7953. SSLClient cli("www.google.com", 443);
  7954. cli.enable_server_certificate_verification(true);
  7955. auto res = cli.Get("/");
  7956. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  7957. }
  7958. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  7959. SSLClient cli("www.google.com", 443);
  7960. cli.enable_server_certificate_verification(true);
  7961. cli.enable_windows_certificate_verification(false);
  7962. auto res = cli.Get("/");
  7963. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  7964. }
  7965. #endif
  7966. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7967. Client cli("https://google.com");
  7968. auto res = cli.Get("/");
  7969. ASSERT_TRUE(res);
  7970. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7971. }
  7972. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7973. SSLClient cli("google.com");
  7974. cli.set_ca_cert_path(CA_CERT_FILE);
  7975. auto res = cli.Get("/");
  7976. ASSERT_TRUE(res);
  7977. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7978. }
  7979. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7980. SSLClient cli("google.com");
  7981. cli.enable_server_certificate_verification(true);
  7982. cli.set_ca_cert_path("hello");
  7983. auto res = cli.Get("/");
  7984. ASSERT_TRUE(!res);
  7985. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7986. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7987. // should be set
  7988. EXPECT_EQ(0, res.ssl_error());
  7989. // Verify backend error is captured for SSLLoadingCerts
  7990. // This error occurs when loading CA certificates fails
  7991. EXPECT_NE(0UL, res.ssl_backend_error());
  7992. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7993. // OpenSSL specific error codes:
  7994. // > openssl errstr 0x80000002
  7995. // error:80000002:system library::No such file or directory
  7996. // > openssl errstr 0xA000126
  7997. // error:0A000126:SSL routines::unexpected eof while reading
  7998. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  7999. res.ssl_backend_error() == 0xA000126);
  8000. #endif
  8001. }
  8002. TEST(SSLClientTest, ServerCertificateVerification4) {
  8003. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8004. ASSERT_TRUE(svr.is_valid());
  8005. svr.Get("/test", [&](const Request &, Response &res) {
  8006. res.set_content("test", "text/plain");
  8007. svr.stop();
  8008. ASSERT_TRUE(true);
  8009. });
  8010. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8011. auto se = detail::scope_exit([&] {
  8012. t.join();
  8013. ASSERT_FALSE(svr.is_running());
  8014. });
  8015. svr.wait_until_ready();
  8016. SSLClient cli("127.0.0.1", PORT);
  8017. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8018. cli.enable_server_certificate_verification(true);
  8019. cli.set_connection_timeout(30);
  8020. auto res = cli.Get("/test");
  8021. ASSERT_TRUE(res);
  8022. ASSERT_EQ(StatusCode::OK_200, res->status);
  8023. }
  8024. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8025. std::string cert;
  8026. read_file(CA_CERT_FILE, cert);
  8027. SSLClient cli("google.com");
  8028. cli.load_ca_cert_store(cert.data(), cert.size());
  8029. const auto res = cli.Get("/");
  8030. ASSERT_TRUE(res);
  8031. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8032. }
  8033. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8034. // clang-format off
  8035. static constexpr char cert[] =
  8036. "GlobalSign Root CA\n"
  8037. "==================\n"
  8038. "-----BEGIN CERTIFICATE-----\n"
  8039. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8040. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8041. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8042. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8043. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8044. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8045. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8046. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8047. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8048. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8049. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8050. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8051. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8052. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8053. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8054. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8055. "-----END CERTIFICATE-----\n";
  8056. // clang-format on
  8057. SSLClient cli("google.com");
  8058. cli.load_ca_cert_store(cert, sizeof(cert));
  8059. const auto res = cli.Get("/");
  8060. ASSERT_TRUE(res);
  8061. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8062. }
  8063. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8064. SSLClient cli("www.youtube.com");
  8065. cli.set_ca_cert_path(CA_CERT_FILE);
  8066. cli.enable_server_certificate_verification(true);
  8067. cli.set_follow_location(true);
  8068. auto res = cli.Get("/");
  8069. ASSERT_TRUE(res);
  8070. ASSERT_EQ(StatusCode::OK_200, res->status);
  8071. }
  8072. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8073. SSLClient cli("wWw.YouTube.Com");
  8074. cli.set_ca_cert_path(CA_CERT_FILE);
  8075. cli.enable_server_certificate_verification(true);
  8076. cli.enable_server_hostname_verification(true);
  8077. cli.set_follow_location(true);
  8078. auto res = cli.Get("/");
  8079. ASSERT_TRUE(res);
  8080. ASSERT_EQ(StatusCode::OK_200, res->status);
  8081. }
  8082. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8083. SSLClient cli("gOoGlE.COm");
  8084. cli.enable_server_certificate_verification(true);
  8085. cli.enable_server_hostname_verification(true);
  8086. cli.set_follow_location(true);
  8087. auto res = cli.Get("/");
  8088. ASSERT_TRUE(res);
  8089. ASSERT_EQ(StatusCode::OK_200, res->status);
  8090. }
  8091. TEST(SSLClientTest, Issue2004_Online) {
  8092. Client client("https://google.com");
  8093. client.set_follow_location(true);
  8094. auto res = client.Get("/");
  8095. ASSERT_TRUE(res);
  8096. ASSERT_EQ(StatusCode::OK_200, res->status);
  8097. auto body = res->body;
  8098. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8099. }
  8100. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8101. // Create SSLClient with invalid cert/key to make is_valid() return false
  8102. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8103. "nonexistent_key.pem");
  8104. // is_valid() should be false due to cert loading failure
  8105. ASSERT_FALSE(cli.is_valid());
  8106. auto res = cli.Get("/");
  8107. ASSERT_FALSE(res);
  8108. EXPECT_EQ(Error::SSLConnection, res.error());
  8109. }
  8110. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8111. // Test for Issue #2251: SSL error not properly reported when client cert
  8112. // and key paths are swapped or mismatched
  8113. // This simulates the scenario where user accidentally swaps the cert and key
  8114. // files
  8115. // Using client cert file as private key and vice versa (completely wrong)
  8116. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8117. // Should fail validation due to cert/key mismatch
  8118. ASSERT_FALSE(cli.is_valid());
  8119. // Attempt to make a request should fail with proper error
  8120. auto res = cli.Get("/");
  8121. ASSERT_FALSE(res);
  8122. EXPECT_EQ(Error::SSLConnection, res.error());
  8123. // SSL error should be recorded in the Result object (this is the key fix for
  8124. // Issue #2251)
  8125. auto backend_error = res.ssl_backend_error();
  8126. EXPECT_NE(0u, backend_error);
  8127. }
  8128. // Tests cert/key mismatch detection at the TLS context level
  8129. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8130. // Test that using mismatched cert/key causes connection failure.
  8131. // We verify this at the SSLClient level rather than through internal
  8132. // TLS API functions.
  8133. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8134. cli.enable_server_certificate_verification(false);
  8135. cli.set_connection_timeout(2);
  8136. // The mismatch should cause a connection or handshake error
  8137. auto res = cli.Get("/test");
  8138. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8139. // Either way, the request should fail
  8140. EXPECT_FALSE(res);
  8141. }
  8142. #endif
  8143. #if 0
  8144. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8145. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8146. ASSERT_TRUE(cli != nullptr);
  8147. cli->set_address_family(AF_INET6);
  8148. cli->set_interface("en0");
  8149. auto res = cli->Get("/get");
  8150. ASSERT_TRUE(res);
  8151. ASSERT_EQ(StatusCode::OK_200, res->status);
  8152. }
  8153. #endif
  8154. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8155. #ifdef CPPHTTPLIB_SSL_ENABLED
  8156. void ClientCertPresent(
  8157. const std::string &client_cert_file,
  8158. const std::string &client_private_key_file,
  8159. const std::string &client_encrypted_private_key_pass = std::string()) {
  8160. using namespace httplib::tls;
  8161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8162. CLIENT_CA_CERT_DIR);
  8163. ASSERT_TRUE(svr.is_valid());
  8164. svr.Get("/test", [&](const Request &req, Response &res) {
  8165. res.set_content("test", "text/plain");
  8166. auto cert = req.peer_cert();
  8167. ASSERT_TRUE(static_cast<bool>(cert));
  8168. std::string common_name = cert.subject_cn();
  8169. EXPECT_EQ("Common Name", common_name);
  8170. });
  8171. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8172. auto se = detail::scope_exit([&] {
  8173. svr.stop();
  8174. t.join();
  8175. ASSERT_FALSE(svr.is_running());
  8176. });
  8177. svr.wait_until_ready();
  8178. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8179. client_encrypted_private_key_pass);
  8180. cli.enable_server_certificate_verification(false);
  8181. cli.set_connection_timeout(30);
  8182. auto res = cli.Get("/test");
  8183. ASSERT_TRUE(res);
  8184. ASSERT_EQ(StatusCode::OK_200, res->status);
  8185. }
  8186. TEST(SSLClientServerTest, ClientCertPresent) {
  8187. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8188. }
  8189. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8190. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8191. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8192. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8193. }
  8194. // PEM memory-based constructor tests (works with all TLS backends)
  8195. void PemMemoryClientCertPresent(
  8196. const std::string &client_cert_file,
  8197. const std::string &client_private_key_file,
  8198. const std::string &client_encrypted_private_key_pass = std::string()) {
  8199. // Read PEM files into memory
  8200. std::string server_cert_pem, server_key_pem;
  8201. std::string client_ca_pem;
  8202. std::string client_cert_pem, client_key_pem;
  8203. read_file(SERVER_CERT_FILE, server_cert_pem);
  8204. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8205. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8206. read_file(client_cert_file, client_cert_pem);
  8207. read_file(client_private_key_file, client_key_pem);
  8208. // Create server with PEM memory
  8209. SSLServer::PemMemory server_pem = {
  8210. server_cert_pem.c_str(),
  8211. server_cert_pem.size(),
  8212. server_key_pem.c_str(),
  8213. server_key_pem.size(),
  8214. client_ca_pem.c_str(),
  8215. client_ca_pem.size(),
  8216. nullptr // no password for server key
  8217. };
  8218. SSLServer svr(server_pem);
  8219. ASSERT_TRUE(svr.is_valid());
  8220. svr.Get("/test", [&](const Request &, Response &res) {
  8221. res.set_content("test", "text/plain");
  8222. });
  8223. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8224. auto se = detail::scope_exit([&] {
  8225. svr.stop();
  8226. t.join();
  8227. ASSERT_FALSE(svr.is_running());
  8228. });
  8229. svr.wait_until_ready();
  8230. // Create client with PEM memory
  8231. const char *password = client_encrypted_private_key_pass.empty()
  8232. ? nullptr
  8233. : client_encrypted_private_key_pass.c_str();
  8234. SSLClient::PemMemory client_pem = {
  8235. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8236. client_key_pem.size(), password};
  8237. SSLClient cli(HOST, PORT, client_pem);
  8238. cli.enable_server_certificate_verification(false);
  8239. cli.set_connection_timeout(30);
  8240. auto res = cli.Get("/test");
  8241. ASSERT_TRUE(res);
  8242. ASSERT_EQ(StatusCode::OK_200, res->status);
  8243. }
  8244. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8245. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8246. }
  8247. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8248. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8249. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8250. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8251. }
  8252. TEST(SSLClientServerTest, ClientCertMissing) {
  8253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8254. CLIENT_CA_CERT_DIR);
  8255. ASSERT_TRUE(svr.is_valid());
  8256. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8257. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8258. auto se = detail::scope_exit([&] {
  8259. svr.stop();
  8260. t.join();
  8261. ASSERT_FALSE(svr.is_running());
  8262. });
  8263. svr.wait_until_ready();
  8264. SSLClient cli(HOST, PORT);
  8265. cli.set_connection_timeout(30);
  8266. auto res = cli.Get("/test");
  8267. ASSERT_TRUE(!res);
  8268. // When client cert is missing and server requires it, connection fails
  8269. // Error type depends on backend implementation
  8270. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8271. res.error() == Error::SSLConnection);
  8272. // Verify backend error is captured
  8273. // Note: This test may have different error codes depending on the exact
  8274. // verification failure
  8275. EXPECT_NE(0UL, res.ssl_backend_error());
  8276. }
  8277. TEST(SSLClientServerTest, TrustDirOptional) {
  8278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8279. ASSERT_TRUE(svr.is_valid());
  8280. svr.Get("/test", [&](const Request &, Response &res) {
  8281. res.set_content("test", "text/plain");
  8282. });
  8283. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8284. auto se = detail::scope_exit([&] {
  8285. svr.stop();
  8286. t.join();
  8287. ASSERT_FALSE(svr.is_running());
  8288. });
  8289. svr.wait_until_ready();
  8290. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8291. cli.enable_server_certificate_verification(false);
  8292. cli.set_connection_timeout(30);
  8293. auto res = cli.Get("/test");
  8294. ASSERT_TRUE(res);
  8295. ASSERT_EQ(StatusCode::OK_200, res->status);
  8296. }
  8297. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8298. class NoListenSSLServer : public SSLServer {
  8299. public:
  8300. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8301. const char *client_ca_cert_file_path,
  8302. const char *client_ca_cert_dir_path = nullptr)
  8303. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8304. client_ca_cert_dir_path),
  8305. stop_(false) {}
  8306. std::atomic_bool stop_;
  8307. private:
  8308. bool process_and_close_socket(socket_t /*sock*/) override {
  8309. // Don't create SSL context
  8310. while (!stop_.load()) {
  8311. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8312. }
  8313. return true;
  8314. }
  8315. };
  8316. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8317. CLIENT_CA_CERT_FILE);
  8318. ASSERT_TRUE(svr.is_valid());
  8319. svr.Get("/test", [&](const Request &, Response &res) {
  8320. res.set_content("test", "text/plain");
  8321. });
  8322. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8323. auto se = detail::scope_exit([&] {
  8324. svr.stop_ = true;
  8325. svr.stop();
  8326. t.join();
  8327. ASSERT_FALSE(svr.is_running());
  8328. });
  8329. svr.wait_until_ready();
  8330. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8331. cli.enable_server_certificate_verification(false);
  8332. cli.set_connection_timeout(1);
  8333. auto res = cli.Get("/test");
  8334. ASSERT_TRUE(!res);
  8335. EXPECT_EQ(Error::SSLConnection, res.error());
  8336. // Timeout results in WantRead error code (maps to backend-specific value)
  8337. EXPECT_NE(0, res.ssl_error());
  8338. }
  8339. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8340. // Test SSLServer with client certificate verification using the standard
  8341. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8342. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8343. CLIENT_CA_CERT_DIR);
  8344. ASSERT_TRUE(svr.is_valid());
  8345. svr.Get("/test", [&](const Request &req, Response &res) {
  8346. res.set_content("test", "text/plain");
  8347. auto cert = req.peer_cert();
  8348. ASSERT_TRUE(static_cast<bool>(cert));
  8349. auto common_name = cert.subject_cn();
  8350. EXPECT_EQ("Common Name", common_name);
  8351. });
  8352. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8353. auto se = detail::scope_exit([&] {
  8354. svr.stop();
  8355. t.join();
  8356. ASSERT_FALSE(svr.is_running());
  8357. });
  8358. svr.wait_until_ready();
  8359. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8360. cli.enable_server_certificate_verification(false);
  8361. cli.set_connection_timeout(30);
  8362. auto res = cli.Get("/test");
  8363. ASSERT_TRUE(res);
  8364. ASSERT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8367. // Verifies that wildcard matching and exact matching work consistently
  8368. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8369. using namespace httplib::tls;
  8370. // We need a running server to test against
  8371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8372. ASSERT_TRUE(svr.is_valid());
  8373. svr.Get("/test", [](const Request &, Response &res) {
  8374. res.set_content("ok", "text/plain");
  8375. });
  8376. thread t([&]() { svr.listen(HOST, PORT); });
  8377. auto se = detail::scope_exit([&] {
  8378. svr.stop();
  8379. t.join();
  8380. });
  8381. svr.wait_until_ready();
  8382. bool verify_callback_called = false;
  8383. bool verify_result_wrong = false;
  8384. SSLClient cli(HOST, PORT);
  8385. cli.enable_server_certificate_verification(true);
  8386. cli.set_ca_cert_path(CA_CERT_FILE);
  8387. cli.set_connection_timeout(5);
  8388. // Note: Test certificate has CN="Common Name", not "localhost"
  8389. bool verify_result_cn = false;
  8390. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8391. verify_callback_called = true;
  8392. if (!ctx.cert) return false;
  8393. // Test 1: "Common Name" should match (our test server cert CN)
  8394. verify_result_cn = ctx.check_hostname("Common Name");
  8395. // Test 2: wrong hostname should not match
  8396. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8397. return true; // Accept for the purpose of this test
  8398. });
  8399. auto res = cli.Get("/test");
  8400. // The request may succeed or fail depending on cert configuration
  8401. // but the callback should have been called
  8402. ASSERT_TRUE(verify_callback_called)
  8403. << "Verify callback should have been called";
  8404. // CN="Common Name" should match our test certificate
  8405. EXPECT_TRUE(verify_result_cn)
  8406. << "verify_hostname should match 'Common Name' (certificate CN)";
  8407. // Wrong hostname should not match
  8408. EXPECT_FALSE(verify_result_wrong)
  8409. << "verify_hostname should not match 'wronghost.example.com'";
  8410. }
  8411. #endif
  8412. // mbedTLS-specific callback constructor test
  8413. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8414. #ifdef CPPHTTPLIB_SSL_ENABLED
  8415. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8417. ASSERT_TRUE(svr.is_valid());
  8418. // Set up a handler to verify client certificate is present
  8419. bool client_cert_verified = false;
  8420. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8421. // Verify that client certificate was provided
  8422. client_cert_verified = true;
  8423. res.set_content("success", "text/plain");
  8424. });
  8425. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8426. auto se = detail::scope_exit([&] {
  8427. svr.stop();
  8428. t.join();
  8429. ASSERT_FALSE(svr.is_running());
  8430. });
  8431. svr.wait_until_ready();
  8432. // Client with certificate
  8433. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8434. cli.enable_server_certificate_verification(false);
  8435. cli.set_connection_timeout(30);
  8436. auto res = cli.Get("/test");
  8437. ASSERT_TRUE(res);
  8438. ASSERT_EQ(StatusCode::OK_200, res->status);
  8439. ASSERT_TRUE(client_cert_verified);
  8440. EXPECT_EQ("success", res->body);
  8441. }
  8442. #endif
  8443. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8444. // backends
  8445. #ifdef CPPHTTPLIB_SSL_ENABLED
  8446. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8447. using namespace httplib::tls;
  8448. // Test that when client CA cert file is provided,
  8449. // the server properly requests and validates client certificates
  8450. // Create a server with client authentication
  8451. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8452. ASSERT_TRUE(svr.is_valid());
  8453. bool handler_called = false;
  8454. svr.Get("/test", [&](const Request &req, Response &res) {
  8455. handler_called = true;
  8456. // Verify that a client certificate was provided
  8457. auto cert = req.peer_cert();
  8458. ASSERT_TRUE(static_cast<bool>(cert));
  8459. // Get the issuer name
  8460. std::string issuer_str = cert.issuer_name();
  8461. ASSERT_FALSE(issuer_str.empty());
  8462. // The client certificate should be issued by our test CA
  8463. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8464. res.set_content("authenticated", "text/plain");
  8465. });
  8466. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8467. auto se = detail::scope_exit([&] {
  8468. svr.stop();
  8469. t.join();
  8470. ASSERT_FALSE(svr.is_running());
  8471. });
  8472. svr.wait_until_ready();
  8473. // Connect with a client certificate issued by the CA
  8474. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8475. cli.enable_server_certificate_verification(false);
  8476. cli.set_connection_timeout(30);
  8477. auto res = cli.Get("/test");
  8478. ASSERT_TRUE(res);
  8479. ASSERT_EQ(StatusCode::OK_200, res->status);
  8480. ASSERT_TRUE(handler_called);
  8481. EXPECT_EQ("authenticated", res->body);
  8482. }
  8483. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8484. using namespace httplib::tls;
  8485. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8486. ASSERT_TRUE(svr.is_valid());
  8487. svr.Get("/test", [](const Request &, Response &res) {
  8488. res.set_content("ok", "text/plain");
  8489. });
  8490. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8491. auto se = detail::scope_exit([&] {
  8492. svr.stop();
  8493. t.join();
  8494. });
  8495. svr.wait_until_ready();
  8496. SSLClient cli(HOST, PORT);
  8497. cli.enable_server_certificate_verification(false);
  8498. cli.set_connection_timeout(30);
  8499. bool cert_checked = false;
  8500. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8501. if (ctx.cert) {
  8502. auto sans = ctx.sans();
  8503. // Test certificate may or may not have SANs - just verify the API
  8504. // works If SANs exist, verify the types are valid
  8505. for (const auto &san : sans) {
  8506. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8507. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8508. san.type == SanType::OTHER);
  8509. EXPECT_FALSE(san.value.empty());
  8510. }
  8511. cert_checked = true;
  8512. }
  8513. return true;
  8514. });
  8515. auto res = cli.Get("/test");
  8516. ASSERT_TRUE(res);
  8517. EXPECT_TRUE(cert_checked);
  8518. }
  8519. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8520. using namespace httplib::tls;
  8521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8522. ASSERT_TRUE(svr.is_valid());
  8523. svr.Get("/test", [](const Request &, Response &res) {
  8524. res.set_content("ok", "text/plain");
  8525. });
  8526. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8527. auto se = detail::scope_exit([&] {
  8528. svr.stop();
  8529. t.join();
  8530. });
  8531. svr.wait_until_ready();
  8532. SSLClient cli(HOST, PORT);
  8533. cli.enable_server_certificate_verification(false);
  8534. cli.set_connection_timeout(30);
  8535. bool validity_checked = false;
  8536. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8537. if (ctx.cert) {
  8538. time_t not_before = 0, not_after = 0;
  8539. bool result = ctx.validity(not_before, not_after);
  8540. EXPECT_TRUE(result);
  8541. // Verify that not_before < now < not_after for a valid cert
  8542. time_t now = time(nullptr);
  8543. EXPECT_LT(not_before, now);
  8544. EXPECT_GT(not_after, now);
  8545. validity_checked = true;
  8546. }
  8547. return true;
  8548. });
  8549. auto res = cli.Get("/test");
  8550. ASSERT_TRUE(res);
  8551. EXPECT_TRUE(validity_checked);
  8552. }
  8553. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8554. using namespace httplib::tls;
  8555. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8556. ASSERT_TRUE(svr.is_valid());
  8557. svr.Get("/test", [](const Request &, Response &res) {
  8558. res.set_content("ok", "text/plain");
  8559. });
  8560. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8561. auto se = detail::scope_exit([&] {
  8562. svr.stop();
  8563. t.join();
  8564. });
  8565. svr.wait_until_ready();
  8566. SSLClient cli(HOST, PORT);
  8567. cli.enable_server_certificate_verification(false);
  8568. cli.set_connection_timeout(30);
  8569. bool serial_checked = false;
  8570. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8571. if (ctx.cert) {
  8572. std::string serial = ctx.serial();
  8573. EXPECT_FALSE(serial.empty());
  8574. // Serial should be a hex string
  8575. for (char c : serial) {
  8576. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8577. (c >= 'a' && c <= 'f'));
  8578. }
  8579. serial_checked = true;
  8580. }
  8581. return true;
  8582. });
  8583. auto res = cli.Get("/test");
  8584. ASSERT_TRUE(res);
  8585. EXPECT_TRUE(serial_checked);
  8586. }
  8587. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8588. // Test 1: Valid CA file - no error should be recorded
  8589. {
  8590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8591. CLIENT_CA_CERT_FILE);
  8592. ASSERT_TRUE(svr.is_valid());
  8593. // With valid setup, last_ssl_error should be 0
  8594. EXPECT_EQ(0, svr.ssl_last_error());
  8595. }
  8596. // Test 2: Invalid CA file content
  8597. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8598. {
  8599. // Create a temporary file with completely invalid content
  8600. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8601. {
  8602. std::ofstream ofs(temp_invalid_ca);
  8603. ofs << "This is not a certificate file at all\n";
  8604. ofs << "Just plain text content\n";
  8605. }
  8606. // Create server with invalid CA file
  8607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8608. // Clean up temporary file
  8609. std::remove(temp_invalid_ca);
  8610. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8611. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8612. // Note: SSL_CTX_load_verify_locations typically fails first,
  8613. // but our error handling code path is still exercised
  8614. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8615. }
  8616. }
  8617. TEST(VerifyCallbackTest, VerifyContextFields) {
  8618. using namespace httplib::tls;
  8619. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8620. ASSERT_TRUE(svr.is_valid());
  8621. svr.Get("/test", [](const Request &, Response &res) {
  8622. res.set_content("ok", "text/plain");
  8623. });
  8624. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8625. auto se = detail::scope_exit([&] {
  8626. svr.stop();
  8627. t.join();
  8628. });
  8629. svr.wait_until_ready();
  8630. SSLClient cli(HOST, PORT);
  8631. cli.enable_server_certificate_verification(false);
  8632. cli.set_connection_timeout(30);
  8633. int callback_count = 0;
  8634. bool saw_leaf_cert = false;
  8635. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8636. if (ctx.cert) {
  8637. callback_count++;
  8638. // We should see at least one certificate (the leaf)
  8639. std::string cn = ctx.subject_cn();
  8640. if (!cn.empty()) { saw_leaf_cert = true; }
  8641. // Verify context fields are populated
  8642. EXPECT_NE(ctx.session, nullptr);
  8643. EXPECT_GE(ctx.depth, 0);
  8644. }
  8645. return true;
  8646. });
  8647. auto res = cli.Get("/test");
  8648. ASSERT_TRUE(res);
  8649. EXPECT_GT(callback_count, 0);
  8650. EXPECT_TRUE(saw_leaf_cert);
  8651. }
  8652. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8653. using httplib::tls::TlsError;
  8654. // Test that verify_error_to_string returns empty for success
  8655. std::string success_str = TlsError::verify_error_to_string(0);
  8656. EXPECT_TRUE(success_str.empty());
  8657. // Test that verify_error_to_string returns non-empty for error codes
  8658. // Using a common error code (certificate expired)
  8659. std::string error_str =
  8660. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8661. EXPECT_FALSE(error_str.empty());
  8662. }
  8663. TEST(SessionVerifierTest, CertificateAccepted) {
  8664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8665. ASSERT_TRUE(svr.is_valid());
  8666. svr.Get("/test", [](const Request &, Response &res) {
  8667. res.set_content("ok", "text/plain");
  8668. });
  8669. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8670. auto se = detail::scope_exit([&] {
  8671. svr.stop();
  8672. t.join();
  8673. });
  8674. svr.wait_until_ready();
  8675. SSLClient cli(HOST, PORT);
  8676. cli.enable_server_certificate_verification(false);
  8677. cli.set_connection_timeout(30);
  8678. bool callback_called = false;
  8679. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8680. EXPECT_NE(session, nullptr);
  8681. callback_called = true;
  8682. return SSLVerifierResponse::CertificateAccepted;
  8683. });
  8684. auto res = cli.Get("/test");
  8685. ASSERT_TRUE(res);
  8686. EXPECT_EQ(200, res->status);
  8687. EXPECT_TRUE(callback_called);
  8688. }
  8689. TEST(SessionVerifierTest, CertificateRejected) {
  8690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8691. ASSERT_TRUE(svr.is_valid());
  8692. svr.Get("/test", [](const Request &, Response &res) {
  8693. res.set_content("ok", "text/plain");
  8694. });
  8695. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8696. auto se = detail::scope_exit([&] {
  8697. svr.stop();
  8698. t.join();
  8699. });
  8700. svr.wait_until_ready();
  8701. SSLClient cli(HOST, PORT);
  8702. cli.enable_server_certificate_verification(false);
  8703. cli.set_connection_timeout(30);
  8704. bool callback_called = false;
  8705. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8706. EXPECT_NE(session, nullptr);
  8707. callback_called = true;
  8708. return SSLVerifierResponse::CertificateRejected;
  8709. });
  8710. auto res = cli.Get("/test");
  8711. EXPECT_FALSE(res);
  8712. EXPECT_TRUE(callback_called);
  8713. }
  8714. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8716. ASSERT_TRUE(svr.is_valid());
  8717. svr.Get("/test", [](const Request &, Response &res) {
  8718. res.set_content("ok", "text/plain");
  8719. });
  8720. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8721. auto se = detail::scope_exit([&] {
  8722. svr.stop();
  8723. t.join();
  8724. });
  8725. svr.wait_until_ready();
  8726. // NoDecisionMade with verification disabled should succeed (no default check)
  8727. SSLClient cli(HOST, PORT);
  8728. cli.enable_server_certificate_verification(false);
  8729. cli.set_connection_timeout(30);
  8730. bool callback_called = false;
  8731. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8732. EXPECT_NE(session, nullptr);
  8733. callback_called = true;
  8734. return SSLVerifierResponse::NoDecisionMade;
  8735. });
  8736. auto res = cli.Get("/test");
  8737. ASSERT_TRUE(res);
  8738. EXPECT_EQ(200, res->status);
  8739. EXPECT_TRUE(callback_called);
  8740. }
  8741. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8743. ASSERT_TRUE(svr.is_valid());
  8744. svr.Get("/test", [](const Request &, Response &res) {
  8745. res.set_content("ok", "text/plain");
  8746. });
  8747. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8748. auto se = detail::scope_exit([&] {
  8749. svr.stop();
  8750. t.join();
  8751. });
  8752. svr.wait_until_ready();
  8753. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8754. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8755. // so we only check that the request fails, not whether the callback was
  8756. // called.
  8757. SSLClient cli(HOST, PORT);
  8758. cli.enable_server_certificate_verification(true);
  8759. cli.set_connection_timeout(30);
  8760. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8761. EXPECT_NE(session, nullptr);
  8762. return SSLVerifierResponse::NoDecisionMade;
  8763. });
  8764. auto res = cli.Get("/test");
  8765. EXPECT_FALSE(res);
  8766. }
  8767. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8768. // Test SSL server using PemMemory constructor with client CA certificates
  8769. // Read PEM files
  8770. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8771. read_file(SERVER_CERT_FILE, server_cert_pem);
  8772. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8773. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8774. // Create SSLServer with PemMemory constructor including client CA
  8775. SSLServer::PemMemory server_pem = {
  8776. server_cert_pem.c_str(),
  8777. server_cert_pem.size(),
  8778. server_key_pem.c_str(),
  8779. server_key_pem.size(),
  8780. client_ca_pem.c_str(),
  8781. client_ca_pem.size(),
  8782. nullptr // no password for server key
  8783. };
  8784. SSLServer svr(server_pem);
  8785. ASSERT_TRUE(svr.is_valid());
  8786. // No SSL error should be recorded for valid setup
  8787. EXPECT_EQ(0, svr.ssl_last_error());
  8788. // Set up server endpoints
  8789. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8790. res.set_content("ok", "text/plain");
  8791. });
  8792. // Start server in a thread
  8793. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8794. svr.wait_until_ready();
  8795. // Connect with client certificate (using constructor with paths)
  8796. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8797. cli.enable_server_certificate_verification(false);
  8798. auto res = cli.Get("/test-pem-ca");
  8799. ASSERT_TRUE(res);
  8800. EXPECT_EQ(200, res->status);
  8801. EXPECT_EQ("ok", res->body);
  8802. svr.stop();
  8803. server_thread.join();
  8804. }
  8805. #endif
  8806. #ifdef _WIN32
  8807. TEST(CleanupTest, WSACleanup) {
  8808. int ret = WSACleanup();
  8809. ASSERT_EQ(0, ret);
  8810. }
  8811. #endif
  8812. #ifndef CPPHTTPLIB_SSL_ENABLED
  8813. TEST(NoSSLSupport, SimpleInterface) {
  8814. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8815. }
  8816. #endif
  8817. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8818. TEST(InvalidScheme, SimpleInterface) {
  8819. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8820. }
  8821. #endif
  8822. TEST(NoScheme, SimpleInterface) {
  8823. Client cli("yahoo.com:80");
  8824. ASSERT_TRUE(cli.is_valid());
  8825. }
  8826. TEST(SendAPI, SimpleInterface_Online) {
  8827. Client cli("http://yahoo.com");
  8828. Request req;
  8829. req.method = "GET";
  8830. req.path = "/";
  8831. auto res = cli.send(req);
  8832. ASSERT_TRUE(res);
  8833. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8834. }
  8835. TEST(SendAPI, WithParamsInRequest) {
  8836. Server svr;
  8837. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8838. EXPECT_TRUE(req.has_param("test"));
  8839. EXPECT_EQ("test_value", req.get_param_value("test"));
  8840. });
  8841. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8842. auto se = detail::scope_exit([&] {
  8843. svr.stop();
  8844. t.join();
  8845. ASSERT_FALSE(svr.is_running());
  8846. });
  8847. svr.wait_until_ready();
  8848. Client cli(HOST, PORT);
  8849. {
  8850. Request req;
  8851. req.method = "GET";
  8852. req.path = "/";
  8853. req.params.emplace("test", "test_value");
  8854. auto res = cli.send(req);
  8855. ASSERT_TRUE(res);
  8856. }
  8857. {
  8858. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8859. ASSERT_TRUE(res);
  8860. }
  8861. }
  8862. TEST(ClientImplMethods, GetSocketTest) {
  8863. httplib::Server svr;
  8864. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8865. res.status = StatusCode::OK_200;
  8866. });
  8867. auto port = svr.bind_to_any_port("127.0.0.1");
  8868. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8869. auto se = detail::scope_exit([&] {
  8870. svr.stop();
  8871. thread.join();
  8872. ASSERT_FALSE(svr.is_running());
  8873. });
  8874. svr.wait_until_ready();
  8875. {
  8876. httplib::Client cli("127.0.0.1", port);
  8877. cli.set_keep_alive(true);
  8878. // Use the behavior of cpp-httplib of opening the connection
  8879. // only when the first request happens. If that changes,
  8880. // this test would be obsolete.
  8881. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8882. // This also implicitly tests the server. But other tests would fail much
  8883. // earlier than this one to be considered.
  8884. auto res = cli.Get("/");
  8885. ASSERT_TRUE(res);
  8886. EXPECT_EQ(StatusCode::OK_200, res->status);
  8887. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8888. }
  8889. }
  8890. // Disabled due to out-of-memory problem on GitHub Actions
  8891. #ifdef _WIN64
  8892. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8893. // allocate content size larger than 2GB in memory
  8894. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8895. char *content = (char *)malloc(content_size);
  8896. ASSERT_TRUE(content);
  8897. Server svr;
  8898. svr.Get("/foo",
  8899. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8900. res.set_content(content, content_size, "application/octet-stream");
  8901. });
  8902. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8903. auto se = detail::scope_exit([&] {
  8904. svr.stop();
  8905. listen_thread.join();
  8906. if (content) free(content);
  8907. ASSERT_FALSE(svr.is_running());
  8908. });
  8909. svr.wait_until_ready();
  8910. Client cli(HOST, PORT);
  8911. auto res = cli.Get("/foo");
  8912. ASSERT_TRUE(res);
  8913. EXPECT_EQ(StatusCode::OK_200, res->status);
  8914. EXPECT_EQ(content_size, res->body.length());
  8915. }
  8916. #endif
  8917. #ifdef CPPHTTPLIB_SSL_ENABLED
  8918. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8919. Client cli("http://yahoo.com");
  8920. auto res = cli.Get("/");
  8921. ASSERT_TRUE(res);
  8922. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8923. cli.set_follow_location(true);
  8924. res = cli.Get("/");
  8925. ASSERT_TRUE(res);
  8926. EXPECT_EQ(StatusCode::OK_200, res->status);
  8927. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8928. }
  8929. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8930. Client cli("https://yahoo.com");
  8931. auto res = cli.Get("/");
  8932. ASSERT_TRUE(res);
  8933. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8934. cli.set_follow_location(true);
  8935. res = cli.Get("/");
  8936. ASSERT_TRUE(res);
  8937. EXPECT_EQ(StatusCode::OK_200, res->status);
  8938. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8939. }
  8940. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8941. Client cli("https://yahoo.com");
  8942. auto res = cli.Get("/");
  8943. ASSERT_TRUE(res);
  8944. ASSERT_FALSE(!res);
  8945. ASSERT_TRUE(res);
  8946. ASSERT_FALSE(res == nullptr);
  8947. ASSERT_TRUE(res != nullptr);
  8948. EXPECT_EQ(Error::Success, res.error());
  8949. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8950. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8951. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8952. cli.set_follow_location(true);
  8953. res = cli.Get("/");
  8954. ASSERT_TRUE(res);
  8955. EXPECT_EQ(Error::Success, res.error());
  8956. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8957. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8958. EXPECT_EQ(StatusCode::OK_200, res->status);
  8959. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8960. }
  8961. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8962. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8963. Client cli("https://cdnjs.cloudflare.com");
  8964. auto res =
  8965. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8966. ASSERT_TRUE(res);
  8967. EXPECT_EQ(StatusCode::OK_200, res->status);
  8968. EXPECT_EQ(287630U, res->body.size());
  8969. EXPECT_EQ("application/javascript; charset=utf-8",
  8970. res->get_header_value("Content-Type"));
  8971. }
  8972. #endif
  8973. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8974. #undef REDIR_HOST // Silence compiler warning
  8975. #define REDIR_HOST "https://httpbingo.org"
  8976. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8977. Client cli(REDIR_HOST);
  8978. cli.set_follow_location(true);
  8979. auto res =
  8980. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8981. ASSERT_TRUE(res);
  8982. EXPECT_EQ(StatusCode::OK_200, res->status);
  8983. }
  8984. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8985. Client cli(REDIR_HOST);
  8986. cli.set_follow_location(true);
  8987. Params params;
  8988. params.emplace("url", "http://example.com");
  8989. params.emplace("status_code", "302");
  8990. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8991. ASSERT_TRUE(res);
  8992. EXPECT_EQ(StatusCode::OK_200, res->status);
  8993. }
  8994. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8995. Client cli(REDIR_HOST);
  8996. cli.set_follow_location(true);
  8997. Params params;
  8998. params.emplace("url", "http://example.com");
  8999. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9000. ASSERT_TRUE(res);
  9001. EXPECT_EQ(StatusCode::OK_200, res->status);
  9002. }
  9003. TEST(HttpToHttpsRedirectTest, CertFile) {
  9004. auto ssl_port = PORT + 1;
  9005. Server svr;
  9006. ASSERT_TRUE(svr.is_valid());
  9007. svr.Get("/index", [&](const Request &, Response &res) {
  9008. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9009. "/index");
  9010. svr.stop();
  9011. });
  9012. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9013. ASSERT_TRUE(ssl_svr.is_valid());
  9014. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9015. res.set_content("test", "text/plain");
  9016. ssl_svr.stop();
  9017. });
  9018. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9019. thread t2 =
  9020. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9021. auto se = detail::scope_exit([&] {
  9022. t2.join();
  9023. t.join();
  9024. ASSERT_FALSE(svr.is_running());
  9025. });
  9026. svr.wait_until_ready();
  9027. ssl_svr.wait_until_ready();
  9028. Client cli("127.0.0.1", PORT);
  9029. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9030. cli.enable_server_certificate_verification(true);
  9031. cli.set_follow_location(true);
  9032. cli.set_connection_timeout(30);
  9033. auto res = cli.Get("/index");
  9034. ASSERT_TRUE(res);
  9035. ASSERT_EQ(StatusCode::OK_200, res->status);
  9036. }
  9037. TEST(SSLClientRedirectTest, CertFile) {
  9038. auto ssl_port = PORT + 1;
  9039. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9040. ASSERT_TRUE(ssl_svr1.is_valid());
  9041. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9042. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9043. "/index");
  9044. ssl_svr1.stop();
  9045. });
  9046. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9047. ASSERT_TRUE(ssl_svr2.is_valid());
  9048. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9049. res.set_content("test", "text/plain");
  9050. ssl_svr2.stop();
  9051. });
  9052. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9053. thread t2 =
  9054. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9055. auto se = detail::scope_exit([&] {
  9056. t2.join();
  9057. t.join();
  9058. ASSERT_FALSE(ssl_svr1.is_running());
  9059. });
  9060. ssl_svr1.wait_until_ready();
  9061. ssl_svr2.wait_until_ready();
  9062. SSLClient cli("127.0.0.1", PORT);
  9063. std::string cert;
  9064. read_file(SERVER_CERT2_FILE, cert);
  9065. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9066. cli.enable_server_certificate_verification(true);
  9067. cli.set_follow_location(true);
  9068. cli.set_connection_timeout(30);
  9069. auto res = cli.Get("/index");
  9070. ASSERT_TRUE(res);
  9071. ASSERT_EQ(StatusCode::OK_200, res->status);
  9072. }
  9073. #endif
  9074. #ifdef CPPHTTPLIB_SSL_ENABLED
  9075. // Test that set_ca_cert_store() skips system certs (consistent with
  9076. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9077. // should be trusted - system certs should NOT be loaded.
  9078. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9079. // Load a specific cert that is NOT a system CA cert
  9080. std::string cert;
  9081. read_file(SERVER_CERT2_FILE, cert);
  9082. SSLClient cli("google.com");
  9083. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9084. cli.enable_server_certificate_verification(true);
  9085. // This should FAIL because:
  9086. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9087. // 2. System certs should NOT be loaded when custom store is set
  9088. // If system certs WERE loaded, this would succeed
  9089. auto res = cli.Get("/");
  9090. ASSERT_FALSE(res);
  9091. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9092. }
  9093. TEST(MultipartFormDataTest, LargeData) {
  9094. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9095. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9096. const ContentReader &content_reader) {
  9097. if (req.is_multipart_form_data()) {
  9098. std::vector<FormData> items;
  9099. content_reader(
  9100. [&](const FormData &file) {
  9101. items.push_back(file);
  9102. return true;
  9103. },
  9104. [&](const char *data, size_t data_length) {
  9105. items.back().content.append(data, data_length);
  9106. return true;
  9107. });
  9108. EXPECT_TRUE(std::string(items[0].name) == "document");
  9109. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9110. EXPECT_TRUE(items[0].filename == "2MB_data");
  9111. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9112. EXPECT_TRUE(items[1].name == "hello");
  9113. EXPECT_TRUE(items[1].content == "world");
  9114. EXPECT_TRUE(items[1].filename == "");
  9115. EXPECT_TRUE(items[1].content_type == "");
  9116. } else {
  9117. std::string body;
  9118. content_reader([&](const char *data, size_t data_length) {
  9119. body.append(data, data_length);
  9120. return true;
  9121. });
  9122. }
  9123. });
  9124. auto port = svr.bind_to_any_port(HOST);
  9125. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9126. auto se = detail::scope_exit([&] {
  9127. svr.stop();
  9128. t.join();
  9129. ASSERT_FALSE(svr.is_running());
  9130. });
  9131. svr.wait_until_ready();
  9132. {
  9133. std::string data(1024 * 1024 * 2, '.');
  9134. std::stringstream buffer;
  9135. buffer << data;
  9136. SSLClient cli(HOST, port);
  9137. cli.enable_server_certificate_verification(false);
  9138. UploadFormDataItems items{
  9139. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9140. {"hello", "world", "", ""},
  9141. };
  9142. auto res = cli.Post("/post", items);
  9143. ASSERT_TRUE(res);
  9144. ASSERT_EQ(StatusCode::OK_200, res->status);
  9145. }
  9146. }
  9147. TEST(MultipartFormDataTest, DataProviderItems) {
  9148. std::random_device seed_gen;
  9149. std::mt19937 random(seed_gen());
  9150. std::string rand1;
  9151. rand1.resize(1000);
  9152. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9153. std::string rand2;
  9154. rand2.resize(3000);
  9155. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9157. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9158. const ContentReader &content_reader) {
  9159. ASSERT_FALSE(req.is_multipart_form_data());
  9160. std::string body;
  9161. content_reader([&](const char *data, size_t data_length) {
  9162. body.append(data, data_length);
  9163. return true;
  9164. });
  9165. EXPECT_EQ(body, "");
  9166. });
  9167. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9168. const ContentReader &content_reader) {
  9169. ASSERT_TRUE(req.is_multipart_form_data());
  9170. std::vector<FormData> items;
  9171. content_reader(
  9172. [&](const FormData &file) {
  9173. items.push_back(file);
  9174. return true;
  9175. },
  9176. [&](const char *data, size_t data_length) {
  9177. items.back().content.append(data, data_length);
  9178. return true;
  9179. });
  9180. ASSERT_TRUE(items.size() == 2);
  9181. EXPECT_EQ(std::string(items[0].name), "name1");
  9182. EXPECT_EQ(items[0].content, "Testing123");
  9183. EXPECT_EQ(items[0].filename, "filename1");
  9184. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9185. EXPECT_EQ(items[1].name, "name2");
  9186. EXPECT_EQ(items[1].content, "Testing456");
  9187. EXPECT_EQ(items[1].filename, "");
  9188. EXPECT_EQ(items[1].content_type, "");
  9189. });
  9190. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9191. const ContentReader &content_reader) {
  9192. ASSERT_TRUE(req.is_multipart_form_data());
  9193. std::vector<FormData> items;
  9194. content_reader(
  9195. [&](const FormData &file) {
  9196. items.push_back(file);
  9197. return true;
  9198. },
  9199. [&](const char *data, size_t data_length) {
  9200. items.back().content.append(data, data_length);
  9201. return true;
  9202. });
  9203. ASSERT_TRUE(items.size() == 2);
  9204. EXPECT_EQ(items[0].name, "name3");
  9205. EXPECT_EQ(items[0].content, rand1);
  9206. EXPECT_EQ(items[0].filename, "filename3");
  9207. EXPECT_EQ(items[0].content_type, "");
  9208. EXPECT_EQ(items[1].name, "name4");
  9209. EXPECT_EQ(items[1].content, rand2);
  9210. EXPECT_EQ(items[1].filename, "filename4");
  9211. EXPECT_EQ(items[1].content_type, "");
  9212. });
  9213. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9214. const ContentReader &content_reader) {
  9215. ASSERT_TRUE(req.is_multipart_form_data());
  9216. std::vector<FormData> items;
  9217. content_reader(
  9218. [&](const FormData &file) {
  9219. items.push_back(file);
  9220. return true;
  9221. },
  9222. [&](const char *data, size_t data_length) {
  9223. items.back().content.append(data, data_length);
  9224. return true;
  9225. });
  9226. ASSERT_TRUE(items.size() == 4);
  9227. EXPECT_EQ(std::string(items[0].name), "name1");
  9228. EXPECT_EQ(items[0].content, "Testing123");
  9229. EXPECT_EQ(items[0].filename, "filename1");
  9230. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9231. EXPECT_EQ(items[1].name, "name2");
  9232. EXPECT_EQ(items[1].content, "Testing456");
  9233. EXPECT_EQ(items[1].filename, "");
  9234. EXPECT_EQ(items[1].content_type, "");
  9235. EXPECT_EQ(items[2].name, "name3");
  9236. EXPECT_EQ(items[2].content, rand1);
  9237. EXPECT_EQ(items[2].filename, "filename3");
  9238. EXPECT_EQ(items[2].content_type, "");
  9239. EXPECT_EQ(items[3].name, "name4");
  9240. EXPECT_EQ(items[3].content, rand2);
  9241. EXPECT_EQ(items[3].filename, "filename4");
  9242. EXPECT_EQ(items[3].content_type, "");
  9243. });
  9244. auto port = svr.bind_to_any_port("localhost");
  9245. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9246. auto se = detail::scope_exit([&] {
  9247. svr.stop();
  9248. t.join();
  9249. ASSERT_FALSE(svr.is_running());
  9250. });
  9251. svr.wait_until_ready();
  9252. {
  9253. SSLClient cli("localhost", port);
  9254. cli.enable_server_certificate_verification(false);
  9255. UploadFormDataItems items{
  9256. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9257. {"name2", "Testing456", "", ""}, // not a file
  9258. };
  9259. {
  9260. auto res = cli.Post("/post-none", {}, {}, {});
  9261. ASSERT_TRUE(res);
  9262. ASSERT_EQ(StatusCode::OK_200, res->status);
  9263. }
  9264. FormDataProviderItems providers;
  9265. {
  9266. auto res =
  9267. cli.Post("/post-items", {}, items, providers); // empty providers
  9268. ASSERT_TRUE(res);
  9269. ASSERT_EQ(StatusCode::OK_200, res->status);
  9270. }
  9271. providers.push_back({"name3",
  9272. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9273. // test the offset is given correctly at each step
  9274. if (!offset)
  9275. sink.os.write(rand1.data(), 30);
  9276. else if (offset == 30)
  9277. sink.os.write(rand1.data() + 30, 300);
  9278. else if (offset == 330)
  9279. sink.os.write(rand1.data() + 330, 670);
  9280. else if (offset == rand1.size())
  9281. sink.done();
  9282. return true;
  9283. },
  9284. "filename3",
  9285. {}});
  9286. providers.push_back({"name4",
  9287. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9288. // test the offset is given correctly at each step
  9289. if (!offset)
  9290. sink.os.write(rand2.data(), 2000);
  9291. else if (offset == 2000)
  9292. sink.os.write(rand2.data() + 2000, 1);
  9293. else if (offset == 2001)
  9294. sink.os.write(rand2.data() + 2001, 999);
  9295. else if (offset == rand2.size())
  9296. sink.done();
  9297. return true;
  9298. },
  9299. "filename4",
  9300. {}});
  9301. {
  9302. auto res = cli.Post("/post-providers", {}, {}, providers);
  9303. ASSERT_TRUE(res);
  9304. ASSERT_EQ(StatusCode::OK_200, res->status);
  9305. }
  9306. {
  9307. auto res = cli.Post("/post-both", {}, items, providers);
  9308. ASSERT_TRUE(res);
  9309. ASSERT_EQ(StatusCode::OK_200, res->status);
  9310. }
  9311. }
  9312. }
  9313. TEST(MultipartFormDataTest, BadHeader) {
  9314. Server svr;
  9315. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9316. res.set_content("ok", "text/plain");
  9317. });
  9318. thread t = thread([&] { svr.listen(HOST, PORT); });
  9319. auto se = detail::scope_exit([&] {
  9320. svr.stop();
  9321. t.join();
  9322. ASSERT_FALSE(svr.is_running());
  9323. });
  9324. svr.wait_until_ready();
  9325. const std::string body =
  9326. "This is the preamble. It is to be ignored, though it\r\n"
  9327. "is a handy place for composition agents to include an\r\n"
  9328. "explanatory note to non-MIME conformant readers.\r\n"
  9329. "\r\n"
  9330. "\r\n"
  9331. "--simple boundary\r\n"
  9332. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9333. ": BAD...\r\n"
  9334. "\r\n"
  9335. "value1\r\n"
  9336. "--simple boundary\r\n"
  9337. "Content-Disposition: form-data; name=\"field2\"; "
  9338. "filename=\"example.txt\"\r\n"
  9339. "\r\n"
  9340. "value2\r\n"
  9341. "--simple boundary--\r\n"
  9342. "This is the epilogue. It is also to be ignored.\r\n";
  9343. std::string content_type =
  9344. R"(multipart/form-data; boundary="simple boundary")";
  9345. Client cli(HOST, PORT);
  9346. auto res = cli.Post("/post", body, content_type.c_str());
  9347. ASSERT_TRUE(res);
  9348. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9349. }
  9350. TEST(MultipartFormDataTest, WithPreamble) {
  9351. Server svr;
  9352. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9353. res.set_content("ok", "text/plain");
  9354. });
  9355. thread t = thread([&] { svr.listen(HOST, PORT); });
  9356. auto se = detail::scope_exit([&] {
  9357. svr.stop();
  9358. t.join();
  9359. ASSERT_FALSE(svr.is_running());
  9360. });
  9361. svr.wait_until_ready();
  9362. const std::string body =
  9363. "This is the preamble. It is to be ignored, though it\r\n"
  9364. "is a handy place for composition agents to include an\r\n"
  9365. "explanatory note to non-MIME conformant readers.\r\n"
  9366. "\r\n"
  9367. "\r\n"
  9368. "--simple boundary\r\n"
  9369. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9370. "\r\n"
  9371. "value1\r\n"
  9372. "--simple boundary\r\n"
  9373. "Content-Disposition: form-data; name=\"field2\"; "
  9374. "filename=\"example.txt\"\r\n"
  9375. "\r\n"
  9376. "value2\r\n"
  9377. "--simple boundary--\r\n"
  9378. "This is the epilogue. It is also to be ignored.\r\n";
  9379. std::string content_type =
  9380. R"(multipart/form-data; boundary="simple boundary")";
  9381. Client cli(HOST, PORT);
  9382. auto res = cli.Post("/post", body, content_type.c_str());
  9383. ASSERT_TRUE(res);
  9384. EXPECT_EQ(StatusCode::OK_200, res->status);
  9385. }
  9386. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9387. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9388. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9389. const ContentReader &content_reader) {
  9390. if (req.is_multipart_form_data()) {
  9391. std::vector<FormData> items;
  9392. content_reader(
  9393. [&](const FormData &file) {
  9394. items.push_back(file);
  9395. return true;
  9396. },
  9397. [&](const char *data, size_t data_length) {
  9398. items.back().content.append(data, data_length);
  9399. return true;
  9400. });
  9401. EXPECT_TRUE(std::string(items[0].name) == "document");
  9402. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9403. EXPECT_TRUE(items[0].filename == "2MB_data");
  9404. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9405. EXPECT_TRUE(items[1].name == "hello");
  9406. EXPECT_TRUE(items[1].content == "world");
  9407. EXPECT_TRUE(items[1].filename == "");
  9408. EXPECT_TRUE(items[1].content_type == "");
  9409. } else {
  9410. std::string body;
  9411. content_reader([&](const char *data, size_t data_length) {
  9412. body.append(data, data_length);
  9413. return true;
  9414. });
  9415. }
  9416. });
  9417. auto port = svr.bind_to_any_port("localhost");
  9418. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9419. auto se = detail::scope_exit([&] {
  9420. svr.stop();
  9421. t.join();
  9422. ASSERT_FALSE(svr.is_running());
  9423. });
  9424. svr.wait_until_ready();
  9425. {
  9426. std::string data(1024 * 1024 * 2, '.');
  9427. std::stringstream buffer;
  9428. buffer << data;
  9429. SSLClient cli("localhost", port);
  9430. cli.enable_server_certificate_verification(false);
  9431. UploadFormDataItems items{
  9432. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9433. {"hello", "world", "", ""},
  9434. };
  9435. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9436. ASSERT_TRUE(res);
  9437. ASSERT_EQ(StatusCode::OK_200, res->status);
  9438. }
  9439. }
  9440. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9441. std::string data(1024 * 1024 * 2, '&');
  9442. std::stringstream buffer;
  9443. buffer << data;
  9444. Client cli("https://localhost:8080");
  9445. UploadFormDataItems items{
  9446. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9447. {"hello", "world", "", ""},
  9448. };
  9449. for (const char &c : " \t\r\n") {
  9450. auto res =
  9451. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9452. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9453. ASSERT_FALSE(res);
  9454. }
  9455. }
  9456. TEST(MultipartFormDataTest, PutFormData) {
  9457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9458. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9459. const ContentReader &content_reader) {
  9460. if (req.is_multipart_form_data()) {
  9461. std::vector<FormData> items;
  9462. content_reader(
  9463. [&](const FormData &file) {
  9464. items.push_back(file);
  9465. return true;
  9466. },
  9467. [&](const char *data, size_t data_length) {
  9468. items.back().content.append(data, data_length);
  9469. return true;
  9470. });
  9471. EXPECT_TRUE(std::string(items[0].name) == "document");
  9472. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9473. EXPECT_TRUE(items[0].filename == "2MB_data");
  9474. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9475. EXPECT_TRUE(items[1].name == "hello");
  9476. EXPECT_TRUE(items[1].content == "world");
  9477. EXPECT_TRUE(items[1].filename == "");
  9478. EXPECT_TRUE(items[1].content_type == "");
  9479. } else {
  9480. std::string body;
  9481. content_reader([&](const char *data, size_t data_length) {
  9482. body.append(data, data_length);
  9483. return true;
  9484. });
  9485. }
  9486. });
  9487. auto port = svr.bind_to_any_port("localhost");
  9488. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9489. auto se = detail::scope_exit([&] {
  9490. svr.stop();
  9491. t.join();
  9492. ASSERT_FALSE(svr.is_running());
  9493. });
  9494. svr.wait_until_ready();
  9495. {
  9496. std::string data(1024 * 1024 * 2, '&');
  9497. std::stringstream buffer;
  9498. buffer << data;
  9499. SSLClient cli("localhost", port);
  9500. cli.enable_server_certificate_verification(false);
  9501. UploadFormDataItems items{
  9502. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9503. {"hello", "world", "", ""},
  9504. };
  9505. auto res = cli.Put("/put", items);
  9506. ASSERT_TRUE(res);
  9507. ASSERT_EQ(StatusCode::OK_200, res->status);
  9508. }
  9509. }
  9510. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9511. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9512. svr.Put("/put_customboundary",
  9513. [&](const Request &req, const Response & /*res*/,
  9514. const ContentReader &content_reader) {
  9515. if (req.is_multipart_form_data()) {
  9516. std::vector<FormData> items;
  9517. content_reader(
  9518. [&](const FormData &file) {
  9519. items.push_back(file);
  9520. return true;
  9521. },
  9522. [&](const char *data, size_t data_length) {
  9523. items.back().content.append(data, data_length);
  9524. return true;
  9525. });
  9526. EXPECT_TRUE(std::string(items[0].name) == "document");
  9527. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9528. EXPECT_TRUE(items[0].filename == "2MB_data");
  9529. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9530. EXPECT_TRUE(items[1].name == "hello");
  9531. EXPECT_TRUE(items[1].content == "world");
  9532. EXPECT_TRUE(items[1].filename == "");
  9533. EXPECT_TRUE(items[1].content_type == "");
  9534. } else {
  9535. std::string body;
  9536. content_reader([&](const char *data, size_t data_length) {
  9537. body.append(data, data_length);
  9538. return true;
  9539. });
  9540. }
  9541. });
  9542. auto port = svr.bind_to_any_port("localhost");
  9543. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9544. auto se = detail::scope_exit([&] {
  9545. svr.stop();
  9546. t.join();
  9547. ASSERT_FALSE(svr.is_running());
  9548. });
  9549. svr.wait_until_ready();
  9550. {
  9551. std::string data(1024 * 1024 * 2, '&');
  9552. std::stringstream buffer;
  9553. buffer << data;
  9554. SSLClient cli("localhost", port);
  9555. cli.enable_server_certificate_verification(false);
  9556. UploadFormDataItems items{
  9557. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9558. {"hello", "world", "", ""},
  9559. };
  9560. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9561. ASSERT_TRUE(res);
  9562. ASSERT_EQ(StatusCode::OK_200, res->status);
  9563. }
  9564. }
  9565. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9566. std::string data(1024 * 1024 * 2, '&');
  9567. std::stringstream buffer;
  9568. buffer << data;
  9569. Client cli("https://localhost:8080");
  9570. cli.enable_server_certificate_verification(false);
  9571. UploadFormDataItems items{
  9572. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9573. {"hello", "world", "", ""},
  9574. };
  9575. for (const char &c : " \t\r\n") {
  9576. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9577. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9578. ASSERT_FALSE(res);
  9579. }
  9580. }
  9581. TEST(MultipartFormDataTest, AlternateFilename) {
  9582. auto handled = false;
  9583. Server svr;
  9584. svr.Post("/test", [&](const Request &req, Response &res) {
  9585. ASSERT_EQ(2u, req.form.files.size());
  9586. ASSERT_EQ(1u, req.form.fields.size());
  9587. // Test files
  9588. const auto &file1 = req.form.get_file("file1");
  9589. ASSERT_EQ("file1", file1.name);
  9590. ASSERT_EQ("A.txt", file1.filename);
  9591. ASSERT_EQ("text/plain", file1.content_type);
  9592. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9593. const auto &file2 = req.form.get_file("file2");
  9594. ASSERT_EQ("file2", file2.name);
  9595. ASSERT_EQ("a.html", file2.filename);
  9596. ASSERT_EQ("text/html", file2.content_type);
  9597. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9598. file2.content);
  9599. // Test text field
  9600. const auto &text = req.form.get_field("text");
  9601. ASSERT_EQ("text default", text);
  9602. res.set_content("ok", "text/plain");
  9603. handled = true;
  9604. });
  9605. thread t = thread([&] { svr.listen(HOST, PORT); });
  9606. auto se = detail::scope_exit([&] {
  9607. svr.stop();
  9608. t.join();
  9609. ASSERT_FALSE(svr.is_running());
  9610. ASSERT_TRUE(handled);
  9611. });
  9612. svr.wait_until_ready();
  9613. auto req = "POST /test HTTP/1.1\r\n"
  9614. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9615. "Content-Length: 399\r\n"
  9616. "\r\n"
  9617. "----------\r\n"
  9618. "Content-Disposition: form-data; name=\"text\"\r\n"
  9619. "\r\n"
  9620. "text default\r\n"
  9621. "----------\r\n"
  9622. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9623. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9624. "Content-Type: text/plain\r\n"
  9625. "\r\n"
  9626. "Content of a.txt.\r\n"
  9627. "\r\n"
  9628. "----------\r\n"
  9629. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9630. "\"a.html\"\r\n"
  9631. "Content-Type: text/html\r\n"
  9632. "\r\n"
  9633. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9634. "\r\n"
  9635. "------------\r\n";
  9636. ASSERT_TRUE(send_request(1, req));
  9637. }
  9638. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9639. auto handled = false;
  9640. Server svr;
  9641. svr.Post("/test", [&](const Request &req, Response &) {
  9642. ASSERT_EQ(2u, req.form.fields.size());
  9643. const auto &text1 = req.form.get_field("text1");
  9644. ASSERT_EQ("text1", text1);
  9645. const auto &text2 = req.form.get_field("text2");
  9646. ASSERT_EQ("text2", text2);
  9647. handled = true;
  9648. });
  9649. thread t = thread([&] { svr.listen(HOST, PORT); });
  9650. auto se = detail::scope_exit([&] {
  9651. svr.stop();
  9652. t.join();
  9653. ASSERT_FALSE(svr.is_running());
  9654. ASSERT_TRUE(handled);
  9655. });
  9656. svr.wait_until_ready();
  9657. auto req = "POST /test HTTP/1.1\r\n"
  9658. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9659. "Content-Length: 146\r\n"
  9660. "\r\n----------\r\n"
  9661. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9662. "\r\n"
  9663. "text1"
  9664. "\r\n----------\r\n"
  9665. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9666. "\r\n"
  9667. "text2"
  9668. "\r\n------------";
  9669. std::string response;
  9670. ASSERT_TRUE(send_request(1, req, &response));
  9671. ASSERT_EQ("200", response.substr(9, 3));
  9672. }
  9673. TEST(MultipartFormDataTest, ContentLength) {
  9674. auto handled = false;
  9675. Server svr;
  9676. svr.Post("/test", [&](const Request &req, Response &) {
  9677. ASSERT_EQ(2u, req.form.fields.size());
  9678. const auto &text1 = req.form.get_field("text1");
  9679. ASSERT_EQ("text1", text1);
  9680. const auto &text2 = req.form.get_field("text2");
  9681. ASSERT_EQ("text2", text2);
  9682. handled = true;
  9683. });
  9684. thread t = thread([&] { svr.listen(HOST, PORT); });
  9685. auto se = detail::scope_exit([&] {
  9686. svr.stop();
  9687. t.join();
  9688. ASSERT_FALSE(svr.is_running());
  9689. ASSERT_TRUE(handled);
  9690. });
  9691. svr.wait_until_ready();
  9692. auto req = "POST /test HTTP/1.1\r\n"
  9693. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9694. "Content-Length: 167\r\n"
  9695. "\r\n----------\r\n"
  9696. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9697. "Content-Length: 5\r\n"
  9698. "\r\n"
  9699. "text1"
  9700. "\r\n----------\r\n"
  9701. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9702. "\r\n"
  9703. "text2"
  9704. "\r\n------------\r\n";
  9705. std::string response;
  9706. ASSERT_TRUE(send_request(1, req, &response));
  9707. ASSERT_EQ("200", response.substr(9, 3));
  9708. }
  9709. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9710. auto handled = false;
  9711. Server svr;
  9712. svr.Post("/test", [&](const Request &req, Response &) {
  9713. ASSERT_EQ(2u, req.form.fields.size());
  9714. const auto &text1 = req.form.get_field("text1");
  9715. ASSERT_EQ("text1", text1);
  9716. // TODO: Add header access for text fields if needed
  9717. const auto &text2 = req.form.get_field("text2");
  9718. ASSERT_EQ("text2", text2);
  9719. // TODO: Header access for text fields needs to be implemented
  9720. // auto &headers = it->second.headers;
  9721. // ASSERT_EQ(3U, headers.size());
  9722. // auto custom_header = headers.find("x-whatever");
  9723. // ASSERT_TRUE(custom_header != headers.end());
  9724. // ASSERT_NE("customvalue", custom_header->second);
  9725. // ASSERT_EQ("CustomValue", custom_header->second);
  9726. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9727. handled = true;
  9728. });
  9729. thread t = thread([&] { svr.listen(HOST, PORT); });
  9730. auto se = detail::scope_exit([&] {
  9731. svr.stop();
  9732. t.join();
  9733. ASSERT_FALSE(svr.is_running());
  9734. ASSERT_TRUE(handled);
  9735. });
  9736. svr.wait_until_ready();
  9737. auto req = "POST /test HTTP/1.1\r\n"
  9738. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9739. "Content-Length: 232\r\n"
  9740. "\r\n----------\r\n"
  9741. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9742. "Content-Length: 5\r\n"
  9743. "X-Test: 1\r\n"
  9744. "\r\n"
  9745. "text1"
  9746. "\r\n----------\r\n"
  9747. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9748. "Content-Type: text/plain\r\n"
  9749. "X-Whatever: CustomValue\r\n"
  9750. "\r\n"
  9751. "text2"
  9752. "\r\n------------\r\n"
  9753. "That should be disregarded. Not even read";
  9754. std::string response;
  9755. ASSERT_TRUE(send_request(1, req, &response));
  9756. ASSERT_EQ("200", response.substr(9, 3));
  9757. }
  9758. TEST(MultipartFormDataTest, LargeHeader) {
  9759. auto handled = false;
  9760. Server svr;
  9761. svr.Post("/test", [&](const Request &req, Response &) {
  9762. ASSERT_EQ(1u, req.form.fields.size());
  9763. const auto &text = req.form.get_field("name1");
  9764. ASSERT_EQ("text1", text);
  9765. handled = true;
  9766. });
  9767. thread t = thread([&] { svr.listen(HOST, PORT); });
  9768. auto se = detail::scope_exit([&] {
  9769. svr.stop();
  9770. t.join();
  9771. ASSERT_FALSE(svr.is_running());
  9772. ASSERT_TRUE(handled);
  9773. });
  9774. svr.wait_until_ready();
  9775. auto boundary = std::string("cpp-httplib-multipart-data");
  9776. std::string content = "--" + boundary +
  9777. "\r\n"
  9778. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9779. "\r\n"
  9780. "text1\r\n"
  9781. "--" +
  9782. boundary + "--\r\n";
  9783. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9784. "Content-Type: multipart/form-data;boundary=" +
  9785. boundary +
  9786. "\r\n"
  9787. "Content-Length: " +
  9788. std::to_string(content.size()) +
  9789. "\r\n"
  9790. "Dummy-Header: ";
  9791. std::string header_suffix = "\r\n"
  9792. "\r\n";
  9793. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9794. size_t header_dummy_size =
  9795. read_buff_size -
  9796. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9797. auto header_dummy = std::string(header_dummy_size, '@');
  9798. auto req = header_prefix + header_dummy + header_suffix + content;
  9799. std::string response;
  9800. ASSERT_TRUE(send_request(1, req, &response));
  9801. ASSERT_EQ("200", response.substr(9, 3));
  9802. }
  9803. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9804. static constexpr unsigned int number_of_tasks{1000000};
  9805. std::atomic_uint count{0};
  9806. std::unique_ptr<TaskQueue> task_queue{
  9807. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9808. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9809. auto queued = task_queue->enqueue(
  9810. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9811. EXPECT_TRUE(queued);
  9812. }
  9813. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9814. task_queue->shutdown();
  9815. #else
  9816. EXPECT_NO_THROW(task_queue->shutdown());
  9817. #endif
  9818. EXPECT_EQ(number_of_tasks, count.load());
  9819. }
  9820. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9821. static constexpr unsigned int number_of_tasks{1000000};
  9822. static constexpr unsigned int qlimit{2};
  9823. unsigned int queued_count{0};
  9824. std::atomic_uint count{0};
  9825. std::unique_ptr<TaskQueue> task_queue{
  9826. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  9827. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9828. if (task_queue->enqueue(
  9829. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9830. queued_count++;
  9831. }
  9832. }
  9833. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9834. task_queue->shutdown();
  9835. #else
  9836. EXPECT_NO_THROW(task_queue->shutdown());
  9837. #endif
  9838. EXPECT_EQ(queued_count, count.load());
  9839. EXPECT_TRUE(queued_count <= number_of_tasks);
  9840. EXPECT_TRUE(queued_count >= qlimit);
  9841. }
  9842. TEST(TaskQueueTest, MaxQueuedRequests) {
  9843. static constexpr unsigned int qlimit{3};
  9844. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  9845. std::condition_variable sem_cv;
  9846. std::mutex sem_mtx;
  9847. int credits = 0;
  9848. bool queued;
  9849. /* Fill up the queue with tasks that will block until we give them credits to
  9850. * complete. */
  9851. for (unsigned int n = 0; n <= qlimit;) {
  9852. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9853. std::unique_lock<std::mutex> lock(sem_mtx);
  9854. while (credits <= 0) {
  9855. sem_cv.wait(lock);
  9856. }
  9857. /* Consume the credit and signal the test code if they are all gone. */
  9858. if (--credits == 0) { sem_cv.notify_one(); }
  9859. });
  9860. if (n < qlimit) {
  9861. /* The first qlimit enqueues must succeed. */
  9862. EXPECT_TRUE(queued);
  9863. } else {
  9864. /* The last one will succeed only when the worker thread
  9865. * starts and dequeues the first blocking task. Although
  9866. * not necessary for the correctness of this test, we sleep for
  9867. * a short while to avoid busy waiting. */
  9868. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9869. }
  9870. if (queued) { n++; }
  9871. }
  9872. /* Further enqueues must fail since the queue is full. */
  9873. for (auto i = 0; i < 4; i++) {
  9874. queued = task_queue->enqueue([] {});
  9875. EXPECT_FALSE(queued);
  9876. }
  9877. /* Give the credits to allow the previous tasks to complete. */
  9878. {
  9879. std::unique_lock<std::mutex> lock(sem_mtx);
  9880. credits += qlimit + 1;
  9881. }
  9882. sem_cv.notify_all();
  9883. /* Wait for all the credits to be consumed. */
  9884. {
  9885. std::unique_lock<std::mutex> lock(sem_mtx);
  9886. while (credits > 0) {
  9887. sem_cv.wait(lock);
  9888. }
  9889. }
  9890. /* Check that we are able again to enqueue at least qlimit tasks. */
  9891. for (unsigned int i = 0; i < qlimit; i++) {
  9892. queued = task_queue->enqueue([] {});
  9893. EXPECT_TRUE(queued);
  9894. }
  9895. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9896. task_queue->shutdown();
  9897. #else
  9898. EXPECT_NO_THROW(task_queue->shutdown());
  9899. #endif
  9900. }
  9901. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  9902. Server svr;
  9903. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9904. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  9905. });
  9906. svr.Get("/hello", [](const Request &req, Response &res) {
  9907. res.set_content(req.get_param_value("key"), "text/plain");
  9908. });
  9909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9910. auto se = detail::scope_exit([&] {
  9911. svr.stop();
  9912. thread.join();
  9913. ASSERT_FALSE(svr.is_running());
  9914. });
  9915. svr.wait_until_ready();
  9916. {
  9917. Client cli(HOST, PORT);
  9918. cli.set_follow_location(true);
  9919. auto res = cli.Get("/");
  9920. ASSERT_TRUE(res);
  9921. EXPECT_EQ(StatusCode::OK_200, res->status);
  9922. EXPECT_EQ("val&key2=val2", res->body);
  9923. }
  9924. }
  9925. #endif
  9926. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  9927. Server svr;
  9928. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9929. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  9930. });
  9931. svr.Get("/hello", [](const Request &req, Response &res) {
  9932. res.set_content(req.get_param_value("key"), "text/plain");
  9933. });
  9934. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9935. auto se = detail::scope_exit([&] {
  9936. svr.stop();
  9937. thread.join();
  9938. ASSERT_FALSE(svr.is_running());
  9939. });
  9940. svr.wait_until_ready();
  9941. {
  9942. Client cli(HOST, PORT);
  9943. cli.set_follow_location(true);
  9944. auto res = cli.Get("/");
  9945. ASSERT_TRUE(res);
  9946. EXPECT_EQ(StatusCode::OK_200, res->status);
  9947. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  9948. }
  9949. }
  9950. #ifdef CPPHTTPLIB_SSL_ENABLED
  9951. TEST(RedirectTest, Issue2185_Online) {
  9952. SSLClient client("github.com");
  9953. client.set_follow_location(true);
  9954. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  9955. "Coollab-Windows.zip");
  9956. ASSERT_TRUE(res);
  9957. EXPECT_EQ(StatusCode::OK_200, res->status);
  9958. EXPECT_EQ(9920427U, res->body.size());
  9959. }
  9960. #endif
  9961. TEST(VulnerabilityTest, CRLFInjection) {
  9962. Server svr;
  9963. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  9964. res.set_content("Hello 1", "text/plain");
  9965. });
  9966. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9967. res.set_content("Hello 2", "text/plain");
  9968. });
  9969. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9970. res.set_content("Hello 3", "text/plain");
  9971. });
  9972. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9973. res.set_content("Hello 4", "text/plain");
  9974. });
  9975. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9976. for (const auto &x : req.headers) {
  9977. auto key = x.first;
  9978. EXPECT_STRNE("evil", key.c_str());
  9979. }
  9980. });
  9981. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9982. auto se = detail::scope_exit([&] {
  9983. svr.stop();
  9984. thread.join();
  9985. ASSERT_FALSE(svr.is_running());
  9986. });
  9987. svr.wait_until_ready();
  9988. {
  9989. Client cli(HOST, PORT);
  9990. cli.Post("/test1", "A=B",
  9991. "application/x-www-form-urlencoded\r\nevil: hello1");
  9992. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9993. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9994. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9995. }
  9996. }
  9997. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9998. auto server_thread = std::thread([] {
  9999. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10000. default_socket_options(srv);
  10001. sockaddr_in addr{};
  10002. addr.sin_family = AF_INET;
  10003. addr.sin_port = htons(PORT + 1);
  10004. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10005. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10006. ::listen(srv, 1);
  10007. sockaddr_in cli_addr{};
  10008. socklen_t cli_len = sizeof(cli_addr);
  10009. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10010. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10011. std::string buf_all;
  10012. char buf[2048];
  10013. ssize_t n;
  10014. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10015. buf_all.append(buf, static_cast<size_t>(n));
  10016. size_t pos;
  10017. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10018. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10019. auto e = request_block.find("\r\n");
  10020. if (e != std::string::npos) {
  10021. auto request_line = request_block.substr(0, e);
  10022. std::string msg =
  10023. "CRLF injection detected in request line: '" + request_line + "'";
  10024. EXPECT_FALSE(true) << msg;
  10025. }
  10026. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10027. ::send(cli,
  10028. #ifdef _WIN32
  10029. static_cast<const char *>(resp.c_str()),
  10030. static_cast<int>(resp.size()),
  10031. #else
  10032. resp.c_str(), resp.size(),
  10033. #endif
  10034. 0);
  10035. buf_all.erase(0, pos + 4);
  10036. }
  10037. }
  10038. detail::close_socket(cli);
  10039. detail::close_socket(srv);
  10040. });
  10041. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10042. auto cli = Client("127.0.0.1", PORT + 1);
  10043. auto headers = Headers{
  10044. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10045. {"Connection", "keep-alive"}};
  10046. auto res = cli.Get("/hi", headers);
  10047. EXPECT_FALSE(res);
  10048. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10049. server_thread.join();
  10050. }
  10051. TEST(PathParamsTest, StaticMatch) {
  10052. const auto pattern = "/users/all";
  10053. detail::PathParamsMatcher matcher(pattern);
  10054. Request request;
  10055. request.path = "/users/all";
  10056. ASSERT_TRUE(matcher.match(request));
  10057. std::unordered_map<std::string, std::string> expected_params = {};
  10058. EXPECT_EQ(request.path_params, expected_params);
  10059. }
  10060. TEST(PathParamsTest, StaticMismatch) {
  10061. const auto pattern = "/users/all";
  10062. detail::PathParamsMatcher matcher(pattern);
  10063. Request request;
  10064. request.path = "/users/1";
  10065. ASSERT_FALSE(matcher.match(request));
  10066. }
  10067. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10068. const auto pattern = "/users/:id/subscriptions";
  10069. detail::PathParamsMatcher matcher(pattern);
  10070. Request request;
  10071. request.path = "/users/42/subscriptions";
  10072. ASSERT_TRUE(matcher.match(request));
  10073. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10074. EXPECT_EQ(request.path_params, expected_params);
  10075. }
  10076. TEST(PathParamsTest, SingleParamInTheEnd) {
  10077. const auto pattern = "/users/:id";
  10078. detail::PathParamsMatcher matcher(pattern);
  10079. Request request;
  10080. request.path = "/users/24";
  10081. ASSERT_TRUE(matcher.match(request));
  10082. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10083. EXPECT_EQ(request.path_params, expected_params);
  10084. }
  10085. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10086. const auto pattern = "/users/:id/";
  10087. detail::PathParamsMatcher matcher(pattern);
  10088. Request request;
  10089. request.path = "/users/42/";
  10090. ASSERT_TRUE(matcher.match(request));
  10091. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10092. EXPECT_EQ(request.path_params, expected_params);
  10093. }
  10094. TEST(PathParamsTest, EmptyParam) {
  10095. const auto pattern = "/users/:id/";
  10096. detail::PathParamsMatcher matcher(pattern);
  10097. Request request;
  10098. request.path = "/users//";
  10099. ASSERT_TRUE(matcher.match(request));
  10100. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10101. EXPECT_EQ(request.path_params, expected_params);
  10102. }
  10103. TEST(PathParamsTest, FragmentMismatch) {
  10104. const auto pattern = "/users/:id/";
  10105. detail::PathParamsMatcher matcher(pattern);
  10106. Request request;
  10107. request.path = "/admins/24/";
  10108. ASSERT_FALSE(matcher.match(request));
  10109. }
  10110. TEST(PathParamsTest, ExtraFragments) {
  10111. const auto pattern = "/users/:id";
  10112. detail::PathParamsMatcher matcher(pattern);
  10113. Request request;
  10114. request.path = "/users/42/subscriptions";
  10115. ASSERT_FALSE(matcher.match(request));
  10116. }
  10117. TEST(PathParamsTest, MissingTrailingParam) {
  10118. const auto pattern = "/users/:id";
  10119. detail::PathParamsMatcher matcher(pattern);
  10120. Request request;
  10121. request.path = "/users";
  10122. ASSERT_FALSE(matcher.match(request));
  10123. }
  10124. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10125. const auto pattern = "/users/:id/subscriptions";
  10126. detail::PathParamsMatcher matcher(pattern);
  10127. Request request;
  10128. request.path = "/users/subscriptions";
  10129. ASSERT_FALSE(matcher.match(request));
  10130. }
  10131. TEST(PathParamsTest, MultipleParams) {
  10132. const auto pattern = "/users/:userid/subscriptions/:subid";
  10133. detail::PathParamsMatcher matcher(pattern);
  10134. Request request;
  10135. request.path = "/users/42/subscriptions/2";
  10136. ASSERT_TRUE(matcher.match(request));
  10137. std::unordered_map<std::string, std::string> expected_params = {
  10138. {"userid", "42"}, {"subid", "2"}};
  10139. EXPECT_EQ(request.path_params, expected_params);
  10140. }
  10141. TEST(PathParamsTest, SequenceOfParams) {
  10142. const auto pattern = "/values/:x/:y/:z";
  10143. detail::PathParamsMatcher matcher(pattern);
  10144. Request request;
  10145. request.path = "/values/1/2/3";
  10146. ASSERT_TRUE(matcher.match(request));
  10147. std::unordered_map<std::string, std::string> expected_params = {
  10148. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10149. EXPECT_EQ(request.path_params, expected_params);
  10150. }
  10151. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10152. const auto pattern = "/prefix:suffix";
  10153. detail::PathParamsMatcher matcher(pattern);
  10154. Request request;
  10155. request.path = "/prefix:suffix";
  10156. ASSERT_TRUE(matcher.match(request));
  10157. const std::unordered_map<std::string, std::string> expected_params = {};
  10158. EXPECT_EQ(request.path_params, expected_params);
  10159. }
  10160. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10161. // If ipv6 regex working, regex match codepath is taken.
  10162. // else port will default to 80 in Client impl
  10163. int clientImplMagicPort = 80;
  10164. int port = 4321;
  10165. // above ports must be different to avoid false negative
  10166. EXPECT_NE(clientImplMagicPort, port);
  10167. std::string ipV6TestURL = "http://[ff06::c3]";
  10168. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10169. CLIENT_PRIVATE_KEY_FILE);
  10170. EXPECT_EQ(cli.port(), port);
  10171. }
  10172. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10173. auto file_path = "./www/dir/index.html";
  10174. auto dir_path = "./www/dir";
  10175. detail::FileStat stat_file(file_path);
  10176. EXPECT_TRUE(stat_file.is_file());
  10177. EXPECT_FALSE(stat_file.is_dir());
  10178. detail::FileStat stat_dir(dir_path);
  10179. EXPECT_FALSE(stat_dir.is_file());
  10180. EXPECT_TRUE(stat_dir.is_dir());
  10181. }
  10182. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10183. // IPv4 with default HTTP port (80)
  10184. EXPECT_EQ("example.com",
  10185. detail::make_host_and_port_string("example.com", 80, false));
  10186. // IPv4 with default HTTPS port (443)
  10187. EXPECT_EQ("example.com",
  10188. detail::make_host_and_port_string("example.com", 443, true));
  10189. // IPv4 with non-default HTTP port
  10190. EXPECT_EQ("example.com:8080",
  10191. detail::make_host_and_port_string("example.com", 8080, false));
  10192. // IPv4 with non-default HTTPS port
  10193. EXPECT_EQ("example.com:8443",
  10194. detail::make_host_and_port_string("example.com", 8443, true));
  10195. // IPv6 with default HTTP port (80)
  10196. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10197. // IPv6 with default HTTPS port (443)
  10198. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10199. // IPv6 with non-default HTTP port
  10200. EXPECT_EQ("[::1]:8080",
  10201. detail::make_host_and_port_string("::1", 8080, false));
  10202. // IPv6 with non-default HTTPS port
  10203. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10204. // IPv6 full address with default port
  10205. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10206. detail::make_host_and_port_string(
  10207. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10208. // IPv6 full address with non-default port
  10209. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10210. detail::make_host_and_port_string(
  10211. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10212. // IPv6 localhost with non-default port
  10213. EXPECT_EQ("[::1]:3000",
  10214. detail::make_host_and_port_string("::1", 3000, false));
  10215. // IPv6 with zone ID (link-local address) with default port
  10216. EXPECT_EQ("[fe80::1%eth0]",
  10217. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10218. // IPv6 with zone ID (link-local address) with non-default port
  10219. EXPECT_EQ("[fe80::1%eth0]:8080",
  10220. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10221. // Edge case: Port 443 with is_ssl=false (should add port)
  10222. EXPECT_EQ("example.com:443",
  10223. detail::make_host_and_port_string("example.com", 443, false));
  10224. // Edge case: Port 80 with is_ssl=true (should add port)
  10225. EXPECT_EQ("example.com:80",
  10226. detail::make_host_and_port_string("example.com", 80, true));
  10227. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10228. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10229. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10230. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10231. // Security fix: Already bracketed IPv6 should not get double brackets
  10232. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10233. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10234. EXPECT_EQ("[::1]:8080",
  10235. detail::make_host_and_port_string("[::1]", 8080, false));
  10236. EXPECT_EQ("[2001:db8::1]:8080",
  10237. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10238. EXPECT_EQ("[fe80::1%eth0]",
  10239. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10240. EXPECT_EQ("[fe80::1%eth0]:8080",
  10241. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10242. // Edge case: Empty host (should return as-is)
  10243. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10244. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10245. // This is a known limitation but shouldn't crash
  10246. EXPECT_EQ("[host:name]",
  10247. detail::make_host_and_port_string("host:name", 80, false));
  10248. // Port number edge cases (no validation, but should not crash)
  10249. EXPECT_EQ("example.com:0",
  10250. detail::make_host_and_port_string("example.com", 0, false));
  10251. EXPECT_EQ("example.com:-1",
  10252. detail::make_host_and_port_string("example.com", -1, false));
  10253. EXPECT_EQ("example.com:65535",
  10254. detail::make_host_and_port_string("example.com", 65535, false));
  10255. EXPECT_EQ("example.com:65536",
  10256. detail::make_host_and_port_string("example.com", 65536, false));
  10257. }
  10258. #ifdef CPPHTTPLIB_SSL_ENABLED
  10259. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10260. httplib::SSLClient cli("roblox.com", 443);
  10261. cli.set_follow_location(true);
  10262. auto res = cli.Get("/");
  10263. ASSERT_TRUE(res);
  10264. EXPECT_EQ(StatusCode::OK_200, res->status);
  10265. }
  10266. #endif
  10267. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10268. Server svr;
  10269. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10270. EXPECT_EQ(res.status, 400);
  10271. });
  10272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10273. auto se = detail::scope_exit([&] {
  10274. svr.stop();
  10275. thread.join();
  10276. ASSERT_FALSE(svr.is_running());
  10277. });
  10278. svr.wait_until_ready();
  10279. Client cli(HOST, PORT);
  10280. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10281. }
  10282. TEST(InvalidHeaderCharsTest, is_field_name) {
  10283. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10284. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10285. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10286. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10287. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10288. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10289. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10290. EXPECT_FALSE(detail::fields::is_field_name(""));
  10291. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10292. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10293. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10294. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10295. }
  10296. TEST(InvalidHeaderCharsTest, is_field_value) {
  10297. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10298. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10299. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10300. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10301. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10302. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10303. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10304. EXPECT_TRUE(detail::fields::is_field_value(""));
  10305. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10306. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10307. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10308. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10309. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10310. }
  10311. TEST(InvalidHeaderCharsTest, OnServer) {
  10312. Server svr;
  10313. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10314. std::string header = "Not Set";
  10315. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10316. res.set_header(header, "value");
  10317. res.set_content("Page Content Page Content", "text/plain");
  10318. });
  10319. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10320. std::string header = "Not Set";
  10321. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10322. res.set_header("X-Test", header);
  10323. res.set_content("Page Content Page Content", "text/plain");
  10324. });
  10325. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10326. auto se = detail::scope_exit([&] {
  10327. svr.stop();
  10328. thread.join();
  10329. ASSERT_FALSE(svr.is_running());
  10330. });
  10331. svr.wait_until_ready();
  10332. Client cli(HOST, PORT);
  10333. {
  10334. auto res = cli.Get(
  10335. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10336. ASSERT_TRUE(res);
  10337. EXPECT_EQ("Page Content Page Content", res->body);
  10338. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10339. }
  10340. {
  10341. auto res = cli.Get(
  10342. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10343. ASSERT_TRUE(res);
  10344. EXPECT_EQ("Page Content Page Content", res->body);
  10345. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10346. }
  10347. }
  10348. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10349. auto handled = false;
  10350. Server svr;
  10351. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10352. thread t = thread([&] { svr.listen(HOST, PORT); });
  10353. auto se = detail::scope_exit([&] {
  10354. svr.stop();
  10355. t.join();
  10356. ASSERT_FALSE(svr.is_running());
  10357. ASSERT_FALSE(handled);
  10358. });
  10359. svr.wait_until_ready();
  10360. auto req = "POST /test HTTP/1.1\r\n"
  10361. "Content-Length: x\r\n"
  10362. "\r\n";
  10363. std::string response;
  10364. ASSERT_TRUE(send_request(1, req, &response));
  10365. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10366. response.substr(0, response.find("\r\n")));
  10367. }
  10368. #ifndef _WIN32
  10369. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10370. static constexpr char reject[] = "Unauthorized";
  10371. static constexpr char accept[] = "Upload accepted";
  10372. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10373. Server svr;
  10374. svr.set_expect_100_continue_handler(
  10375. [](const Request & /*req*/, Response &res) {
  10376. res.status = StatusCode::Unauthorized_401;
  10377. res.set_content(reject, "text/plain");
  10378. return res.status;
  10379. });
  10380. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10381. res.set_content(accept, "text/plain");
  10382. });
  10383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10384. auto se = detail::scope_exit([&] {
  10385. svr.stop();
  10386. thread.join();
  10387. ASSERT_FALSE(svr.is_running());
  10388. });
  10389. svr.wait_until_ready();
  10390. {
  10391. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10392. curl_easy_init(), &curl_easy_cleanup};
  10393. ASSERT_NE(curl, nullptr);
  10394. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10395. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10396. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10397. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10398. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10399. &curl_slist_free_all};
  10400. ASSERT_NE(list, nullptr);
  10401. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10402. struct read_data {
  10403. size_t read_size;
  10404. size_t total_size;
  10405. } data = {0, total_size};
  10406. using read_callback_t =
  10407. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10408. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10409. void *userdata) -> size_t {
  10410. read_data *data = (read_data *)userdata;
  10411. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10412. std::fill_n(ptr, size * nmemb, 'A');
  10413. data->read_size += size * nmemb;
  10414. return size * nmemb;
  10415. };
  10416. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10417. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10418. std::vector<char> buffer;
  10419. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10420. using write_callback_t =
  10421. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10422. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10423. void *userdata) -> size_t {
  10424. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10425. buffer->reserve(buffer->size() + size * nmemb + 1);
  10426. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10427. return size * nmemb;
  10428. };
  10429. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10430. {
  10431. const auto res = curl_easy_perform(curl.get());
  10432. ASSERT_EQ(res, CURLE_OK);
  10433. }
  10434. {
  10435. auto response_code = long{};
  10436. const auto res =
  10437. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10438. ASSERT_EQ(res, CURLE_OK);
  10439. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10440. }
  10441. {
  10442. auto dl = curl_off_t{};
  10443. const auto res =
  10444. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10445. ASSERT_EQ(res, CURLE_OK);
  10446. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10447. }
  10448. {
  10449. buffer.push_back('\0');
  10450. ASSERT_STRCASEEQ(buffer.data(), reject);
  10451. }
  10452. }
  10453. }
  10454. #endif
  10455. template <typename S, typename C>
  10456. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10457. svr.Get("/stream", [&](const Request &, Response &res) {
  10458. auto data = new std::string("01234567890123456789");
  10459. res.set_content_provider(
  10460. data->size(), "text/plain",
  10461. [&, data](size_t offset, size_t length, DataSink &sink) {
  10462. const size_t DATA_CHUNK_SIZE = 4;
  10463. const auto &d = *data;
  10464. std::this_thread::sleep_for(std::chrono::seconds(1));
  10465. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10466. return true;
  10467. },
  10468. [data](bool success) {
  10469. EXPECT_FALSE(success);
  10470. delete data;
  10471. });
  10472. });
  10473. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10474. auto i = new size_t(0);
  10475. res.set_content_provider(
  10476. "text/plain",
  10477. [i](size_t, DataSink &sink) {
  10478. if (*i < 5) {
  10479. std::this_thread::sleep_for(std::chrono::seconds(1));
  10480. sink.write("abcd", 4);
  10481. (*i)++;
  10482. } else {
  10483. sink.done();
  10484. }
  10485. return true;
  10486. },
  10487. [i](bool success) {
  10488. EXPECT_FALSE(success);
  10489. delete i;
  10490. });
  10491. });
  10492. svr.Get("/chunked", [&](const Request &, Response &res) {
  10493. auto i = new size_t(0);
  10494. res.set_chunked_content_provider(
  10495. "text/plain",
  10496. [i](size_t, DataSink &sink) {
  10497. if (*i < 5) {
  10498. std::this_thread::sleep_for(std::chrono::seconds(1));
  10499. sink.os << "abcd";
  10500. (*i)++;
  10501. } else {
  10502. sink.done();
  10503. }
  10504. return true;
  10505. },
  10506. [i](bool success) {
  10507. EXPECT_FALSE(success);
  10508. delete i;
  10509. });
  10510. });
  10511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10512. auto se = detail::scope_exit([&] {
  10513. svr.stop();
  10514. listen_thread.join();
  10515. ASSERT_FALSE(svr.is_running());
  10516. });
  10517. svr.wait_until_ready();
  10518. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10519. {
  10520. auto start = std::chrono::steady_clock::now();
  10521. auto res = cli.Get("/stream");
  10522. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10523. std::chrono::steady_clock::now() - start)
  10524. .count();
  10525. ASSERT_FALSE(res);
  10526. EXPECT_EQ(Error::Read, res.error());
  10527. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10528. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10529. }
  10530. {
  10531. auto start = std::chrono::steady_clock::now();
  10532. auto res = cli.Get("/stream_without_length");
  10533. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10534. std::chrono::steady_clock::now() - start)
  10535. .count();
  10536. ASSERT_FALSE(res);
  10537. EXPECT_EQ(Error::Read, res.error());
  10538. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10539. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10540. }
  10541. {
  10542. auto start = std::chrono::steady_clock::now();
  10543. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10544. EXPECT_EQ("abcd", string(data, data_length));
  10545. return true;
  10546. });
  10547. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10548. std::chrono::steady_clock::now() - start)
  10549. .count();
  10550. ASSERT_FALSE(res);
  10551. EXPECT_EQ(Error::Read, res.error());
  10552. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10553. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10554. }
  10555. }
  10556. TEST(MaxTimeoutTest, ContentStream) {
  10557. time_t timeout = 2000;
  10558. time_t threshold = 200;
  10559. Server svr;
  10560. Client cli("localhost", PORT);
  10561. max_timeout_test(svr, cli, timeout, threshold);
  10562. }
  10563. #ifdef CPPHTTPLIB_SSL_ENABLED
  10564. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10565. time_t timeout = 2000;
  10566. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10567. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10568. SSLClient cli("localhost", PORT);
  10569. cli.enable_server_certificate_verification(false);
  10570. max_timeout_test(svr, cli, timeout, threshold);
  10571. }
  10572. #endif
  10573. class EventDispatcher {
  10574. public:
  10575. EventDispatcher() {}
  10576. bool wait_event(DataSink *sink) {
  10577. unique_lock<mutex> lk(m_);
  10578. int id = id_;
  10579. // Wait with timeout to prevent hanging if client disconnects
  10580. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10581. [&] { return cid_ == id; })) {
  10582. return false; // Timeout occurred
  10583. }
  10584. sink->write(message_.data(), message_.size());
  10585. return true;
  10586. }
  10587. void send_event(const string &message) {
  10588. lock_guard<mutex> lk(m_);
  10589. cid_ = id_++;
  10590. message_ = message;
  10591. cv_.notify_all();
  10592. }
  10593. private:
  10594. mutex m_;
  10595. condition_variable cv_;
  10596. atomic_int id_{0};
  10597. atomic_int cid_{-1};
  10598. string message_;
  10599. };
  10600. TEST(ClientInThreadTest, Issue2068) {
  10601. EventDispatcher ed;
  10602. Server svr;
  10603. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10604. res.set_chunked_content_provider("text/event-stream",
  10605. [&](size_t /*offset*/, DataSink &sink) {
  10606. return ed.wait_event(&sink);
  10607. });
  10608. });
  10609. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10610. svr.wait_until_ready();
  10611. thread event_thread([&] {
  10612. int id = 0;
  10613. while (svr.is_running()) {
  10614. this_thread::sleep_for(chrono::milliseconds(500));
  10615. std::stringstream ss;
  10616. ss << "data: " << id << "\n\n";
  10617. ed.send_event(ss.str());
  10618. id++;
  10619. }
  10620. });
  10621. auto se = detail::scope_exit([&] {
  10622. svr.stop();
  10623. listen_thread.join();
  10624. event_thread.join();
  10625. ASSERT_FALSE(svr.is_running());
  10626. });
  10627. {
  10628. auto client = detail::make_unique<Client>(HOST, PORT);
  10629. client->set_read_timeout(std::chrono::minutes(10));
  10630. std::atomic<bool> stop{false};
  10631. std::thread t([&] {
  10632. client->Get("/event1",
  10633. [&](const char *, size_t) -> bool { return !stop; });
  10634. });
  10635. std::this_thread::sleep_for(std::chrono::seconds(2));
  10636. stop = true;
  10637. client->stop();
  10638. t.join();
  10639. // Reset client after thread has finished
  10640. client.reset();
  10641. }
  10642. }
  10643. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10644. Server svr;
  10645. svr.Get("/", [](const Request &req, Response &res) {
  10646. EXPECT_EQ(2U, req.trailers.size());
  10647. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10648. // Denied
  10649. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10650. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10651. // Accepted
  10652. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10653. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10654. EXPECT_TRUE(req.has_trailer("X-World"));
  10655. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10656. res.set_content("ok", "text/plain");
  10657. });
  10658. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10659. auto se = detail::scope_exit([&] {
  10660. svr.stop();
  10661. t.join();
  10662. ASSERT_FALSE(svr.is_running());
  10663. });
  10664. svr.wait_until_ready();
  10665. const std::string req = "GET / HTTP/1.1\r\n"
  10666. "Transfer-Encoding: chunked\r\n"
  10667. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10668. "\r\n"
  10669. "0\r\n"
  10670. "Content-Length: 10\r\n"
  10671. "Host: internal.local\r\n"
  10672. "Content-Type: malicious/content\r\n"
  10673. "Cookie: any\r\n"
  10674. "Set-Cookie: any\r\n"
  10675. "X-Forwarded-For: attacker.com\r\n"
  10676. "X-Real-Ip: 1.1.1.1\r\n"
  10677. "X-Hello: hello\r\n"
  10678. "X-World: world\r\n"
  10679. "\r\n";
  10680. std::string res;
  10681. ASSERT_TRUE(send_request(1, req, &res));
  10682. }
  10683. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10684. Server svr;
  10685. std::string observed_remote_addr;
  10686. std::string observed_xff;
  10687. svr.Get("/ip", [&](const Request &req, Response &res) {
  10688. observed_remote_addr = req.remote_addr;
  10689. observed_xff = req.get_header_value("X-Forwarded-For");
  10690. res.set_content("ok", "text/plain");
  10691. });
  10692. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10693. auto se = detail::scope_exit([&] {
  10694. svr.stop();
  10695. t.join();
  10696. ASSERT_FALSE(svr.is_running());
  10697. });
  10698. svr.wait_until_ready();
  10699. Client cli(HOST, PORT);
  10700. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10701. ASSERT_TRUE(res);
  10702. EXPECT_EQ(StatusCode::OK_200, res->status);
  10703. EXPECT_EQ(observed_xff, "203.0.113.66");
  10704. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10705. observed_remote_addr == "127.0.0.1");
  10706. }
  10707. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10708. Server svr;
  10709. svr.set_trusted_proxies({"203.0.113.66"});
  10710. std::string observed_remote_addr;
  10711. std::string observed_xff;
  10712. svr.Get("/ip", [&](const Request &req, Response &res) {
  10713. observed_remote_addr = req.remote_addr;
  10714. observed_xff = req.get_header_value("X-Forwarded-For");
  10715. res.set_content("ok", "text/plain");
  10716. });
  10717. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10718. auto se = detail::scope_exit([&] {
  10719. svr.stop();
  10720. t.join();
  10721. ASSERT_FALSE(svr.is_running());
  10722. });
  10723. svr.wait_until_ready();
  10724. Client cli(HOST, PORT);
  10725. auto res = cli.Get("/ip");
  10726. ASSERT_TRUE(res);
  10727. EXPECT_EQ(StatusCode::OK_200, res->status);
  10728. EXPECT_EQ(observed_xff, "");
  10729. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10730. observed_remote_addr == "127.0.0.1");
  10731. }
  10732. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10733. Server svr;
  10734. svr.set_trusted_proxies({"203.0.113.66"});
  10735. std::string observed_remote_addr;
  10736. std::string observed_xff;
  10737. svr.Get("/ip", [&](const Request &req, Response &res) {
  10738. observed_remote_addr = req.remote_addr;
  10739. observed_xff = req.get_header_value("X-Forwarded-For");
  10740. res.set_content("ok", "text/plain");
  10741. });
  10742. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10743. auto se = detail::scope_exit([&] {
  10744. svr.stop();
  10745. t.join();
  10746. ASSERT_FALSE(svr.is_running());
  10747. });
  10748. svr.wait_until_ready();
  10749. Client cli(HOST, PORT);
  10750. auto res =
  10751. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10752. ASSERT_TRUE(res);
  10753. EXPECT_EQ(StatusCode::OK_200, res->status);
  10754. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10755. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10756. }
  10757. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10758. Server svr;
  10759. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10760. std::string observed_remote_addr;
  10761. std::string observed_xff;
  10762. svr.Get("/ip", [&](const Request &req, Response &res) {
  10763. observed_remote_addr = req.remote_addr;
  10764. observed_xff = req.get_header_value("X-Forwarded-For");
  10765. res.set_content("ok", "text/plain");
  10766. });
  10767. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10768. auto se = detail::scope_exit([&] {
  10769. svr.stop();
  10770. t.join();
  10771. ASSERT_FALSE(svr.is_running());
  10772. });
  10773. svr.wait_until_ready();
  10774. Client cli(HOST, PORT);
  10775. auto res = cli.Get(
  10776. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10777. ASSERT_TRUE(res);
  10778. EXPECT_EQ(StatusCode::OK_200, res->status);
  10779. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10780. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10781. }
  10782. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10783. Server svr;
  10784. svr.set_trusted_proxies({"192.0.2.45"});
  10785. std::string observed_remote_addr;
  10786. std::string observed_xff;
  10787. svr.Get("/ip", [&](const Request &req, Response &res) {
  10788. observed_remote_addr = req.remote_addr;
  10789. observed_xff = req.get_header_value("X-Forwarded-For");
  10790. res.set_content("ok", "text/plain");
  10791. });
  10792. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10793. auto se = detail::scope_exit([&] {
  10794. svr.stop();
  10795. t.join();
  10796. ASSERT_FALSE(svr.is_running());
  10797. });
  10798. svr.wait_until_ready();
  10799. Client cli(HOST, PORT);
  10800. auto res =
  10801. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10802. ASSERT_TRUE(res);
  10803. EXPECT_EQ(StatusCode::OK_200, res->status);
  10804. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10805. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10806. }
  10807. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10808. Server svr;
  10809. svr.set_trusted_proxies({"192.0.2.45"});
  10810. std::string observed_remote_addr;
  10811. std::string observed_xff;
  10812. svr.Get("/ip", [&](const Request &req, Response &res) {
  10813. observed_remote_addr = req.remote_addr;
  10814. observed_xff = req.get_header_value("X-Forwarded-For");
  10815. res.set_content("ok", "text/plain");
  10816. });
  10817. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10818. auto se = detail::scope_exit([&] {
  10819. svr.stop();
  10820. t.join();
  10821. ASSERT_FALSE(svr.is_running());
  10822. });
  10823. svr.wait_until_ready();
  10824. Client cli(HOST, PORT);
  10825. auto res = cli.Get(
  10826. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10827. ASSERT_TRUE(res);
  10828. EXPECT_EQ(StatusCode::OK_200, res->status);
  10829. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10830. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10831. }
  10832. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10833. Server svr;
  10834. svr.set_trusted_proxies({"192.0.2.45"});
  10835. std::string observed_remote_addr;
  10836. std::string observed_xff;
  10837. svr.Get("/ip", [&](const Request &req, Response &res) {
  10838. observed_remote_addr = req.remote_addr;
  10839. observed_xff = req.get_header_value("X-Forwarded-For");
  10840. res.set_content("ok", "text/plain");
  10841. });
  10842. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10843. auto se = detail::scope_exit([&] {
  10844. svr.stop();
  10845. t.join();
  10846. ASSERT_FALSE(svr.is_running());
  10847. });
  10848. svr.wait_until_ready();
  10849. std::string raw_req =
  10850. "GET /ip HTTP/1.1\r\n"
  10851. "Host: localhost\r\n"
  10852. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10853. "Connection: close\r\n"
  10854. "\r\n";
  10855. std::string out;
  10856. ASSERT_TRUE(send_request(5, raw_req, &out));
  10857. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10858. // Header parser trims surrounding whitespace of the header value
  10859. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10860. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10861. }
  10862. #ifndef _WIN32
  10863. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10864. Server svr;
  10865. svr.Post("/post", [&](const Request &req, Response &res) {
  10866. res.set_content(req.body, "text/plain");
  10867. });
  10868. svr.Put("/put", [&](const Request &req, Response &res) {
  10869. res.set_content(req.body, "text/plain");
  10870. });
  10871. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10872. res.set_content(req.body, "text/plain");
  10873. });
  10874. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10875. res.set_content(req.body, "text/plain");
  10876. });
  10877. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10878. auto se = detail::scope_exit([&] {
  10879. svr.stop();
  10880. t.join();
  10881. ASSERT_FALSE(svr.is_running());
  10882. });
  10883. svr.wait_until_ready();
  10884. std::string resp;
  10885. // POST without Content-Length
  10886. ASSERT_TRUE(send_request(5,
  10887. "POST /post HTTP/1.1\r\n"
  10888. "Host: localhost\r\n"
  10889. "Connection: close\r\n"
  10890. "\r\n",
  10891. &resp));
  10892. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10893. // PUT without Content-Length
  10894. resp.clear();
  10895. ASSERT_TRUE(send_request(5,
  10896. "PUT /put HTTP/1.1\r\n"
  10897. "Host: localhost\r\n"
  10898. "Connection: close\r\n"
  10899. "\r\n",
  10900. &resp));
  10901. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10902. // PATCH without Content-Length
  10903. resp.clear();
  10904. ASSERT_TRUE(send_request(5,
  10905. "PATCH /patch HTTP/1.1\r\n"
  10906. "Host: localhost\r\n"
  10907. "Connection: close\r\n"
  10908. "\r\n",
  10909. &resp));
  10910. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10911. // DELETE without Content-Length
  10912. resp.clear();
  10913. ASSERT_TRUE(send_request(5,
  10914. "DELETE /delete HTTP/1.1\r\n"
  10915. "Host: localhost\r\n"
  10916. "Connection: close\r\n"
  10917. "\r\n",
  10918. &resp));
  10919. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10920. }
  10921. #endif
  10922. //==============================================================================
  10923. // open_stream() Tests
  10924. //==============================================================================
  10925. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  10926. std::string result;
  10927. char buf[8192];
  10928. ssize_t n;
  10929. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10930. result.append(buf, static_cast<size_t>(n));
  10931. }
  10932. return result;
  10933. }
  10934. // Mock stream for unit tests
  10935. class MockStream : public Stream {
  10936. public:
  10937. std::string data;
  10938. size_t pos = 0;
  10939. ssize_t error_after = -1; // -1 = no error
  10940. explicit MockStream(const std::string &d, ssize_t err = -1)
  10941. : data(d), error_after(err) {}
  10942. bool is_readable() const override { return true; }
  10943. bool wait_readable() const override { return true; }
  10944. bool wait_writable() const override { return true; }
  10945. ssize_t read(char *ptr, size_t size) override {
  10946. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  10947. if (pos >= data.size()) return 0;
  10948. size_t limit =
  10949. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  10950. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  10951. std::memcpy(ptr, data.data() + pos, to_read);
  10952. pos += to_read;
  10953. return static_cast<ssize_t>(to_read);
  10954. }
  10955. ssize_t write(const char *, size_t) override { return -1; }
  10956. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  10957. ip = "127.0.0.1";
  10958. port = 0;
  10959. }
  10960. void get_local_ip_and_port(std::string &ip, int &port) const override {
  10961. ip = "127.0.0.1";
  10962. port = 0;
  10963. }
  10964. socket_t socket() const override { return INVALID_SOCKET; }
  10965. time_t duration() const override { return 0; }
  10966. };
  10967. TEST(StreamHandleTest, Basic) {
  10968. ClientImpl::StreamHandle handle;
  10969. EXPECT_FALSE(handle.is_valid());
  10970. handle.response = detail::make_unique<Response>();
  10971. handle.error = Error::Connection;
  10972. EXPECT_FALSE(handle.is_valid());
  10973. handle.error = Error::Success;
  10974. EXPECT_TRUE(handle.is_valid());
  10975. }
  10976. TEST(BodyReaderTest, Basic) {
  10977. MockStream stream("Hello, World!");
  10978. detail::BodyReader reader;
  10979. reader.stream = &stream;
  10980. reader.content_length = 13;
  10981. char buf[32];
  10982. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10983. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10984. EXPECT_TRUE(reader.eof);
  10985. }
  10986. TEST(BodyReaderTest, NoStream) {
  10987. detail::BodyReader reader;
  10988. char buf[32];
  10989. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10990. EXPECT_EQ(Error::Connection, reader.last_error);
  10991. }
  10992. TEST(BodyReaderTest, Error) {
  10993. MockStream stream("Hello, World!", 5);
  10994. detail::BodyReader reader;
  10995. reader.stream = &stream;
  10996. reader.content_length = 13;
  10997. char buf[32];
  10998. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10999. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11000. EXPECT_EQ(Error::Read, reader.last_error);
  11001. }
  11002. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11003. // Mock-based StreamHandle tests relying on private internals are removed.
  11004. class OpenStreamTest : public ::testing::Test {
  11005. protected:
  11006. void SetUp() override {
  11007. svr_.Get("/hello", [](const Request &, Response &res) {
  11008. res.set_content("Hello World!", "text/plain");
  11009. });
  11010. svr_.Get("/large", [](const Request &, Response &res) {
  11011. res.set_content(std::string(10000, 'X'), "text/plain");
  11012. });
  11013. svr_.Get("/chunked", [](const Request &, Response &res) {
  11014. res.set_chunked_content_provider("text/plain",
  11015. [](size_t offset, DataSink &sink) {
  11016. if (offset < 15) {
  11017. sink.write("chunk", 5);
  11018. return true;
  11019. }
  11020. sink.done();
  11021. return true;
  11022. });
  11023. });
  11024. svr_.Get("/compressible", [](const Request &, Response &res) {
  11025. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11026. DataSink &sink) {
  11027. if (offset < 100 * 1024) {
  11028. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11029. sink.write(chunk.data(), chunk.size());
  11030. return true;
  11031. }
  11032. sink.done();
  11033. return true;
  11034. });
  11035. });
  11036. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11037. [](const Request & /*req*/, Response &res) {
  11038. auto i = new int(0);
  11039. res.set_header("Trailer", "Content-Length, X-Allowed");
  11040. res.set_chunked_content_provider(
  11041. "text/plain",
  11042. [i](size_t /*offset*/, DataSink &sink) {
  11043. switch (*i) {
  11044. case 0: sink.os << "123"; break;
  11045. case 1: sink.os << "456"; break;
  11046. case 2: sink.os << "789"; break;
  11047. case 3: {
  11048. sink.done_with_trailer(
  11049. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11050. } break;
  11051. }
  11052. (*i)++;
  11053. return true;
  11054. },
  11055. [i](bool success) {
  11056. EXPECT_TRUE(success);
  11057. delete i;
  11058. });
  11059. });
  11060. // Echo headers endpoint for header-related tests
  11061. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11062. std::string body;
  11063. for (const auto &h : req.headers) {
  11064. body.append(h.first);
  11065. body.push_back(':');
  11066. body.append(h.second);
  11067. body.push_back('\n');
  11068. }
  11069. res.set_content(body, "text/plain");
  11070. });
  11071. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11072. std::string body;
  11073. for (const auto &h : req.headers) {
  11074. body.append(h.first);
  11075. body.push_back(':');
  11076. body.append(h.second);
  11077. body.push_back('\n');
  11078. }
  11079. res.set_content(body, "text/plain");
  11080. });
  11081. port_ = svr_.bind_to_any_port("127.0.0.1");
  11082. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11083. svr_.wait_until_ready();
  11084. }
  11085. void TearDown() override {
  11086. svr_.stop();
  11087. if (thread_.joinable()) thread_.join();
  11088. }
  11089. Server svr_;
  11090. std::thread thread_;
  11091. int port_ = 0;
  11092. };
  11093. TEST_F(OpenStreamTest, Basic) {
  11094. Client cli("127.0.0.1", port_);
  11095. auto handle = cli.open_stream("GET", "/hello");
  11096. EXPECT_TRUE(handle.is_valid());
  11097. EXPECT_EQ("Hello World!", read_all(handle));
  11098. }
  11099. TEST_F(OpenStreamTest, SmallBuffer) {
  11100. Client cli("127.0.0.1", port_);
  11101. auto handle = cli.open_stream("GET", "/hello");
  11102. std::string result;
  11103. char buf[4];
  11104. ssize_t n;
  11105. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11106. result.append(buf, static_cast<size_t>(n));
  11107. EXPECT_EQ("Hello World!", result);
  11108. }
  11109. TEST_F(OpenStreamTest, DefaultHeaders) {
  11110. Client cli("127.0.0.1", port_);
  11111. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11112. {
  11113. auto handle = cli.open_stream("GET", "/echo-headers");
  11114. ASSERT_TRUE(handle.is_valid());
  11115. auto body = read_all(handle);
  11116. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11117. std::string::npos);
  11118. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11119. std::string::npos);
  11120. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11121. }
  11122. // open_stream POST with body and no explicit content_type should NOT add
  11123. // text/plain Content-Type (behavior differs from non-streaming path), but
  11124. // should include Content-Length
  11125. {
  11126. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11127. ASSERT_TRUE(handle.is_valid());
  11128. auto body = read_all(handle);
  11129. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11130. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11131. }
  11132. // open_stream POST with explicit Content-Type should preserve it
  11133. {
  11134. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11135. {{"Content-Type", "application/custom"}},
  11136. "{}", "application/custom");
  11137. ASSERT_TRUE(handle.is_valid());
  11138. auto body = read_all(handle);
  11139. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11140. }
  11141. // User-specified User-Agent must not be overwritten for stream API
  11142. {
  11143. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11144. {{"User-Agent", "MyAgent/1.2"}});
  11145. ASSERT_TRUE(handle.is_valid());
  11146. auto body = read_all(handle);
  11147. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11148. }
  11149. }
  11150. TEST_F(OpenStreamTest, Large) {
  11151. Client cli("127.0.0.1", port_);
  11152. auto handle = cli.open_stream("GET", "/large");
  11153. EXPECT_EQ(10000u, read_all(handle).size());
  11154. }
  11155. TEST_F(OpenStreamTest, ConnectionError) {
  11156. Client cli("127.0.0.1", 9999);
  11157. auto handle = cli.open_stream("GET", "/hello");
  11158. EXPECT_FALSE(handle.is_valid());
  11159. }
  11160. TEST_F(OpenStreamTest, Chunked) {
  11161. Client cli("127.0.0.1", port_);
  11162. auto handle = cli.open_stream("GET", "/chunked");
  11163. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11164. "Transfer-Encoding") == "chunked");
  11165. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11166. }
  11167. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11168. Client cli("127.0.0.1", port_);
  11169. auto handle =
  11170. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11171. ASSERT_TRUE(handle.is_valid());
  11172. // Consume body to allow trailers to be received/parsed
  11173. auto body = read_all(handle);
  11174. // Explicitly parse trailers (ensure trailers are available for assertion)
  11175. handle.parse_trailers_if_needed();
  11176. EXPECT_EQ(std::string("123456789"), body);
  11177. // The response should include a Trailer header declaring both names
  11178. ASSERT_TRUE(handle.response);
  11179. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11180. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11181. handle.response->get_header_value("Trailer"));
  11182. // Prohibited trailer must not be present
  11183. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11184. // Allowed trailer should be present
  11185. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11186. EXPECT_EQ(std::string("yes"),
  11187. handle.response->get_trailer_value("X-Allowed"));
  11188. // Verify trailers are NOT present as regular headers
  11189. EXPECT_EQ(std::string(""),
  11190. handle.response->get_header_value("Content-Length"));
  11191. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11192. }
  11193. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11194. TEST_F(OpenStreamTest, Gzip) {
  11195. Client cli("127.0.0.1", port_);
  11196. auto handle = cli.open_stream("GET", "/compressible", {},
  11197. {{"Accept-Encoding", "gzip"}});
  11198. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11199. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11200. }
  11201. #endif
  11202. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11203. TEST_F(OpenStreamTest, Brotli) {
  11204. Client cli("127.0.0.1", port_);
  11205. auto handle =
  11206. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11207. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11208. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11209. }
  11210. #endif
  11211. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11212. TEST_F(OpenStreamTest, Zstd) {
  11213. Client cli("127.0.0.1", port_);
  11214. auto handle = cli.open_stream("GET", "/compressible", {},
  11215. {{"Accept-Encoding", "zstd"}});
  11216. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11217. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11218. }
  11219. #endif
  11220. #ifdef CPPHTTPLIB_SSL_ENABLED
  11221. class SSLOpenStreamTest : public ::testing::Test {
  11222. protected:
  11223. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11224. void SetUp() override {
  11225. svr_.Get("/hello", [](const Request &, Response &res) {
  11226. res.set_content("Hello SSL World!", "text/plain");
  11227. });
  11228. svr_.Get("/chunked", [](const Request &, Response &res) {
  11229. res.set_chunked_content_provider("text/plain",
  11230. [](size_t offset, DataSink &sink) {
  11231. if (offset < 15) {
  11232. sink.write("chunk", 5);
  11233. return true;
  11234. }
  11235. sink.done();
  11236. return true;
  11237. });
  11238. });
  11239. svr_.Post("/echo", [](const Request &req, Response &res) {
  11240. res.set_content(req.body, req.get_header_value("Content-Type"));
  11241. });
  11242. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11243. std::string body = req.body;
  11244. res.set_chunked_content_provider(
  11245. "text/plain", [body](size_t offset, DataSink &sink) {
  11246. if (offset < body.size()) {
  11247. sink.write(body.data() + offset, body.size() - offset);
  11248. }
  11249. sink.done();
  11250. return true;
  11251. });
  11252. });
  11253. port_ = svr_.bind_to_any_port("127.0.0.1");
  11254. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11255. svr_.wait_until_ready();
  11256. }
  11257. void TearDown() override {
  11258. svr_.stop();
  11259. if (thread_.joinable()) thread_.join();
  11260. }
  11261. SSLServer svr_;
  11262. std::thread thread_;
  11263. int port_ = 0;
  11264. };
  11265. TEST_F(SSLOpenStreamTest, Basic) {
  11266. SSLClient cli("127.0.0.1", port_);
  11267. cli.enable_server_certificate_verification(false);
  11268. auto handle = cli.open_stream("GET", "/hello");
  11269. ASSERT_TRUE(handle.is_valid());
  11270. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11271. }
  11272. TEST_F(SSLOpenStreamTest, Chunked) {
  11273. SSLClient cli("127.0.0.1", port_);
  11274. cli.enable_server_certificate_verification(false);
  11275. auto handle = cli.open_stream("GET", "/chunked");
  11276. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11277. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11278. "Transfer-Encoding") == "chunked");
  11279. auto body = read_all(handle);
  11280. EXPECT_EQ("chunkchunkchunk", body);
  11281. }
  11282. TEST_F(SSLOpenStreamTest, Post) {
  11283. SSLClient cli("127.0.0.1", port_);
  11284. cli.enable_server_certificate_verification(false);
  11285. auto handle =
  11286. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11287. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11288. EXPECT_EQ(200, handle.response->status);
  11289. auto body = read_all(handle);
  11290. EXPECT_EQ("Hello SSL POST", body);
  11291. }
  11292. TEST_F(SSLOpenStreamTest, PostChunked) {
  11293. SSLClient cli("127.0.0.1", port_);
  11294. cli.enable_server_certificate_verification(false);
  11295. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11296. "Chunked SSL Data", "text/plain");
  11297. ASSERT_TRUE(handle.is_valid());
  11298. EXPECT_EQ(200, handle.response->status);
  11299. auto body = read_all(handle);
  11300. EXPECT_EQ("Chunked SSL Data", body);
  11301. }
  11302. #endif // CPPHTTPLIB_SSL_ENABLED
  11303. //==============================================================================
  11304. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11305. // results for various scenarios.
  11306. //==============================================================================
  11307. TEST(ParityTest, GetVsOpenStream) {
  11308. Server svr;
  11309. const std::string path = "/parity";
  11310. const std::string content = "Parity test content: hello world";
  11311. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11312. res.set_content(content, "text/plain");
  11313. });
  11314. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11315. auto se = detail::scope_exit([&] {
  11316. svr.stop();
  11317. t.join();
  11318. ASSERT_FALSE(svr.is_running());
  11319. });
  11320. svr.wait_until_ready();
  11321. Client cli(HOST, PORT);
  11322. // Non-stream path
  11323. auto r1 = cli.Get(path);
  11324. ASSERT_TRUE(r1);
  11325. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11326. // Stream path
  11327. auto h = cli.open_stream("GET", path);
  11328. ASSERT_TRUE(h.is_valid());
  11329. EXPECT_EQ(r1->body, read_all(h));
  11330. }
  11331. // Helper to compress data with provided compressor type T
  11332. template <typename Compressor>
  11333. static std::string compress_payload_for_parity(const std::string &in) {
  11334. std::string out;
  11335. Compressor compressor;
  11336. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11337. [&](const char *data, size_t n) {
  11338. out.append(data, n);
  11339. return true;
  11340. });
  11341. EXPECT_TRUE(ok);
  11342. return out;
  11343. }
  11344. // Helper function for compression parity tests
  11345. template <typename Compressor>
  11346. static void test_compression_parity(const std::string &original,
  11347. const std::string &path,
  11348. const std::string &encoding) {
  11349. const std::string compressed =
  11350. compress_payload_for_parity<Compressor>(original);
  11351. Server svr;
  11352. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11353. res.set_content(compressed, "application/octet-stream");
  11354. res.set_header("Content-Encoding", encoding);
  11355. });
  11356. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11357. auto se = detail::scope_exit([&] {
  11358. svr.stop();
  11359. t.join();
  11360. ASSERT_FALSE(svr.is_running());
  11361. });
  11362. svr.wait_until_ready();
  11363. Client cli(HOST, PORT);
  11364. // Non-streaming
  11365. {
  11366. auto res = cli.Get(path);
  11367. ASSERT_TRUE(res);
  11368. EXPECT_EQ(StatusCode::OK_200, res->status);
  11369. EXPECT_EQ(original, res->body);
  11370. }
  11371. // Streaming
  11372. {
  11373. auto h = cli.open_stream("GET", path);
  11374. ASSERT_TRUE(h.is_valid());
  11375. EXPECT_EQ(original, read_all(h));
  11376. }
  11377. }
  11378. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11379. TEST(ParityTest, Gzip) {
  11380. test_compression_parity<detail::gzip_compressor>(
  11381. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11382. }
  11383. #endif
  11384. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11385. TEST(ParityTest, Brotli) {
  11386. test_compression_parity<detail::brotli_compressor>(
  11387. "Hello, brotli parity test payload", "/parity-br", "br");
  11388. }
  11389. #endif
  11390. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11391. TEST(ParityTest, Zstd) {
  11392. test_compression_parity<detail::zstd_compressor>(
  11393. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11394. }
  11395. #endif
  11396. //==============================================================================
  11397. // New Stream API Tests
  11398. //==============================================================================
  11399. inline std::string read_body(httplib::stream::Result &result) {
  11400. std::string body;
  11401. while (result.next()) {
  11402. body.append(result.data(), result.size());
  11403. }
  11404. return body;
  11405. }
  11406. TEST(ClientConnectionTest, Basic) {
  11407. httplib::ClientConnection conn;
  11408. EXPECT_FALSE(conn.is_open());
  11409. conn.sock = 1;
  11410. EXPECT_TRUE(conn.is_open());
  11411. httplib::ClientConnection conn2(std::move(conn));
  11412. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11413. conn2.sock = INVALID_SOCKET;
  11414. }
  11415. // Unified test server for all stream::* tests
  11416. class StreamApiTest : public ::testing::Test {
  11417. protected:
  11418. void SetUp() override {
  11419. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11420. res.set_content("Hello World!", "text/plain");
  11421. });
  11422. svr_.Get("/echo-params",
  11423. [](const httplib::Request &req, httplib::Response &res) {
  11424. std::string r;
  11425. for (const auto &p : req.params) {
  11426. if (!r.empty()) r += "&";
  11427. r += p.first + "=" + p.second;
  11428. }
  11429. res.set_content(r, "text/plain");
  11430. });
  11431. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11432. res.set_content(req.body, req.get_header_value("Content-Type"));
  11433. });
  11434. svr_.Post("/echo-headers",
  11435. [](const httplib::Request &req, httplib::Response &res) {
  11436. std::string r;
  11437. for (const auto &h : req.headers)
  11438. r += h.first + ": " + h.second + "\n";
  11439. res.set_content(r, "text/plain");
  11440. });
  11441. svr_.Post("/echo-params",
  11442. [](const httplib::Request &req, httplib::Response &res) {
  11443. std::string r = "params:";
  11444. for (const auto &p : req.params)
  11445. r += p.first + "=" + p.second + ";";
  11446. res.set_content(r + " body:" + req.body, "text/plain");
  11447. });
  11448. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11449. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11450. });
  11451. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11452. res.set_content("PUT:" + req.body, "text/plain");
  11453. });
  11454. svr_.Patch("/echo",
  11455. [](const httplib::Request &req, httplib::Response &res) {
  11456. res.set_content("PATCH:" + req.body, "text/plain");
  11457. });
  11458. svr_.Delete(
  11459. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11460. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11461. "text/plain");
  11462. });
  11463. svr_.Get("/head-test",
  11464. [](const httplib::Request &, httplib::Response &res) {
  11465. res.set_content("body for HEAD", "text/plain");
  11466. });
  11467. svr_.Options("/options",
  11468. [](const httplib::Request &, httplib::Response &res) {
  11469. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11470. });
  11471. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11472. svr_.wait_until_ready();
  11473. }
  11474. void TearDown() override {
  11475. svr_.stop();
  11476. if (thread_.joinable()) thread_.join();
  11477. }
  11478. httplib::Server svr_;
  11479. std::thread thread_;
  11480. };
  11481. // stream::Get tests
  11482. TEST_F(StreamApiTest, GetBasic) {
  11483. httplib::Client cli(HOST, PORT);
  11484. auto result = httplib::stream::Get(cli, "/hello");
  11485. ASSERT_TRUE(result.is_valid());
  11486. EXPECT_EQ(200, result.status());
  11487. EXPECT_EQ("Hello World!", read_body(result));
  11488. }
  11489. TEST_F(StreamApiTest, GetWithParams) {
  11490. httplib::Client cli(HOST, PORT);
  11491. httplib::Params params{{"foo", "bar"}};
  11492. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11493. ASSERT_TRUE(result.is_valid());
  11494. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11495. }
  11496. TEST_F(StreamApiTest, GetConnectionError) {
  11497. httplib::Client cli(HOST, 9999);
  11498. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11499. }
  11500. TEST_F(StreamApiTest, Get404) {
  11501. httplib::Client cli(HOST, PORT);
  11502. auto result = httplib::stream::Get(cli, "/nonexistent");
  11503. EXPECT_TRUE(result.is_valid());
  11504. EXPECT_EQ(404, result.status());
  11505. }
  11506. // stream::Post tests
  11507. TEST_F(StreamApiTest, PostBasic) {
  11508. httplib::Client cli(HOST, PORT);
  11509. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11510. "application/json");
  11511. ASSERT_TRUE(result.is_valid());
  11512. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11513. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11514. }
  11515. TEST_F(StreamApiTest, PostWithHeaders) {
  11516. httplib::Client cli(HOST, PORT);
  11517. httplib::Headers headers{{"X-Custom", "value"}};
  11518. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11519. "text/plain");
  11520. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11521. }
  11522. TEST_F(StreamApiTest, PostWithParams) {
  11523. httplib::Client cli(HOST, PORT);
  11524. httplib::Params params{{"k", "v"}};
  11525. auto result =
  11526. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11527. auto body = read_body(result);
  11528. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11529. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11530. }
  11531. TEST_F(StreamApiTest, PostLarge) {
  11532. httplib::Client cli(HOST, PORT);
  11533. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11534. size_t total = 0;
  11535. while (result.next()) {
  11536. total += result.size();
  11537. }
  11538. EXPECT_EQ(100u * 1024u, total);
  11539. }
  11540. // stream::Put/Patch tests
  11541. TEST_F(StreamApiTest, PutAndPatch) {
  11542. httplib::Client cli(HOST, PORT);
  11543. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11544. EXPECT_EQ("PUT:test", read_body(put));
  11545. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11546. EXPECT_EQ("PATCH:test", read_body(patch));
  11547. }
  11548. // stream::Delete tests
  11549. TEST_F(StreamApiTest, Delete) {
  11550. httplib::Client cli(HOST, PORT);
  11551. auto del1 = httplib::stream::Delete(cli, "/resource");
  11552. EXPECT_EQ("Deleted", read_body(del1));
  11553. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11554. EXPECT_EQ("Deleted:data", read_body(del2));
  11555. }
  11556. // stream::Head/Options tests
  11557. TEST_F(StreamApiTest, HeadAndOptions) {
  11558. httplib::Client cli(HOST, PORT);
  11559. auto head = httplib::stream::Head(cli, "/head-test");
  11560. EXPECT_TRUE(head.is_valid());
  11561. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11562. auto opts = httplib::stream::Options(cli, "/options");
  11563. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11564. }
  11565. // SSL stream::* tests
  11566. #ifdef CPPHTTPLIB_SSL_ENABLED
  11567. class SSLStreamApiTest : public ::testing::Test {
  11568. protected:
  11569. void SetUp() override {
  11570. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11571. res.set_content("Hello SSL!", "text/plain");
  11572. });
  11573. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11574. res.set_content(req.body, "text/plain");
  11575. });
  11576. port_ = svr_.bind_to_any_port("127.0.0.1");
  11577. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11578. svr_.wait_until_ready();
  11579. }
  11580. void TearDown() override {
  11581. svr_.stop();
  11582. if (thread_.joinable()) thread_.join();
  11583. }
  11584. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11585. std::thread thread_;
  11586. int port_ = 0;
  11587. };
  11588. TEST_F(SSLStreamApiTest, GetAndPost) {
  11589. httplib::SSLClient cli("127.0.0.1", port_);
  11590. cli.enable_server_certificate_verification(false);
  11591. auto get = httplib::stream::Get(cli, "/hello");
  11592. EXPECT_EQ("Hello SSL!", read_body(get));
  11593. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11594. EXPECT_EQ("test", read_body(post));
  11595. }
  11596. #endif
  11597. // Tests for Error::Timeout and Error::ConnectionClosed error types
  11598. // These errors are set in SocketStream/SSLSocketStream and propagated through
  11599. // BodyReader
  11600. TEST(ErrorHandlingTest, StreamReadTimeout) {
  11601. // Test that read timeout during streaming is detected
  11602. // Use a large content-length response where server delays mid-stream
  11603. Server svr;
  11604. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11605. // Send a large response with delay in the middle
  11606. res.set_content_provider(
  11607. 1000, // content_length
  11608. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  11609. if (offset < 100) {
  11610. // Send first 100 bytes immediately
  11611. std::string data(100, 'A');
  11612. sink.write(data.c_str(), data.size());
  11613. return true;
  11614. }
  11615. // Then delay longer than client timeout
  11616. std::this_thread::sleep_for(std::chrono::seconds(3));
  11617. std::string data(900, 'B');
  11618. sink.write(data.c_str(), data.size());
  11619. return true;
  11620. });
  11621. });
  11622. auto port = 8091;
  11623. std::thread t([&]() { svr.listen("localhost", port); });
  11624. svr.wait_until_ready();
  11625. Client cli("localhost", port);
  11626. cli.set_read_timeout(1, 0); // 1 second timeout
  11627. auto handle = cli.open_stream("GET", "/slow-stream");
  11628. ASSERT_TRUE(handle.is_valid());
  11629. char buf[256];
  11630. ssize_t total = 0;
  11631. ssize_t n;
  11632. bool got_error = false;
  11633. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11634. total += n;
  11635. }
  11636. if (n < 0) {
  11637. got_error = true;
  11638. // Should be timeout or read error
  11639. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11640. handle.get_read_error() == Error::Read)
  11641. << "Actual error: " << to_string(handle.get_read_error());
  11642. }
  11643. // Either we got an error, or we got less data than expected
  11644. EXPECT_TRUE(got_error || total < 1000)
  11645. << "Expected timeout but got all " << total << " bytes";
  11646. svr.stop();
  11647. t.join();
  11648. }
  11649. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11650. // Test connection closed detection via BodyReader
  11651. Server svr;
  11652. std::atomic<bool> close_now{false};
  11653. svr.Get("/will-close", [&](const Request &, Response &res) {
  11654. res.set_content_provider(
  11655. 10000, // Large content_length that we won't fully send
  11656. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11657. if (offset < 100) {
  11658. std::string data(100, 'X');
  11659. sink.write(data.c_str(), data.size());
  11660. return true;
  11661. }
  11662. // Wait for signal then abort
  11663. while (!close_now) {
  11664. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11665. }
  11666. return false; // Abort - server will close connection
  11667. });
  11668. });
  11669. auto port = 8092;
  11670. std::thread t([&]() { svr.listen("localhost", port); });
  11671. svr.wait_until_ready();
  11672. Client cli("localhost", port);
  11673. auto handle = cli.open_stream("GET", "/will-close");
  11674. ASSERT_TRUE(handle.is_valid());
  11675. char buf[256];
  11676. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11677. EXPECT_GT(n, 0) << "First read should succeed";
  11678. // Signal server to close
  11679. close_now = true;
  11680. // Keep reading until error or EOF
  11681. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11682. // Keep reading
  11683. }
  11684. // Should get an error since content_length wasn't satisfied
  11685. if (n < 0) {
  11686. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11687. handle.get_read_error() == Error::Read)
  11688. << "Actual error: " << to_string(handle.get_read_error());
  11689. }
  11690. svr.stop();
  11691. t.join();
  11692. }
  11693. #ifdef CPPHTTPLIB_SSL_ENABLED
  11694. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11695. // Test that read timeout during SSL streaming is detected
  11696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11697. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11698. res.set_content_provider(
  11699. 1000, "text/plain",
  11700. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11701. if (offset < 100) {
  11702. std::string data(100, 'A');
  11703. sink.write(data.c_str(), data.size());
  11704. return true;
  11705. }
  11706. std::this_thread::sleep_for(std::chrono::seconds(3));
  11707. std::string data(900, 'B');
  11708. sink.write(data.c_str(), data.size());
  11709. return true;
  11710. });
  11711. });
  11712. auto port = 8093;
  11713. std::thread t([&]() { svr.listen("localhost", port); });
  11714. svr.wait_until_ready();
  11715. SSLClient cli("localhost", port);
  11716. cli.enable_server_certificate_verification(false);
  11717. cli.set_read_timeout(1, 0); // 1 second timeout
  11718. auto handle = cli.open_stream("GET", "/slow-stream");
  11719. ASSERT_TRUE(handle.is_valid());
  11720. char buf[256];
  11721. ssize_t total = 0;
  11722. ssize_t n;
  11723. bool got_error = false;
  11724. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11725. total += n;
  11726. }
  11727. if (n < 0) {
  11728. got_error = true;
  11729. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11730. handle.get_read_error() == Error::Read)
  11731. << "Actual error: " << to_string(handle.get_read_error());
  11732. }
  11733. EXPECT_TRUE(got_error || total < 1000)
  11734. << "Expected timeout but got all " << total << " bytes";
  11735. svr.stop();
  11736. t.join();
  11737. }
  11738. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11739. // Test SSL connection closed detection
  11740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11741. std::atomic<bool> close_now{false};
  11742. svr.Get("/will-close", [&](const Request &, Response &res) {
  11743. res.set_content_provider(
  11744. 10000, "text/plain",
  11745. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11746. if (offset < 100) {
  11747. std::string data(100, 'X');
  11748. sink.write(data.c_str(), data.size());
  11749. return true;
  11750. }
  11751. while (!close_now) {
  11752. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11753. }
  11754. return false;
  11755. });
  11756. });
  11757. auto port = 8094;
  11758. std::thread t([&]() { svr.listen("localhost", port); });
  11759. svr.wait_until_ready();
  11760. SSLClient cli("localhost", port);
  11761. cli.enable_server_certificate_verification(false);
  11762. auto handle = cli.open_stream("GET", "/will-close");
  11763. ASSERT_TRUE(handle.is_valid());
  11764. char buf[256];
  11765. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11766. EXPECT_GT(n, 0);
  11767. // Signal server to close
  11768. close_now = true;
  11769. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11770. // Keep reading
  11771. }
  11772. if (n < 0) {
  11773. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11774. handle.get_read_error() == Error::Read)
  11775. << "Actual error: " << to_string(handle.get_read_error());
  11776. }
  11777. svr.stop();
  11778. t.join();
  11779. }
  11780. #endif
  11781. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11782. using namespace httplib;
  11783. // Create a test file
  11784. const char *fname = "etag_testfile.txt";
  11785. const char *content = "etag-content";
  11786. {
  11787. std::ofstream ofs(fname);
  11788. ofs << content;
  11789. ASSERT_TRUE(ofs.good());
  11790. }
  11791. Server svr;
  11792. svr.set_mount_point("/static", ".");
  11793. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11794. svr.wait_until_ready();
  11795. Client cli(HOST, PORT);
  11796. // First request: should get 200 with ETag header
  11797. auto res1 = cli.Get("/static/etag_testfile.txt");
  11798. ASSERT_TRUE(res1);
  11799. ASSERT_EQ(200, res1->status);
  11800. ASSERT_TRUE(res1->has_header("ETag"));
  11801. std::string etag = res1->get_header_value("ETag");
  11802. EXPECT_FALSE(etag.empty());
  11803. // Verify ETag format: W/"hex-hex"
  11804. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11805. EXPECT_EQ('W', etag[0]);
  11806. EXPECT_EQ('/', etag[1]);
  11807. EXPECT_EQ('"', etag[2]);
  11808. EXPECT_EQ('"', etag.back());
  11809. // Exact match: expect 304 Not Modified
  11810. Headers h2 = {{"If-None-Match", etag}};
  11811. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11812. ASSERT_TRUE(res2);
  11813. EXPECT_EQ(304, res2->status);
  11814. // Wildcard match: expect 304 Not Modified
  11815. Headers h3 = {{"If-None-Match", "*"}};
  11816. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11817. ASSERT_TRUE(res3);
  11818. EXPECT_EQ(304, res3->status);
  11819. // Non-matching ETag: expect 200
  11820. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11821. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11822. ASSERT_TRUE(res4);
  11823. EXPECT_EQ(200, res4->status);
  11824. // Multiple ETags with one matching: expect 304
  11825. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11826. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11827. ASSERT_TRUE(res5);
  11828. EXPECT_EQ(304, res5->status);
  11829. svr.stop();
  11830. t.join();
  11831. std::remove(fname);
  11832. }
  11833. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11834. using namespace httplib;
  11835. Server svr;
  11836. svr.set_mount_point("/static", ".");
  11837. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11838. svr.wait_until_ready();
  11839. Client cli(HOST, PORT);
  11840. // Send If-None-Match: * to a non-existent file
  11841. Headers h = {{"If-None-Match", "*"}};
  11842. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11843. ASSERT_TRUE(res);
  11844. EXPECT_EQ(404, res->status);
  11845. svr.stop();
  11846. t.join();
  11847. }
  11848. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  11849. using namespace httplib;
  11850. // Create a test file
  11851. const char *fname = "etag_boundary_testfile.txt";
  11852. const char *content = "boundary-test";
  11853. {
  11854. std::ofstream ofs(fname);
  11855. ofs << content;
  11856. ASSERT_TRUE(ofs.good());
  11857. }
  11858. Server svr;
  11859. svr.set_mount_point("/static", ".");
  11860. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11861. svr.wait_until_ready();
  11862. Client cli(HOST, PORT);
  11863. // Get the actual ETag
  11864. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  11865. ASSERT_TRUE(res1);
  11866. ASSERT_EQ(200, res1->status);
  11867. ASSERT_TRUE(res1->has_header("ETag"));
  11868. std::string etag = res1->get_header_value("ETag");
  11869. // Test 1: Very long ETag value (longer than actual ETag)
  11870. // Should NOT match and return 200 (not trigger out-of-bounds read)
  11871. Headers h1 = {{"If-None-Match", "W/"
  11872. "\"very-long-etag-value-that-is-much-longer-"
  11873. "than-the-actual-etag-value\""}};
  11874. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  11875. ASSERT_TRUE(res2);
  11876. EXPECT_EQ(200, res2->status); // Should not match
  11877. // Test 2: Long string followed by wildcard
  11878. // Should match on "*" and return 304 (without out-of-bounds read on the long
  11879. // string)
  11880. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  11881. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  11882. ASSERT_TRUE(res3);
  11883. EXPECT_EQ(304, res3->status); // Should match on "*"
  11884. // Test 3: Wildcard followed by long string
  11885. // Should match on "*" immediately and return 304
  11886. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  11887. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  11888. ASSERT_TRUE(res4);
  11889. EXPECT_EQ(304, res4->status); // Should match on "*"
  11890. // Test 4: Multiple long non-matching values
  11891. // Should NOT match and return 200 (test that all comparisons are safe)
  11892. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  11893. "W/\"second-long-non-matching-value\", "
  11894. "W/\"third-long-non-matching-value\""}};
  11895. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  11896. ASSERT_TRUE(res5);
  11897. EXPECT_EQ(200, res5->status); // Should not match
  11898. // Test 5: Single character that is not "*" (edge case)
  11899. Headers h5 = {{"If-None-Match", "X"}};
  11900. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  11901. ASSERT_TRUE(res6);
  11902. EXPECT_EQ(200, res6->status); // Should not match
  11903. svr.stop();
  11904. t.join();
  11905. std::remove(fname);
  11906. }
  11907. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  11908. using namespace httplib;
  11909. // Create a test file
  11910. const char *fname = "ims_testfile.txt";
  11911. const char *content = "if-modified-since-test";
  11912. {
  11913. std::ofstream ofs(fname);
  11914. ofs << content;
  11915. ASSERT_TRUE(ofs.good());
  11916. }
  11917. Server svr;
  11918. svr.set_mount_point("/static", ".");
  11919. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11920. svr.wait_until_ready();
  11921. Client cli(HOST, PORT);
  11922. // First request: should get 200 with Last-Modified header
  11923. auto res1 = cli.Get("/static/ims_testfile.txt");
  11924. ASSERT_TRUE(res1);
  11925. ASSERT_EQ(200, res1->status);
  11926. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11927. std::string last_modified = res1->get_header_value("Last-Modified");
  11928. EXPECT_FALSE(last_modified.empty());
  11929. // If-Modified-Since with same time: expect 304
  11930. Headers h2 = {{"If-Modified-Since", last_modified}};
  11931. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  11932. ASSERT_TRUE(res2);
  11933. EXPECT_EQ(304, res2->status);
  11934. // If-Modified-Since with future time: expect 304
  11935. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11936. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  11937. ASSERT_TRUE(res3);
  11938. EXPECT_EQ(304, res3->status);
  11939. // If-Modified-Since with past time: expect 200
  11940. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11941. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  11942. ASSERT_TRUE(res4);
  11943. EXPECT_EQ(200, res4->status);
  11944. // If-None-Match takes precedence over If-Modified-Since
  11945. // (send matching ETag with old If-Modified-Since -> should still be 304)
  11946. ASSERT_TRUE(res1->has_header("ETag"));
  11947. std::string etag = res1->get_header_value("ETag");
  11948. Headers h5 = {{"If-None-Match", etag},
  11949. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11950. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  11951. ASSERT_TRUE(res5);
  11952. EXPECT_EQ(304, res5->status);
  11953. svr.stop();
  11954. t.join();
  11955. std::remove(fname);
  11956. }
  11957. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  11958. using namespace httplib;
  11959. Server svr;
  11960. // Endpoint that returns compressible content
  11961. svr.Get("/compressible", [](const Request &, Response &res) {
  11962. // Return a large enough body to trigger compression
  11963. std::string body(1000, 'a');
  11964. res.set_content(body, "text/plain");
  11965. });
  11966. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11967. svr.wait_until_ready();
  11968. Client cli(HOST, PORT);
  11969. // Request with gzip support: should get Vary header when compressed
  11970. cli.set_compress(true);
  11971. auto res1 = cli.Get("/compressible");
  11972. ASSERT_TRUE(res1);
  11973. EXPECT_EQ(200, res1->status);
  11974. // If Content-Encoding is set, Vary should also be set
  11975. if (res1->has_header("Content-Encoding")) {
  11976. EXPECT_TRUE(res1->has_header("Vary"));
  11977. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  11978. }
  11979. // Request without Accept-Encoding header: should not have compression
  11980. Headers h_no_compress;
  11981. auto res2 = cli.Get("/compressible", h_no_compress);
  11982. ASSERT_TRUE(res2);
  11983. EXPECT_EQ(200, res2->status);
  11984. // Verify Vary header is present when compression is applied
  11985. // (the exact behavior depends on server configuration)
  11986. svr.stop();
  11987. t.join();
  11988. }
  11989. TEST(ETagTest, IfRangeWithETag) {
  11990. using namespace httplib;
  11991. // Create a test file with known content
  11992. const char *fname = "if_range_testfile.txt";
  11993. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  11994. {
  11995. std::ofstream ofs(fname);
  11996. ofs << content;
  11997. ASSERT_TRUE(ofs.good());
  11998. }
  11999. Server svr;
  12000. svr.set_mount_point("/static", ".");
  12001. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12002. svr.wait_until_ready();
  12003. Client cli(HOST, PORT);
  12004. // First request: get ETag
  12005. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12006. ASSERT_TRUE(res1);
  12007. ASSERT_EQ(200, res1->status);
  12008. ASSERT_TRUE(res1->has_header("ETag"));
  12009. std::string etag = res1->get_header_value("ETag");
  12010. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12011. // Since our server generates weak ETags (W/"..."), If-Range with our
  12012. // ETag should NOT result in partial content - it should return full content.
  12013. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12014. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12015. ASSERT_TRUE(res2);
  12016. // Weak ETag in If-Range -> full content (200), not partial (206)
  12017. EXPECT_EQ(200, res2->status);
  12018. EXPECT_EQ(content, res2->body);
  12019. EXPECT_FALSE(res2->has_header("Content-Range"));
  12020. // Range request with non-matching If-Range (ETag): should get 200 (full
  12021. // content)
  12022. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12023. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12024. ASSERT_TRUE(res3);
  12025. EXPECT_EQ(200, res3->status);
  12026. EXPECT_EQ(content, res3->body);
  12027. EXPECT_FALSE(res3->has_header("Content-Range"));
  12028. // Range request with strong ETag (hypothetical - our server doesn't generate
  12029. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12030. // should return full content)
  12031. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12032. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12033. ASSERT_TRUE(res4);
  12034. EXPECT_EQ(200, res4->status);
  12035. EXPECT_EQ(content, res4->body);
  12036. EXPECT_FALSE(res4->has_header("Content-Range"));
  12037. svr.stop();
  12038. t.join();
  12039. std::remove(fname);
  12040. }
  12041. TEST(ETagTest, IfRangeWithDate) {
  12042. using namespace httplib;
  12043. // Create a test file
  12044. const char *fname = "if_range_date_testfile.txt";
  12045. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12046. {
  12047. std::ofstream ofs(fname);
  12048. ofs << content;
  12049. ASSERT_TRUE(ofs.good());
  12050. }
  12051. Server svr;
  12052. svr.set_mount_point("/static", ".");
  12053. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12054. svr.wait_until_ready();
  12055. Client cli(HOST, PORT);
  12056. // First request: get Last-Modified
  12057. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12058. ASSERT_TRUE(res1);
  12059. ASSERT_EQ(200, res1->status);
  12060. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12061. std::string last_modified = res1->get_header_value("Last-Modified");
  12062. // Range request with matching If-Range (date): should get 206
  12063. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12064. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12065. ASSERT_TRUE(res2);
  12066. EXPECT_EQ(206, res2->status);
  12067. EXPECT_EQ("FGHIJ", res2->body);
  12068. // Range request with old If-Range date: should get 200 (full content)
  12069. Headers h3 = {{"Range", "bytes=5-9"},
  12070. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12071. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12072. ASSERT_TRUE(res3);
  12073. EXPECT_EQ(200, res3->status);
  12074. EXPECT_EQ(content, res3->body);
  12075. // Range request with future If-Range date: should get 206
  12076. Headers h4 = {{"Range", "bytes=0-4"},
  12077. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12078. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12079. ASSERT_TRUE(res4);
  12080. EXPECT_EQ(206, res4->status);
  12081. EXPECT_EQ("ABCDE", res4->body);
  12082. svr.stop();
  12083. t.join();
  12084. std::remove(fname);
  12085. }
  12086. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12087. using namespace httplib;
  12088. const char *fname = "etag_malformed.txt";
  12089. const char *content = "malformed-etag";
  12090. {
  12091. std::ofstream ofs(fname);
  12092. ofs << content;
  12093. ASSERT_TRUE(ofs.good());
  12094. }
  12095. Server svr;
  12096. svr.set_mount_point("/static", ".");
  12097. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12098. svr.wait_until_ready();
  12099. Client cli(HOST, PORT);
  12100. // baseline: should get 200 and an ETag
  12101. auto res1 = cli.Get("/static/etag_malformed.txt");
  12102. ASSERT_TRUE(res1);
  12103. ASSERT_EQ(200, res1->status);
  12104. ASSERT_TRUE(res1->has_header("ETag"));
  12105. // Malformed ETag value (missing quotes) should be treated as non-matching
  12106. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12107. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12108. ASSERT_TRUE(res_bad);
  12109. EXPECT_EQ(200, res_bad->status);
  12110. // Whitespace-only header value should be considered invalid / non-matching
  12111. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12112. "Host: localhost\r\n"
  12113. "If-None-Match: \r\n"
  12114. "Connection: close\r\n"
  12115. "\r\n";
  12116. std::string out;
  12117. ASSERT_TRUE(send_request(5, raw_req, &out));
  12118. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12119. svr.stop();
  12120. t.join();
  12121. std::remove(fname);
  12122. }
  12123. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12124. using namespace httplib;
  12125. const char *fname = "ims_invalid_format.txt";
  12126. const char *content = "ims-bad-format";
  12127. {
  12128. std::ofstream ofs(fname);
  12129. ofs << content;
  12130. ASSERT_TRUE(ofs.good());
  12131. }
  12132. Server svr;
  12133. svr.set_mount_point("/static", ".");
  12134. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12135. svr.wait_until_ready();
  12136. Client cli(HOST, PORT);
  12137. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12138. ASSERT_TRUE(res1);
  12139. ASSERT_EQ(200, res1->status);
  12140. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12141. // If-Modified-Since with invalid format should not result in 304
  12142. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12143. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12144. ASSERT_TRUE(res_bad);
  12145. EXPECT_EQ(200, res_bad->status);
  12146. // If-Range with invalid date format should be treated as mismatch -> full
  12147. // content (200)
  12148. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12149. {"If-Range", "invalid-date"}};
  12150. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12151. ASSERT_TRUE(res_ifrange);
  12152. EXPECT_EQ(200, res_ifrange->status);
  12153. svr.stop();
  12154. t.join();
  12155. std::remove(fname);
  12156. }
  12157. TEST(ETagTest, IfRangeWithMalformedETag) {
  12158. using namespace httplib;
  12159. const char *fname = "ifrange_malformed.txt";
  12160. const std::string content = "0123456789";
  12161. {
  12162. std::ofstream ofs(fname);
  12163. ofs << content;
  12164. ASSERT_TRUE(ofs.good());
  12165. }
  12166. Server svr;
  12167. svr.set_mount_point("/static", ".");
  12168. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12169. svr.wait_until_ready();
  12170. Client cli(HOST, PORT);
  12171. // First request: get ETag
  12172. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12173. ASSERT_TRUE(res1);
  12174. ASSERT_EQ(200, res1->status);
  12175. ASSERT_TRUE(res1->has_header("ETag"));
  12176. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12177. // full content (200)
  12178. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12179. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12180. ASSERT_TRUE(res2);
  12181. EXPECT_EQ(200, res2->status);
  12182. EXPECT_EQ(content, res2->body);
  12183. svr.stop();
  12184. t.join();
  12185. std::remove(fname);
  12186. }
  12187. TEST(ETagTest, ExtremeLargeDateValues) {
  12188. using namespace httplib;
  12189. const char *fname = "ims_extreme_date.txt";
  12190. const char *content = "ims-extreme-date";
  12191. {
  12192. std::ofstream ofs(fname);
  12193. ofs << content;
  12194. ASSERT_TRUE(ofs.good());
  12195. }
  12196. Server svr;
  12197. svr.set_mount_point("/static", ".");
  12198. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12199. svr.wait_until_ready();
  12200. Client cli(HOST, PORT);
  12201. auto res1 = cli.Get(std::string("/static/") + fname);
  12202. ASSERT_TRUE(res1);
  12203. ASSERT_EQ(200, res1->status);
  12204. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12205. // Extremely large year that may overflow date parsing routines.
  12206. Headers h_large_date = {
  12207. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12208. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12209. ASSERT_TRUE(res_bad);
  12210. // Expect server to treat this as invalid/mismatch and return full content
  12211. EXPECT_EQ(200, res_bad->status);
  12212. // If-Range with extremely large date should be treated as mismatch -> full
  12213. // content (200)
  12214. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12215. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12216. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12217. ASSERT_TRUE(res_ifrange);
  12218. EXPECT_EQ(200, res_ifrange->status);
  12219. svr.stop();
  12220. t.join();
  12221. std::remove(fname);
  12222. }
  12223. TEST(ETagTest, NegativeFileModificationTime) {
  12224. using namespace httplib;
  12225. const char *fname = "ims_negative_mtime.txt";
  12226. const std::string content = "negative-mtime";
  12227. {
  12228. std::ofstream ofs(fname);
  12229. ofs << content;
  12230. ASSERT_TRUE(ofs.good());
  12231. }
  12232. // Try to set file mtime to a negative value. This may fail on some
  12233. // platforms/filesystems; if it fails, the test will still verify server
  12234. // behaves safely by performing a regular conditional request.
  12235. #if defined(__APPLE__) || defined(__linux__)
  12236. bool set_negative = false;
  12237. do {
  12238. struct timeval times[2];
  12239. // access time: now
  12240. times[0].tv_sec = time(nullptr);
  12241. times[0].tv_usec = 0;
  12242. // modification time: negative (e.g., -1)
  12243. times[1].tv_sec = -1;
  12244. times[1].tv_usec = 0;
  12245. if (utimes(fname, times) == 0) { set_negative = true; }
  12246. } while (0);
  12247. #else
  12248. bool set_negative = false;
  12249. #endif
  12250. Server svr;
  12251. svr.set_mount_point("/static", ".");
  12252. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12253. svr.wait_until_ready();
  12254. Client cli(HOST, PORT);
  12255. auto res1 = cli.Get(std::string("/static/") + fname);
  12256. ASSERT_TRUE(res1);
  12257. ASSERT_EQ(200, res1->status);
  12258. bool has_last_modified = res1->has_header("Last-Modified");
  12259. std::string last_modified;
  12260. if (has_last_modified) {
  12261. last_modified = res1->get_header_value("Last-Modified");
  12262. }
  12263. if (set_negative) {
  12264. // If we successfully set a negative mtime, ensure server returns a
  12265. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12266. // with an old date and ensure server handles it without crash.
  12267. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12268. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12269. ASSERT_TRUE(res2);
  12270. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12271. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12272. } else {
  12273. // Could not set negative mtime on this platform; fall back to verifying
  12274. // that normal invalid/malformed dates are treated safely (non-304).
  12275. Headers h_bad_date = {
  12276. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12277. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12278. ASSERT_TRUE(res_bad);
  12279. EXPECT_EQ(200, res_bad->status);
  12280. }
  12281. svr.stop();
  12282. t.join();
  12283. std::remove(fname);
  12284. }
  12285. //==============================================================================
  12286. // SSE Parsing Tests
  12287. //==============================================================================
  12288. class SSEParsingTest : public ::testing::Test {
  12289. protected:
  12290. // Test helper that mimics SSE parsing behavior
  12291. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12292. int &retry_ms) {
  12293. // Blank line signals end of event
  12294. if (line.empty() || line == "\r") { return true; }
  12295. // Lines starting with ':' are comments (ignored)
  12296. if (!line.empty() && line[0] == ':') { return false; }
  12297. // Find the colon separator
  12298. auto colon_pos = line.find(':');
  12299. if (colon_pos == std::string::npos) {
  12300. // Line with no colon is treated as field name with empty value
  12301. return false;
  12302. }
  12303. std::string field = line.substr(0, colon_pos);
  12304. std::string value;
  12305. // Value starts after colon, skip optional single space
  12306. if (colon_pos + 1 < line.size()) {
  12307. size_t value_start = colon_pos + 1;
  12308. if (line[value_start] == ' ') { value_start++; }
  12309. value = line.substr(value_start);
  12310. // Remove trailing \r if present
  12311. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12312. }
  12313. // Handle known fields
  12314. if (field == "event") {
  12315. msg.event = value;
  12316. } else if (field == "data") {
  12317. // Multiple data lines are concatenated with newlines
  12318. if (!msg.data.empty()) { msg.data += "\n"; }
  12319. msg.data += value;
  12320. } else if (field == "id") {
  12321. // Empty id is valid (clears the last event ID)
  12322. msg.id = value;
  12323. } else if (field == "retry") {
  12324. // Parse retry interval in milliseconds
  12325. {
  12326. int v = 0;
  12327. auto res =
  12328. detail::from_chars(value.data(), value.data() + value.size(), v);
  12329. if (res.ec == std::errc{}) { retry_ms = v; }
  12330. }
  12331. }
  12332. // Unknown fields are ignored per SSE spec
  12333. return false;
  12334. }
  12335. };
  12336. // Test: Single-line data
  12337. TEST_F(SSEParsingTest, SingleLineData) {
  12338. sse::SSEMessage msg;
  12339. int retry_ms = 3000;
  12340. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12341. EXPECT_EQ(msg.data, "hello");
  12342. EXPECT_EQ(msg.event, "message");
  12343. // Blank line ends event
  12344. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12345. }
  12346. // Test: Multi-line data
  12347. TEST_F(SSEParsingTest, MultiLineData) {
  12348. sse::SSEMessage msg;
  12349. int retry_ms = 3000;
  12350. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12351. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12352. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12353. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12354. }
  12355. // Test: Custom event types
  12356. TEST_F(SSEParsingTest, CustomEventType) {
  12357. sse::SSEMessage msg;
  12358. int retry_ms = 3000;
  12359. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12360. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12361. EXPECT_EQ(msg.event, "update");
  12362. EXPECT_EQ(msg.data, "payload");
  12363. }
  12364. // Test: Event ID handling
  12365. TEST_F(SSEParsingTest, EventIdHandling) {
  12366. sse::SSEMessage msg;
  12367. int retry_ms = 3000;
  12368. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12369. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12370. EXPECT_EQ(msg.id, "12345");
  12371. }
  12372. // Test: Empty event ID (clears last event ID)
  12373. TEST_F(SSEParsingTest, EmptyEventId) {
  12374. sse::SSEMessage msg;
  12375. msg.id = "previous";
  12376. int retry_ms = 3000;
  12377. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12378. EXPECT_EQ(msg.id, "");
  12379. }
  12380. // Test: Retry field parsing
  12381. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12382. sse::SSEMessage msg;
  12383. int retry_ms = 3000;
  12384. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12385. EXPECT_EQ(retry_ms, 5000);
  12386. }
  12387. // Test: Invalid retry value
  12388. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12389. sse::SSEMessage msg;
  12390. int retry_ms = 3000;
  12391. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12392. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12393. }
  12394. // Test: Comments (lines starting with :)
  12395. TEST_F(SSEParsingTest, CommentsIgnored) {
  12396. sse::SSEMessage msg;
  12397. int retry_ms = 3000;
  12398. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12399. EXPECT_EQ(msg.data, "");
  12400. EXPECT_EQ(msg.event, "message");
  12401. }
  12402. // Test: Colon in value
  12403. TEST_F(SSEParsingTest, ColonInValue) {
  12404. sse::SSEMessage msg;
  12405. int retry_ms = 3000;
  12406. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12407. EXPECT_EQ(msg.data, "hello:world:test");
  12408. }
  12409. // Test: Line with no colon (field name only)
  12410. TEST_F(SSEParsingTest, FieldNameOnly) {
  12411. sse::SSEMessage msg;
  12412. int retry_ms = 3000;
  12413. // According to SSE spec, this is treated as field name with empty value
  12414. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12415. // Since we don't recognize "data" without colon, data should be empty
  12416. EXPECT_EQ(msg.data, "");
  12417. }
  12418. // Test: Trailing \r handling
  12419. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12420. sse::SSEMessage msg;
  12421. int retry_ms = 3000;
  12422. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12423. EXPECT_EQ(msg.data, "hello");
  12424. }
  12425. // Test: Unknown fields ignored
  12426. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12427. sse::SSEMessage msg;
  12428. int retry_ms = 3000;
  12429. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12430. EXPECT_EQ(msg.data, "");
  12431. EXPECT_EQ(msg.event, "message");
  12432. }
  12433. // Test: Space after colon is optional
  12434. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12435. sse::SSEMessage msg1, msg2;
  12436. int retry_ms = 3000;
  12437. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12438. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12439. EXPECT_EQ(msg1.data, "hello");
  12440. EXPECT_EQ(msg2.data, "hello");
  12441. }
  12442. // Test: SSEMessage clear
  12443. TEST_F(SSEParsingTest, MessageClear) {
  12444. sse::SSEMessage msg;
  12445. msg.event = "custom";
  12446. msg.data = "some data";
  12447. msg.id = "123";
  12448. msg.clear();
  12449. EXPECT_EQ(msg.event, "message");
  12450. EXPECT_EQ(msg.data, "");
  12451. EXPECT_EQ(msg.id, "");
  12452. }
  12453. // Test: Complete event parsing
  12454. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12455. sse::SSEMessage msg;
  12456. int retry_ms = 3000;
  12457. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12458. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12459. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12460. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12461. // Blank line ends event
  12462. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12463. EXPECT_EQ(msg.event, "notification");
  12464. EXPECT_EQ(msg.id, "evt-42");
  12465. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12466. EXPECT_EQ(retry_ms, 1000);
  12467. }
  12468. //==============================================================================
  12469. // Integration Tests with Server
  12470. //==============================================================================
  12471. class SSEIntegrationTest : public ::testing::Test {
  12472. protected:
  12473. void SetUp() override {
  12474. stop_server_.store(false);
  12475. events_.clear();
  12476. server_ = httplib::detail::make_unique<Server>();
  12477. setup_server();
  12478. start_server();
  12479. }
  12480. void TearDown() override {
  12481. stop_server_.store(true);
  12482. event_cv_.notify_all();
  12483. server_->stop();
  12484. if (server_thread_.joinable()) { server_thread_.join(); }
  12485. }
  12486. void setup_server() {
  12487. // Simple SSE endpoint
  12488. server_->Get("/events", [this](const Request &req, Response &res) {
  12489. auto last_id = req.get_header_value("Last-Event-ID");
  12490. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12491. res.set_chunked_content_provider(
  12492. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12493. std::unique_lock<std::mutex> lock(event_mutex_);
  12494. if (event_cv_.wait_for(
  12495. lock, std::chrono::milliseconds(200), [this] {
  12496. return !events_.empty() || stop_server_.load();
  12497. })) {
  12498. if (stop_server_.load()) { return false; }
  12499. if (!events_.empty()) {
  12500. std::string event = events_.front();
  12501. events_.erase(events_.begin());
  12502. sink.write(event.data(), event.size());
  12503. return true;
  12504. }
  12505. }
  12506. return !stop_server_.load();
  12507. });
  12508. });
  12509. // Endpoint that returns error
  12510. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12511. res.status = 500;
  12512. res.set_content("Internal Server Error", "text/plain");
  12513. });
  12514. // Endpoint for custom event types
  12515. server_->Get("/custom-events", [](const Request &, Response &res) {
  12516. res.set_chunked_content_provider(
  12517. "text/event-stream", [](size_t offset, DataSink &sink) {
  12518. if (offset == 0) {
  12519. std::string event = "event: update\ndata: updated\n\n"
  12520. "event: delete\ndata: deleted\n\n";
  12521. sink.write(event.data(), event.size());
  12522. }
  12523. return false; // End stream after sending
  12524. });
  12525. });
  12526. }
  12527. void start_server() {
  12528. port_ = server_->bind_to_any_port(HOST);
  12529. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12530. // Wait for server to start
  12531. while (!server_->is_running()) {
  12532. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12533. }
  12534. }
  12535. int get_port() const { return port_; }
  12536. void send_event(const std::string &event) {
  12537. std::lock_guard<std::mutex> lock(event_mutex_);
  12538. events_.push_back(event);
  12539. event_cv_.notify_all();
  12540. }
  12541. std::unique_ptr<Server> server_;
  12542. std::thread server_thread_;
  12543. std::mutex event_mutex_;
  12544. std::condition_variable event_cv_;
  12545. std::vector<std::string> events_;
  12546. std::atomic<bool> stop_server_{false};
  12547. std::string last_received_event_id_;
  12548. int port_ = 0;
  12549. };
  12550. // Test: Successful connection and on_open callback
  12551. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12552. // Add a simple endpoint that sends one event and closes
  12553. server_->Get("/simple-event", [](const Request &, Response &res) {
  12554. res.set_chunked_content_provider(
  12555. "text/event-stream", [](size_t offset, DataSink &sink) {
  12556. if (offset == 0) {
  12557. std::string event = "data: hello\n\n";
  12558. sink.write(event.data(), event.size());
  12559. }
  12560. return false; // Close stream after sending
  12561. });
  12562. });
  12563. Client client("localhost", get_port());
  12564. sse::SSEClient sse(client, "/simple-event");
  12565. std::atomic<bool> open_called{false};
  12566. std::atomic<bool> message_received{false};
  12567. sse.on_open([&open_called]() { open_called.store(true); });
  12568. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12569. if (msg.data == "hello") { message_received.store(true); }
  12570. });
  12571. sse.set_reconnect_interval(100);
  12572. sse.set_max_reconnect_attempts(1);
  12573. // Start async
  12574. sse.start_async();
  12575. // Wait for message to be processed
  12576. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12577. sse.stop();
  12578. EXPECT_TRUE(open_called.load());
  12579. EXPECT_TRUE(message_received.load());
  12580. }
  12581. // Test: on_message callback
  12582. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12583. // Endpoint that sends multiple events then closes
  12584. server_->Get("/multi-event", [](const Request &, Response &res) {
  12585. res.set_chunked_content_provider(
  12586. "text/event-stream", [](size_t offset, DataSink &sink) {
  12587. if (offset == 0) {
  12588. std::string events = "data: message1\n\ndata: message2\n\n";
  12589. sink.write(events.data(), events.size());
  12590. }
  12591. return false;
  12592. });
  12593. });
  12594. Client client("localhost", get_port());
  12595. sse::SSEClient sse(client, "/multi-event");
  12596. std::vector<std::string> received_messages;
  12597. std::mutex messages_mutex;
  12598. sse.on_message([&](const sse::SSEMessage &msg) {
  12599. std::lock_guard<std::mutex> lock(messages_mutex);
  12600. received_messages.push_back(msg.data);
  12601. });
  12602. sse.set_reconnect_interval(100);
  12603. sse.set_max_reconnect_attempts(1);
  12604. sse.start_async();
  12605. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12606. sse.stop();
  12607. std::lock_guard<std::mutex> lock(messages_mutex);
  12608. EXPECT_GE(received_messages.size(), 2u);
  12609. if (received_messages.size() >= 2) {
  12610. EXPECT_EQ(received_messages[0], "message1");
  12611. EXPECT_EQ(received_messages[1], "message2");
  12612. }
  12613. }
  12614. // Test: on_event for specific types
  12615. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  12616. Client client("localhost", get_port());
  12617. sse::SSEClient sse(client, "/custom-events");
  12618. std::atomic<bool> update_received{false};
  12619. std::atomic<bool> delete_received{false};
  12620. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  12621. if (msg.data == "updated") { update_received.store(true); }
  12622. });
  12623. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  12624. if (msg.data == "deleted") { delete_received.store(true); }
  12625. });
  12626. sse.set_max_reconnect_attempts(1);
  12627. sse.start_async();
  12628. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  12629. sse.stop();
  12630. EXPECT_TRUE(update_received.load());
  12631. EXPECT_TRUE(delete_received.load());
  12632. }
  12633. // Test: on_error callback on connection failure
  12634. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  12635. // Connect to a non-existent port
  12636. Client client("localhost", 59999);
  12637. sse::SSEClient sse(client, "/events");
  12638. std::atomic<bool> error_called{false};
  12639. Error received_error = Error::Success;
  12640. sse.on_error([&](Error err) {
  12641. error_called.store(true);
  12642. received_error = err;
  12643. });
  12644. sse.set_reconnect_interval(50);
  12645. sse.set_max_reconnect_attempts(1);
  12646. sse.start_async();
  12647. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12648. sse.stop();
  12649. EXPECT_TRUE(error_called.load());
  12650. EXPECT_NE(received_error, Error::Success);
  12651. }
  12652. // Test: Last-Event-ID header sent on reconnect
  12653. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  12654. // Endpoint that sends event with ID
  12655. server_->Get("/event-with-id", [](const Request &, Response &res) {
  12656. res.set_chunked_content_provider(
  12657. "text/event-stream", [](size_t offset, DataSink &sink) {
  12658. if (offset == 0) {
  12659. std::string event = "id: evt-123\ndata: test\n\n";
  12660. sink.write(event.data(), event.size());
  12661. }
  12662. return false;
  12663. });
  12664. });
  12665. Client client("localhost", get_port());
  12666. sse::SSEClient sse(client, "/event-with-id");
  12667. std::atomic<bool> id_received{false};
  12668. sse.on_message([&](const sse::SSEMessage &msg) {
  12669. if (!msg.id.empty()) { id_received.store(true); }
  12670. });
  12671. sse.set_reconnect_interval(100);
  12672. sse.set_max_reconnect_attempts(1);
  12673. sse.start_async();
  12674. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12675. sse.stop();
  12676. EXPECT_TRUE(id_received.load());
  12677. EXPECT_EQ(sse.last_event_id(), "evt-123");
  12678. }
  12679. // Test: Manual stop
  12680. TEST_F(SSEIntegrationTest, ManualStop) {
  12681. // Endpoint that sends one event and stays open briefly
  12682. std::atomic<bool> handler_running{true};
  12683. server_->Get("/stay-open", [&handler_running](const Request &,
  12684. Response &res) {
  12685. res.set_chunked_content_provider(
  12686. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  12687. if (offset == 0) {
  12688. std::string event = "data: connected\n\n";
  12689. sink.write(event.data(), event.size());
  12690. }
  12691. // Keep connection open while handler_running is true
  12692. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12693. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12694. }
  12695. return false;
  12696. });
  12697. });
  12698. Client client("localhost", get_port());
  12699. sse::SSEClient sse(client, "/stay-open");
  12700. std::atomic<bool> connected{false};
  12701. sse.on_open([&connected]() { connected.store(true); });
  12702. sse.set_reconnect_interval(100);
  12703. sse.set_max_reconnect_attempts(1);
  12704. sse.start_async();
  12705. // Wait for connection to establish
  12706. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12707. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12708. }
  12709. EXPECT_TRUE(connected.load());
  12710. EXPECT_TRUE(sse.is_connected());
  12711. // Signal handler to stop
  12712. handler_running.store(false);
  12713. // Stop SSE client
  12714. sse.stop();
  12715. EXPECT_FALSE(sse.is_connected());
  12716. }
  12717. // Test: SSEClient with custom headers
  12718. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12719. // Setup a server endpoint that checks for custom header
  12720. std::atomic<bool> header_received{false};
  12721. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12722. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12723. header_received.store(true);
  12724. }
  12725. res.set_chunked_content_provider("text/event-stream",
  12726. [](size_t, DataSink &) { return false; });
  12727. });
  12728. Client client("localhost", get_port());
  12729. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12730. sse::SSEClient sse(client, "/header-check", headers);
  12731. sse.set_max_reconnect_attempts(1);
  12732. sse.start_async();
  12733. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12734. sse.stop();
  12735. EXPECT_TRUE(header_received.load());
  12736. }
  12737. // Test: Reconnect interval configuration
  12738. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12739. Client client("localhost", get_port());
  12740. sse::SSEClient sse(client, "/events");
  12741. auto &result = sse.set_reconnect_interval(500);
  12742. // Builder pattern should return reference to self
  12743. EXPECT_EQ(&result, &sse);
  12744. }
  12745. // Test: Max reconnect attempts
  12746. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12747. // Connect to non-existent port to force reconnects
  12748. Client client("localhost", 59998);
  12749. sse::SSEClient sse(client, "/events");
  12750. std::atomic<int> error_count{0};
  12751. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12752. sse.set_reconnect_interval(50);
  12753. sse.set_max_reconnect_attempts(2);
  12754. auto start = std::chrono::steady_clock::now();
  12755. sse.start(); // Blocking call
  12756. auto end = std::chrono::steady_clock::now();
  12757. // Should have stopped after 2 failed attempts
  12758. EXPECT_GE(error_count.load(), 2);
  12759. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12760. auto duration =
  12761. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12762. #ifdef _WIN32
  12763. // Windows is much slower for socket connection failures
  12764. EXPECT_LT(duration.count(), 7000);
  12765. #else
  12766. EXPECT_LT(duration.count(), 1000);
  12767. #endif
  12768. }
  12769. // Test: Multi-line data in integration
  12770. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  12771. // Endpoint with multi-line data
  12772. server_->Get("/multiline-data", [](const Request &, Response &res) {
  12773. res.set_chunked_content_provider(
  12774. "text/event-stream", [](size_t offset, DataSink &sink) {
  12775. if (offset == 0) {
  12776. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  12777. sink.write(event.data(), event.size());
  12778. }
  12779. return false;
  12780. });
  12781. });
  12782. Client client("localhost", get_port());
  12783. sse::SSEClient sse(client, "/multiline-data");
  12784. std::string received_data;
  12785. std::mutex data_mutex;
  12786. sse.on_message([&](const sse::SSEMessage &msg) {
  12787. std::lock_guard<std::mutex> lock(data_mutex);
  12788. received_data = msg.data;
  12789. });
  12790. sse.set_reconnect_interval(100);
  12791. sse.set_max_reconnect_attempts(1);
  12792. sse.start_async();
  12793. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12794. sse.stop();
  12795. std::lock_guard<std::mutex> lock(data_mutex);
  12796. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12797. }
  12798. // Test: Auto-reconnect after server disconnection
  12799. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12800. std::atomic<int> connection_count{0};
  12801. std::atomic<int> message_count{0};
  12802. // Endpoint that sends one event and closes, forcing reconnect
  12803. server_->Get("/reconnect-test",
  12804. [&connection_count](const Request &, Response &res) {
  12805. connection_count.fetch_add(1);
  12806. res.set_chunked_content_provider(
  12807. "text/event-stream", [](size_t offset, DataSink &sink) {
  12808. if (offset == 0) {
  12809. std::string event = "data: hello\n\n";
  12810. sink.write(event.data(), event.size());
  12811. }
  12812. return false; // Close connection after sending
  12813. });
  12814. });
  12815. Client client("localhost", get_port());
  12816. sse::SSEClient sse(client, "/reconnect-test");
  12817. sse.on_message([&message_count](const sse::SSEMessage &) {
  12818. message_count.fetch_add(1);
  12819. });
  12820. sse.set_reconnect_interval(100);
  12821. sse.set_max_reconnect_attempts(3);
  12822. sse.start_async();
  12823. // Wait long enough for multiple reconnects
  12824. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12825. sse.stop();
  12826. // Should have connected multiple times (initial + reconnects)
  12827. EXPECT_GE(connection_count.load(), 2);
  12828. // Should have received messages from multiple connections
  12829. EXPECT_GE(message_count.load(), 2);
  12830. }
  12831. // Test: Last-Event-ID sent on reconnect
  12832. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12833. std::atomic<int> connection_count{0};
  12834. std::vector<std::string> received_last_event_ids;
  12835. std::mutex id_mutex;
  12836. // Endpoint that checks Last-Event-ID header and sends event with ID
  12837. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12838. int conn = connection_count.fetch_add(1);
  12839. // Capture the Last-Event-ID header from each connection
  12840. {
  12841. std::lock_guard<std::mutex> lock(id_mutex);
  12842. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12843. }
  12844. res.set_chunked_content_provider(
  12845. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12846. if (offset == 0) {
  12847. std::string event =
  12848. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12849. sink.write(event.data(), event.size());
  12850. }
  12851. return false;
  12852. });
  12853. });
  12854. Client client("localhost", get_port());
  12855. sse::SSEClient sse(client, "/reconnect-with-id");
  12856. sse.set_reconnect_interval(100);
  12857. sse.set_max_reconnect_attempts(3);
  12858. sse.start_async();
  12859. // Wait for at least 2 connections
  12860. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12861. sse.stop();
  12862. // Verify behavior
  12863. std::lock_guard<std::mutex> lock(id_mutex);
  12864. EXPECT_GE(received_last_event_ids.size(), 2u);
  12865. // First connection should have no Last-Event-ID
  12866. if (!received_last_event_ids.empty()) {
  12867. EXPECT_EQ(received_last_event_ids[0], "");
  12868. }
  12869. // Second connection should have Last-Event-ID from first connection
  12870. if (received_last_event_ids.size() >= 2) {
  12871. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12872. }
  12873. }
  12874. TEST(Issue2318Test, EmptyHostString) {
  12875. {
  12876. httplib::Client cli_empty("", PORT);
  12877. auto res = cli_empty.Get("/");
  12878. ASSERT_FALSE(res);
  12879. EXPECT_EQ(httplib::Error::Connection, res.error());
  12880. }
  12881. {
  12882. httplib::Client cli(" ", PORT);
  12883. auto res = cli.Get("/");
  12884. ASSERT_FALSE(res);
  12885. EXPECT_EQ(httplib::Error::Connection, res.error());
  12886. }
  12887. }
  12888. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12889. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  12890. Server svr;
  12891. // Set a small payload limit (1KB)
  12892. svr.set_payload_max_length(1024);
  12893. svr.Post("/test", [&](const Request &req, Response &res) {
  12894. res.set_content("Body size: " + std::to_string(req.body.size()),
  12895. "text/plain");
  12896. });
  12897. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12898. auto se = detail::scope_exit([&] {
  12899. svr.stop();
  12900. listen_thread.join();
  12901. });
  12902. svr.wait_until_ready();
  12903. // Create data that compresses well but exceeds limit when decompressed
  12904. // 8KB of repeated null bytes compresses to a very small size
  12905. std::string original_data(8 * 1024, '\0');
  12906. // Compress the data using gzip
  12907. std::string compressed_data;
  12908. detail::gzip_compressor compressor;
  12909. compressor.compress(original_data.data(), original_data.size(), true,
  12910. [&](const char *data, size_t size) {
  12911. compressed_data.append(data, size);
  12912. return true;
  12913. });
  12914. // Verify compression worked (compressed should be much smaller)
  12915. ASSERT_LT(compressed_data.size(), original_data.size());
  12916. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  12917. // Send compressed data with Content-Encoding: gzip
  12918. Client cli(HOST, PORT);
  12919. Headers headers = {{"Content-Encoding", "gzip"}};
  12920. auto res =
  12921. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  12922. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  12923. ASSERT_TRUE(res);
  12924. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12925. }
  12926. #endif
  12927. // ============================================================================
  12928. // OpenSSL-Specific Tests
  12929. // ============================================================================
  12930. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12931. X509 *readCertificate(const std::string &strFileName) {
  12932. std::ifstream inStream(strFileName);
  12933. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  12934. std::istreambuf_iterator<char>());
  12935. if (strCertPEM.empty()) return (nullptr);
  12936. BIO *pbCert = BIO_new(BIO_s_mem());
  12937. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  12938. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  12939. BIO_free(pbCert);
  12940. return (pCert);
  12941. }
  12942. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  12943. std::ifstream inStream(strFileName);
  12944. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  12945. std::istreambuf_iterator<char>());
  12946. if (strPrivateKeyPEM.empty()) return (nullptr);
  12947. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  12948. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  12949. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  12950. BIO_free(pbPrivKey);
  12951. return (pPrivateKey);
  12952. }
  12953. TEST(BindServerTest, UpdateCerts) {
  12954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12955. int port = svr.bind_to_any_port("0.0.0.0");
  12956. ASSERT_TRUE(svr.is_valid());
  12957. ASSERT_TRUE(port > 0);
  12958. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12959. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12960. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12961. ASSERT_TRUE(cert != nullptr);
  12962. ASSERT_TRUE(ca_cert != nullptr);
  12963. ASSERT_TRUE(key != nullptr);
  12964. X509_STORE *cert_store = X509_STORE_new();
  12965. X509_STORE_add_cert(cert_store, ca_cert);
  12966. // svr.update_certs(cert, key, cert_store); // deprecated
  12967. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12968. CLIENT_CA_CERT_FILE);
  12969. ASSERT_TRUE(svr.is_valid());
  12970. svr.stop();
  12971. X509_STORE_free(cert_store);
  12972. X509_free(cert);
  12973. X509_free(ca_cert);
  12974. EVP_PKEY_free(key);
  12975. }
  12976. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  12977. // client CA list correctly for TLS handshake
  12978. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  12979. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12980. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12981. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12982. ASSERT_TRUE(cert != nullptr);
  12983. ASSERT_TRUE(ca_cert != nullptr);
  12984. ASSERT_TRUE(key != nullptr);
  12985. X509_STORE *cert_store = X509_STORE_new();
  12986. X509_STORE_add_cert(cert_store, ca_cert);
  12987. // Use X509-based constructor (deprecated but should still work correctly)
  12988. #pragma GCC diagnostic push
  12989. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  12990. SSLServer svr(cert, key, cert_store);
  12991. #pragma GCC diagnostic pop
  12992. ASSERT_TRUE(svr.is_valid());
  12993. // Verify that client CA list is set in SSL_CTX
  12994. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12995. ASSERT_TRUE(ssl_ctx != nullptr);
  12996. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12997. ASSERT_TRUE(ca_list != nullptr);
  12998. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12999. X509_free(cert);
  13000. X509_free(ca_cert);
  13001. EVP_PKEY_free(key);
  13002. }
  13003. // Test that update_certs() updates client CA list correctly
  13004. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13005. // Start with file-based constructor
  13006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13007. ASSERT_TRUE(svr.is_valid());
  13008. // Initially no client CA list should be set
  13009. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13010. ASSERT_TRUE(ssl_ctx != nullptr);
  13011. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13012. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13013. EXPECT_EQ(0, count_before);
  13014. // Now update with client CA (PEM string)
  13015. std::string cert_pem, key_pem, ca_pem;
  13016. read_file(SERVER_CERT_FILE, cert_pem);
  13017. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13018. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13019. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13020. ASSERT_TRUE(svr.is_valid());
  13021. // Now client CA list should be set
  13022. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13023. ASSERT_TRUE(ca_list_after != nullptr);
  13024. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13025. }
  13026. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13027. // Test that the file-path SSLServer constructor properly sets the client CA
  13028. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13029. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13030. ASSERT_TRUE(svr.is_valid());
  13031. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13032. ASSERT_TRUE(ssl_ctx != nullptr);
  13033. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13034. ASSERT_TRUE(ca_list != nullptr);
  13035. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13036. }
  13037. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13038. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13039. // prepare large data
  13040. std::random_device seed_gen;
  13041. std::mt19937 random(seed_gen());
  13042. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13043. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13044. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13045. // server
  13046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13047. ASSERT_TRUE(svr.is_valid());
  13048. svr.Post("/binary", [&](const Request &req, Response &res) {
  13049. EXPECT_EQ(large_size_byte, req.body.size());
  13050. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13051. res.set_content(req.body, "application/octet-stream");
  13052. });
  13053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13054. auto se = detail::scope_exit([&] {
  13055. svr.stop();
  13056. listen_thread.join();
  13057. ASSERT_FALSE(svr.is_running());
  13058. });
  13059. svr.wait_until_ready();
  13060. // client POST
  13061. SSLClient cli("localhost", PORT);
  13062. cli.enable_server_certificate_verification(false);
  13063. cli.set_read_timeout(std::chrono::seconds(100));
  13064. cli.set_write_timeout(std::chrono::seconds(100));
  13065. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13066. large_size_byte, "application/octet-stream");
  13067. // compare
  13068. EXPECT_EQ(StatusCode::OK_200, res->status);
  13069. EXPECT_EQ(large_size_byte, res->body.size());
  13070. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13071. }
  13072. #endif
  13073. // ============================================================================
  13074. // MbedTLS-Specific Tests
  13075. // ============================================================================
  13076. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13077. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13078. using namespace httplib::tls;
  13079. // Track if callback was invoked
  13080. bool callback_invoked = false;
  13081. // The callback receives void* ctx which is actually MbedTlsContext*
  13082. // We can access the mbedtls_ssl_config via the context
  13083. auto setup_callback = [&callback_invoked](void *ctx) {
  13084. callback_invoked = true;
  13085. // Cast to MbedTlsContext* to access the ssl config
  13086. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13087. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13088. // Use static variables to hold certificate data (simplified for test)
  13089. static mbedtls_x509_crt own_cert;
  13090. static mbedtls_pk_context own_key;
  13091. static mbedtls_x509_crt ca_chain;
  13092. static bool initialized = false;
  13093. if (!initialized) {
  13094. mbedtls_x509_crt_init(&own_cert);
  13095. mbedtls_pk_init(&own_key);
  13096. mbedtls_x509_crt_init(&ca_chain);
  13097. // Load server certificate
  13098. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13099. return false;
  13100. }
  13101. // Load server private key
  13102. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13103. #if MBEDTLS_VERSION_MAJOR >= 3
  13104. ,
  13105. mbedtls_ctr_drbg_random, nullptr
  13106. #endif
  13107. ) != 0) {
  13108. return false;
  13109. }
  13110. // Load CA chain for client verification
  13111. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13112. return false;
  13113. }
  13114. initialized = true;
  13115. }
  13116. // Configure the SSL config
  13117. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13118. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13119. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13120. // Set minimum TLS version using mbedTLS native API
  13121. #if MBEDTLS_VERSION_MAJOR >= 3
  13122. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13123. #else
  13124. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13125. MBEDTLS_SSL_MINOR_VERSION_3);
  13126. #endif
  13127. return true;
  13128. };
  13129. SSLServer svr(setup_callback);
  13130. ASSERT_TRUE(svr.is_valid());
  13131. ASSERT_TRUE(callback_invoked);
  13132. svr.Get("/test", [&](const Request &req, Response &res) {
  13133. res.set_content("test", "text/plain");
  13134. auto cert = req.peer_cert();
  13135. ASSERT_TRUE(static_cast<bool>(cert));
  13136. auto common_name = cert.subject_cn();
  13137. EXPECT_EQ("Common Name", common_name);
  13138. });
  13139. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13140. auto se = detail::scope_exit([&] {
  13141. svr.stop();
  13142. t.join();
  13143. ASSERT_FALSE(svr.is_running());
  13144. });
  13145. svr.wait_until_ready();
  13146. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13147. cli.enable_server_certificate_verification(false);
  13148. cli.set_connection_timeout(30);
  13149. auto res = cli.Get("/test");
  13150. ASSERT_TRUE(res);
  13151. ASSERT_EQ(StatusCode::OK_200, res->status);
  13152. }
  13153. #endif
  13154. // WebSocket Tests
  13155. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13156. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13157. // defining the meaning of these bits has been negotiated.
  13158. auto make_frame = [](uint8_t first_byte) {
  13159. std::string frame;
  13160. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13161. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13162. frame += "Hello";
  13163. return frame;
  13164. };
  13165. // RSV1 set (0x40)
  13166. {
  13167. detail::BufferStream strm;
  13168. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13169. ws::Opcode opcode;
  13170. std::string payload;
  13171. bool fin;
  13172. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13173. false, 1024));
  13174. }
  13175. // RSV2 set (0x20)
  13176. {
  13177. detail::BufferStream strm;
  13178. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13179. ws::Opcode opcode;
  13180. std::string payload;
  13181. bool fin;
  13182. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13183. false, 1024));
  13184. }
  13185. // RSV3 set (0x10)
  13186. {
  13187. detail::BufferStream strm;
  13188. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13189. ws::Opcode opcode;
  13190. std::string payload;
  13191. bool fin;
  13192. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13193. false, 1024));
  13194. }
  13195. // No RSV bits set - should succeed
  13196. {
  13197. detail::BufferStream strm;
  13198. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13199. ws::Opcode opcode;
  13200. std::string payload;
  13201. bool fin;
  13202. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13203. false, 1024));
  13204. EXPECT_EQ(ws::Opcode::Text, opcode);
  13205. EXPECT_EQ("Hello", payload);
  13206. EXPECT_TRUE(fin);
  13207. }
  13208. }
  13209. TEST(WebSocketTest, ControlFrameValidation) {
  13210. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13211. // payload length <= 125.
  13212. // Ping with FIN=0 - must be rejected
  13213. {
  13214. detail::BufferStream strm;
  13215. std::string frame;
  13216. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13217. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13218. strm.write(frame.data(), frame.size());
  13219. ws::Opcode opcode;
  13220. std::string payload;
  13221. bool fin;
  13222. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13223. false, 1024));
  13224. }
  13225. // Close with FIN=0 - must be rejected
  13226. {
  13227. detail::BufferStream strm;
  13228. std::string frame;
  13229. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13230. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13231. strm.write(frame.data(), frame.size());
  13232. ws::Opcode opcode;
  13233. std::string payload;
  13234. bool fin;
  13235. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13236. false, 1024));
  13237. }
  13238. // Ping with payload_len=126 (extended length) - must be rejected
  13239. {
  13240. detail::BufferStream strm;
  13241. std::string frame;
  13242. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13243. frame += static_cast<char>(126); // payload_len=126 (>125)
  13244. frame += static_cast<char>(0x00); // extended length high byte
  13245. frame += static_cast<char>(126); // extended length low byte
  13246. frame += std::string(126, 'x');
  13247. strm.write(frame.data(), frame.size());
  13248. ws::Opcode opcode;
  13249. std::string payload;
  13250. bool fin;
  13251. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13252. false, 1024));
  13253. }
  13254. // Ping with FIN=1 and payload_len=125 - should succeed
  13255. {
  13256. detail::BufferStream strm;
  13257. std::string frame;
  13258. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13259. frame += static_cast<char>(125); // payload_len=125
  13260. frame += std::string(125, 'x');
  13261. strm.write(frame.data(), frame.size());
  13262. ws::Opcode opcode;
  13263. std::string payload;
  13264. bool fin;
  13265. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13266. false, 1024));
  13267. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13268. EXPECT_EQ(125u, payload.size());
  13269. EXPECT_TRUE(fin);
  13270. }
  13271. }
  13272. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13273. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13274. // length MUST be 0.
  13275. // MSB set - must be rejected
  13276. {
  13277. detail::BufferStream strm;
  13278. std::string frame;
  13279. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13280. frame += static_cast<char>(127); // 64-bit extended length
  13281. frame += static_cast<char>(0x80); // MSB set (invalid)
  13282. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13283. strm.write(frame.data(), frame.size());
  13284. ws::Opcode opcode;
  13285. std::string payload;
  13286. bool fin;
  13287. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13288. false, 1024));
  13289. }
  13290. // MSB clear - should pass length parsing (will be rejected by max_len,
  13291. // but that's a different check; use a small length to verify)
  13292. {
  13293. detail::BufferStream strm;
  13294. std::string frame;
  13295. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13296. frame += static_cast<char>(127); // 64-bit extended length
  13297. frame += std::string(7, '\0'); // high bytes = 0
  13298. frame += static_cast<char>(0x03); // length = 3
  13299. frame += "abc";
  13300. strm.write(frame.data(), frame.size());
  13301. ws::Opcode opcode;
  13302. std::string payload;
  13303. bool fin;
  13304. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13305. false, 1024));
  13306. EXPECT_EQ(ws::Opcode::Text, opcode);
  13307. EXPECT_EQ("abc", payload);
  13308. }
  13309. }
  13310. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13311. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13312. // Valid UTF-8
  13313. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13314. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13315. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13316. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13317. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13318. // Invalid UTF-8
  13319. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13320. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13321. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13322. EXPECT_FALSE(
  13323. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13324. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13325. }
  13326. TEST(WebSocketTest, ConnectAndDisconnect) {
  13327. Server svr;
  13328. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13329. std::string msg;
  13330. while (ws.read(msg)) {}
  13331. });
  13332. auto port = svr.bind_to_any_port(HOST);
  13333. std::thread t([&]() { svr.listen_after_bind(); });
  13334. svr.wait_until_ready();
  13335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13336. ASSERT_TRUE(client.connect());
  13337. EXPECT_TRUE(client.is_open());
  13338. client.close();
  13339. EXPECT_FALSE(client.is_open());
  13340. svr.stop();
  13341. t.join();
  13342. }
  13343. TEST(WebSocketTest, ValidURL) {
  13344. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13345. EXPECT_TRUE(ws1.is_valid());
  13346. ws::WebSocketClient ws2("ws://example.com/path");
  13347. EXPECT_TRUE(ws2.is_valid());
  13348. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13349. EXPECT_TRUE(ws3.is_valid());
  13350. #ifdef CPPHTTPLIB_SSL_ENABLED
  13351. ws::WebSocketClient wss1("wss://example.com/path");
  13352. EXPECT_TRUE(wss1.is_valid());
  13353. ws::WebSocketClient wss2("wss://example.com:443/path");
  13354. EXPECT_TRUE(wss2.is_valid());
  13355. #endif
  13356. }
  13357. TEST(WebSocketTest, InvalidURL) {
  13358. // No scheme
  13359. ws::WebSocketClient ws1("localhost:8080/path");
  13360. EXPECT_FALSE(ws1.is_valid());
  13361. // No path
  13362. ws::WebSocketClient ws2("ws://localhost:8080");
  13363. EXPECT_FALSE(ws2.is_valid());
  13364. // Empty string
  13365. ws::WebSocketClient ws3("");
  13366. EXPECT_FALSE(ws3.is_valid());
  13367. // Missing host
  13368. ws::WebSocketClient ws4("ws://:8080/path");
  13369. EXPECT_FALSE(ws4.is_valid());
  13370. }
  13371. TEST(WebSocketTest, UnsupportedScheme) {
  13372. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13373. ws::WebSocketClient ws1("http://localhost:8080/path");
  13374. EXPECT_FALSE(ws1.is_valid());
  13375. ws::WebSocketClient ws2("https://localhost:8080/path");
  13376. EXPECT_FALSE(ws2.is_valid());
  13377. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13378. EXPECT_FALSE(ws3.is_valid());
  13379. #else
  13380. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13381. std::invalid_argument);
  13382. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13383. std::invalid_argument);
  13384. #endif
  13385. }
  13386. TEST(WebSocketTest, ConnectWhenInvalid) {
  13387. ws::WebSocketClient ws("not a valid url");
  13388. EXPECT_FALSE(ws.is_valid());
  13389. EXPECT_FALSE(ws.connect());
  13390. }
  13391. TEST(WebSocketTest, DefaultPort) {
  13392. ws::WebSocketClient ws1("ws://example.com/path");
  13393. EXPECT_TRUE(ws1.is_valid());
  13394. // ws:// defaults to port 80 (verified by successful parse)
  13395. #ifdef CPPHTTPLIB_SSL_ENABLED
  13396. ws::WebSocketClient ws2("wss://example.com/path");
  13397. EXPECT_TRUE(ws2.is_valid());
  13398. // wss:// defaults to port 443 (verified by successful parse)
  13399. #endif
  13400. }
  13401. TEST(WebSocketTest, IPv6LiteralAddress) {
  13402. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13403. EXPECT_TRUE(ws1.is_valid());
  13404. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13405. EXPECT_TRUE(ws2.is_valid());
  13406. }
  13407. TEST(WebSocketTest, ComplexPath) {
  13408. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13409. EXPECT_TRUE(ws1.is_valid());
  13410. ws::WebSocketClient ws2("ws://localhost:8080/");
  13411. EXPECT_TRUE(ws2.is_valid());
  13412. }
  13413. class WebSocketIntegrationTest : public ::testing::Test {
  13414. protected:
  13415. void SetUp() override {
  13416. server_ = httplib::detail::make_unique<Server>();
  13417. setup_server();
  13418. start_server();
  13419. }
  13420. void TearDown() override {
  13421. server_->stop();
  13422. if (server_thread_.joinable()) { server_thread_.join(); }
  13423. }
  13424. void setup_server() {
  13425. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13426. std::string msg;
  13427. ws::ReadResult ret;
  13428. while ((ret = ws.read(msg))) {
  13429. if (ret == ws::Binary) {
  13430. ws.send(msg.data(), msg.size());
  13431. } else {
  13432. ws.send(msg);
  13433. }
  13434. }
  13435. });
  13436. server_->WebSocket("/ws-echo-string",
  13437. [](const Request &, ws::WebSocket &ws) {
  13438. std::string msg;
  13439. while (ws.read(msg)) {
  13440. ws.send("echo: " + msg);
  13441. }
  13442. });
  13443. server_->WebSocket(
  13444. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13445. // Echo back request metadata
  13446. ws.send("path:" + req.path);
  13447. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13448. std::string msg;
  13449. while (ws.read(msg)) {}
  13450. });
  13451. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13452. std::string msg;
  13453. ws.read(msg); // wait for a message
  13454. ws.close();
  13455. });
  13456. server_->WebSocket("/ws-close-status",
  13457. [](const Request &, ws::WebSocket &ws) {
  13458. std::string msg;
  13459. ws.read(msg); // wait for a message
  13460. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13461. });
  13462. server_->WebSocket(
  13463. "/ws-subprotocol",
  13464. [](const Request &, ws::WebSocket &ws) {
  13465. std::string msg;
  13466. while (ws.read(msg)) {
  13467. ws.send(msg);
  13468. }
  13469. },
  13470. [](const std::vector<std::string> &protocols) -> std::string {
  13471. for (const auto &p : protocols) {
  13472. if (p == "graphql-ws") { return p; }
  13473. }
  13474. return "";
  13475. });
  13476. }
  13477. void start_server() {
  13478. port_ = server_->bind_to_any_port(HOST);
  13479. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13480. server_->wait_until_ready();
  13481. }
  13482. std::unique_ptr<Server> server_;
  13483. std::thread server_thread_;
  13484. int port_ = 0;
  13485. };
  13486. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13487. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13488. "/ws-echo");
  13489. ASSERT_TRUE(client.connect());
  13490. ASSERT_TRUE(client.is_open());
  13491. ASSERT_TRUE(client.send("Hello WebSocket"));
  13492. std::string msg;
  13493. EXPECT_EQ(ws::Text, client.read(msg));
  13494. EXPECT_EQ("Hello WebSocket", msg);
  13495. client.close();
  13496. }
  13497. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13498. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13499. "/ws-echo");
  13500. ASSERT_TRUE(client.connect());
  13501. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13502. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13503. std::string msg;
  13504. EXPECT_EQ(ws::Binary, client.read(msg));
  13505. EXPECT_EQ(binary_data, msg);
  13506. client.close();
  13507. }
  13508. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13509. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13510. "/ws-echo");
  13511. ASSERT_TRUE(client.connect());
  13512. for (int i = 0; i < 10; i++) {
  13513. auto text = "message " + std::to_string(i);
  13514. ASSERT_TRUE(client.send(text));
  13515. std::string msg;
  13516. ASSERT_TRUE(client.read(msg));
  13517. EXPECT_EQ(text, msg);
  13518. }
  13519. client.close();
  13520. }
  13521. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13522. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13523. "/ws-close");
  13524. ASSERT_TRUE(client.connect());
  13525. // Send a message to trigger the server to close
  13526. ASSERT_TRUE(client.send("trigger close"));
  13527. // The server will close, so read should return false
  13528. std::string msg;
  13529. EXPECT_FALSE(client.read(msg));
  13530. EXPECT_FALSE(client.is_open());
  13531. }
  13532. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13533. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13534. "/ws-echo");
  13535. ASSERT_TRUE(client.connect());
  13536. // 128KB message
  13537. std::string large_data(128 * 1024, 'X');
  13538. ASSERT_TRUE(client.send(large_data));
  13539. std::string msg;
  13540. ASSERT_TRUE(client.read(msg));
  13541. EXPECT_EQ(large_data, msg);
  13542. client.close();
  13543. }
  13544. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13545. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13546. "/ws-echo");
  13547. ASSERT_TRUE(client.connect());
  13548. const int num_threads = 4;
  13549. std::vector<std::thread> threads;
  13550. std::atomic<int> send_count{0};
  13551. for (int t = 0; t < num_threads; t++) {
  13552. threads.emplace_back([&client, &send_count, t]() {
  13553. for (int i = 0; i < 5; i++) {
  13554. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13555. if (client.send(text)) { send_count++; }
  13556. }
  13557. });
  13558. }
  13559. for (auto &th : threads) {
  13560. th.join();
  13561. }
  13562. int received = 0;
  13563. std::string msg;
  13564. while (received < send_count.load()) {
  13565. if (!client.read(msg)) { break; }
  13566. received++;
  13567. }
  13568. EXPECT_EQ(send_count.load(), received);
  13569. client.close();
  13570. }
  13571. TEST_F(WebSocketIntegrationTest, ReadString) {
  13572. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13573. "/ws-echo-string");
  13574. ASSERT_TRUE(client.connect());
  13575. ASSERT_TRUE(client.send("hello"));
  13576. std::string msg;
  13577. ASSERT_TRUE(client.read(msg));
  13578. EXPECT_EQ("echo: hello", msg);
  13579. ASSERT_TRUE(client.send("world"));
  13580. ASSERT_TRUE(client.read(msg));
  13581. EXPECT_EQ("echo: world", msg);
  13582. client.close();
  13583. }
  13584. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  13585. Headers headers = {{"X-Test-Header", "test-value"}};
  13586. ws::WebSocketClient client(
  13587. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  13588. ASSERT_TRUE(client.connect());
  13589. std::string msg;
  13590. ASSERT_TRUE(client.read(msg));
  13591. EXPECT_EQ("path:/ws-request-info", msg);
  13592. ASSERT_TRUE(client.read(msg));
  13593. EXPECT_EQ("header:test-value", msg);
  13594. client.close();
  13595. }
  13596. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  13597. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13598. "/ws-echo");
  13599. client.set_read_timeout(1, 0); // 1 second
  13600. ASSERT_TRUE(client.connect());
  13601. // Don't send anything — server echo handler waits for a message,
  13602. // so read() should time out and return false.
  13603. std::string msg;
  13604. EXPECT_FALSE(client.read(msg));
  13605. }
  13606. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  13607. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13608. "/ws-echo");
  13609. client.set_read_timeout(5, 0);
  13610. ASSERT_TRUE(client.connect());
  13611. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13612. // The server should reject it and close the connection.
  13613. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  13614. client.send(oversized);
  13615. // The server's read() should have failed due to payload limit,
  13616. // so our read() should return false (connection closed).
  13617. std::string msg;
  13618. EXPECT_FALSE(client.read(msg));
  13619. }
  13620. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  13621. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13622. "/ws-echo");
  13623. client.set_read_timeout(10, 0);
  13624. ASSERT_TRUE(client.connect());
  13625. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13626. // This should succeed.
  13627. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  13628. ASSERT_TRUE(client.send(at_limit));
  13629. std::string msg;
  13630. ASSERT_TRUE(client.read(msg));
  13631. EXPECT_EQ(at_limit.size(), msg.size());
  13632. client.close();
  13633. }
  13634. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  13635. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13636. "/nonexistent");
  13637. EXPECT_FALSE(client.connect());
  13638. EXPECT_FALSE(client.is_open());
  13639. }
  13640. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  13641. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13642. "/ws-echo");
  13643. ASSERT_TRUE(client.connect());
  13644. ASSERT_TRUE(client.send(""));
  13645. std::string msg;
  13646. EXPECT_EQ(ws::Text, client.read(msg));
  13647. EXPECT_EQ("", msg);
  13648. client.close();
  13649. }
  13650. TEST_F(WebSocketIntegrationTest, Reconnect) {
  13651. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13652. "/ws-echo");
  13653. // First connection
  13654. ASSERT_TRUE(client.connect());
  13655. ASSERT_TRUE(client.send("first"));
  13656. std::string msg;
  13657. ASSERT_TRUE(client.read(msg));
  13658. EXPECT_EQ("first", msg);
  13659. client.close();
  13660. EXPECT_FALSE(client.is_open());
  13661. // Reconnect using the same client object
  13662. ASSERT_TRUE(client.connect());
  13663. ASSERT_TRUE(client.is_open());
  13664. ASSERT_TRUE(client.send("second"));
  13665. ASSERT_TRUE(client.read(msg));
  13666. EXPECT_EQ("second", msg);
  13667. client.close();
  13668. }
  13669. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  13670. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13671. "/ws-close-status");
  13672. ASSERT_TRUE(client.connect());
  13673. // Trigger the server to close with GoingAway status
  13674. ASSERT_TRUE(client.send("trigger"));
  13675. // read() should return false after receiving the close frame
  13676. std::string msg;
  13677. EXPECT_FALSE(client.read(msg));
  13678. EXPECT_FALSE(client.is_open());
  13679. }
  13680. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  13681. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13682. "/ws-echo");
  13683. ASSERT_TRUE(client.connect());
  13684. client.close(ws::CloseStatus::GoingAway, "client leaving");
  13685. EXPECT_FALSE(client.is_open());
  13686. }
  13687. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  13688. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  13689. ws::WebSocketClient client(
  13690. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13691. ASSERT_TRUE(client.connect());
  13692. // Server should have selected graphql-ws
  13693. EXPECT_EQ("graphql-ws", client.subprotocol());
  13694. client.close();
  13695. }
  13696. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  13697. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  13698. ws::WebSocketClient client(
  13699. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13700. ASSERT_TRUE(client.connect());
  13701. // Server should not have selected any subprotocol
  13702. EXPECT_TRUE(client.subprotocol().empty());
  13703. client.close();
  13704. }
  13705. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  13706. // Connect without requesting any subprotocol
  13707. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13708. "/ws-subprotocol");
  13709. ASSERT_TRUE(client.connect());
  13710. EXPECT_TRUE(client.subprotocol().empty());
  13711. client.close();
  13712. }
  13713. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  13714. Server svr;
  13715. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  13716. if (!req.has_header("Authorization")) {
  13717. res.status = StatusCode::Unauthorized_401;
  13718. res.set_content("Unauthorized", "text/plain");
  13719. return Server::HandlerResponse::Handled;
  13720. }
  13721. return Server::HandlerResponse::Unhandled;
  13722. });
  13723. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13724. std::string msg;
  13725. while (ws.read(msg)) {
  13726. ws.send(msg);
  13727. }
  13728. });
  13729. auto port = svr.bind_to_any_port("localhost");
  13730. std::thread t([&]() { svr.listen_after_bind(); });
  13731. svr.wait_until_ready();
  13732. // Without Authorization header - should be rejected before upgrade
  13733. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  13734. EXPECT_FALSE(client1.connect());
  13735. // With Authorization header - should succeed
  13736. Headers headers = {{"Authorization", "Bearer token123"}};
  13737. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  13738. headers);
  13739. ASSERT_TRUE(client2.connect());
  13740. ASSERT_TRUE(client2.send("hello"));
  13741. std::string msg;
  13742. ASSERT_TRUE(client2.read(msg));
  13743. EXPECT_EQ("hello", msg);
  13744. client2.close();
  13745. svr.stop();
  13746. t.join();
  13747. }
  13748. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13749. class WebSocketSSLIntegrationTest : public ::testing::Test {
  13750. protected:
  13751. void SetUp() override {
  13752. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  13753. SERVER_PRIVATE_KEY_FILE);
  13754. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13755. std::string msg;
  13756. ws::ReadResult ret;
  13757. while ((ret = ws.read(msg))) {
  13758. if (ret == ws::Binary) {
  13759. ws.send(msg.data(), msg.size());
  13760. } else {
  13761. ws.send(msg);
  13762. }
  13763. }
  13764. });
  13765. port_ = server_->bind_to_any_port(HOST);
  13766. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13767. server_->wait_until_ready();
  13768. }
  13769. void TearDown() override {
  13770. server_->stop();
  13771. if (server_thread_.joinable()) { server_thread_.join(); }
  13772. }
  13773. std::unique_ptr<SSLServer> server_;
  13774. std::thread server_thread_;
  13775. int port_ = 0;
  13776. };
  13777. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  13778. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  13779. "/ws-echo");
  13780. client.enable_server_certificate_verification(false);
  13781. ASSERT_TRUE(client.connect());
  13782. ASSERT_TRUE(client.is_open());
  13783. ASSERT_TRUE(client.send("Hello WSS"));
  13784. std::string msg;
  13785. EXPECT_EQ(ws::Text, client.read(msg));
  13786. EXPECT_EQ("Hello WSS", msg);
  13787. client.close();
  13788. }
  13789. #endif