test.cc 523 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078
  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_TRUE(s0.is_peer_alive());
  269. EXPECT_EQ(0, close(fds[1]));
  270. EXPECT_FALSE(s0.is_peer_alive());
  271. return true;
  272. });
  273. EXPECT_EQ(0, close(fds[0]));
  274. }
  275. TEST(SocketStream, wait_writable_INET) {
  276. sockaddr_in addr;
  277. memset(&addr, 0, sizeof(addr));
  278. addr.sin_family = AF_INET;
  279. addr.sin_port = htons(PORT + 1);
  280. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  281. int disconnected_svr_sock = -1;
  282. std::thread svr{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, listen(s, 1));
  287. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  288. ASSERT_EQ(0, close(s));
  289. }};
  290. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  291. std::thread cli{[&] {
  292. const int s = socket(AF_INET, SOCK_STREAM, 0);
  293. ASSERT_LE(0, s);
  294. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  295. ASSERT_EQ(0, close(s));
  296. }};
  297. cli.join();
  298. svr.join();
  299. ASSERT_NE(disconnected_svr_sock, -1);
  300. const auto asSocketStream = [&](socket_t fd,
  301. std::function<bool(Stream &)> func) {
  302. return detail::process_client_socket(
  303. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  304. };
  305. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  306. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  307. // wait_writable() returns true because select_write() only checks if the
  308. // send buffer has space. Peer disconnection is detected later by send().
  309. EXPECT_TRUE(ss.wait_writable());
  310. return true;
  311. });
  312. ASSERT_EQ(0, close(disconnected_svr_sock));
  313. }
  314. #endif // #ifndef _WIN32
  315. TEST(ClientTest, MoveConstructible) {
  316. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  317. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  318. }
  319. TEST(ClientTest, MoveAssignable) {
  320. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  321. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  322. }
  323. #ifdef _WIN32
  324. TEST(StartupTest, WSAStartup) {
  325. WSADATA wsaData;
  326. int ret = WSAStartup(0x0002, &wsaData);
  327. ASSERT_EQ(0, ret);
  328. }
  329. #endif
  330. TEST(DecodePathTest, PercentCharacter) {
  331. EXPECT_EQ(
  332. decode_path_component(
  333. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  334. U8("descrip=Gastos áéíóúñÑ 6"));
  335. }
  336. TEST(DecodePathTest, PercentCharacterNUL) {
  337. string expected;
  338. expected.push_back('x');
  339. expected.push_back('\0');
  340. expected.push_back('x');
  341. EXPECT_EQ(decode_path_component("x%00x"), expected);
  342. }
  343. TEST(DecodePathTest, UnicodeEncoding) {
  344. // %u0041 = 'A' (1-byte UTF-8)
  345. EXPECT_EQ("A", decode_path_component("%u0041"));
  346. // %u00E9 = 'é' (2-byte UTF-8)
  347. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  348. // %u3042 = 'あ' (3-byte UTF-8)
  349. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  350. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  351. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  352. // %uD800 = surrogate (invalid, silently dropped)
  353. EXPECT_EQ("", decode_path_component("%uD800"));
  354. }
  355. TEST(SanitizeFilenameTest, VariousPatterns) {
  356. // Path traversal
  357. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  359. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  360. // Normal and edge cases
  361. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  362. EXPECT_EQ("filename.txt",
  363. httplib::sanitize_filename("/path/to/filename.txt"));
  364. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  365. EXPECT_EQ("", httplib::sanitize_filename(".."));
  366. EXPECT_EQ("", httplib::sanitize_filename(""));
  367. // Null bytes stripped
  368. EXPECT_EQ("safe.txt",
  369. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  370. // Whitespace-only rejected
  371. EXPECT_EQ("", httplib::sanitize_filename(" "));
  372. }
  373. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  374. string unescapedCharacters = "-_.!~*'()";
  375. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  376. }
  377. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  378. string reservedCharacters = ";,/?:@&=+$";
  379. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  380. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  381. }
  382. TEST(ClientQueryOrder, PreserveOrder) {
  383. // This test reproduces Issue #2259: client may reorder query parameters
  384. // when sending a GET request. The expected behavior is that the client
  385. // preserves the original query string order when the caller supplied it
  386. // as part of the path.
  387. Server svr;
  388. svr.Get("/", [&](const Request &req, Response &res) {
  389. // Echo back the raw target so the test can assert ordering
  390. res.set_content(req.target, "text/plain");
  391. });
  392. std::thread t{[&] { svr.listen(HOST, PORT); }};
  393. auto se = detail::scope_exit([&] {
  394. svr.stop();
  395. t.join();
  396. ASSERT_FALSE(svr.is_running());
  397. });
  398. svr.wait_until_ready();
  399. Client cli(HOST, PORT);
  400. ASSERT_TRUE(cli.is_valid());
  401. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  402. auto res = cli.Get(original);
  403. ASSERT_TRUE(res);
  404. // Expect the echoed target to exactly match the original path (order
  405. // preserved)
  406. EXPECT_EQ(res->body, original);
  407. }
  408. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  409. string chineseCharacters = U8("中国語");
  410. string russianCharacters = U8("дом");
  411. string brazilianCharacters = U8("óculos");
  412. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  413. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  414. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  415. "%D0%B4%D0%BE%D0%BC");
  416. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  417. }
  418. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  419. string unescapedCharacters = "-_.!~*'()";
  420. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  421. }
  422. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  423. string reservedCharacters = ";,/?:@&=+$";
  424. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  425. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  426. }
  427. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  428. string chineseCharacters = U8("中国語");
  429. string russianCharacters = U8("дом");
  430. string brazilianCharacters = U8("óculos");
  431. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  432. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  433. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  434. "%D0%B4%D0%BE%D0%BC");
  435. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  436. }
  437. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  438. // Issue #2082 use case: encoding path component with ampersand
  439. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  440. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  441. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  442. }
  443. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  444. string unescapedCharacters = "-_.!~*'()";
  445. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  446. }
  447. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  448. string reservedCharacters = ";,/?:@&=+$#";
  449. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  450. }
  451. TEST(EncodeUriTest, TestUTF8Characters) {
  452. string chineseCharacters = U8("中国語");
  453. string russianCharacters = U8("дом");
  454. string brazilianCharacters = U8("óculos");
  455. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  456. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  457. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  458. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  459. }
  460. TEST(EncodeUriTest, TestCompleteUri) {
  461. string uri =
  462. "https://example.com/path/to/resource?query=value&param=test#fragment";
  463. EXPECT_EQ(
  464. httplib::encode_uri(uri),
  465. "https://example.com/path/to/resource?query=value&param=test#fragment");
  466. }
  467. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  468. string uri =
  469. "https://example.com/path with spaces/file name.html?q=hello world";
  470. EXPECT_EQ(httplib::encode_uri(uri),
  471. "https://example.com/path%20with%20spaces/"
  472. "file%20name.html?q=hello%20world");
  473. }
  474. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  475. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  476. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  477. }
  478. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  479. string unescapedCharacters = "-_.!~*'()";
  480. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  481. }
  482. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  483. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  484. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  485. string encodedBrazilian = "%C3%B3culos";
  486. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  487. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  488. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  489. }
  490. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  491. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  492. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  493. "Piri Tommy Villiers - on & on");
  494. }
  495. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  496. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  497. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  498. }
  499. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  500. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  501. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  502. }
  503. TEST(DecodeUriTest, TestUTF8Characters) {
  504. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  505. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  506. string encodedBrazilian = "%C3%B3culos";
  507. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  508. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  509. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  510. }
  511. TEST(DecodeUriTest, TestCompleteUri) {
  512. string encodedUri = "https://example.com/path%20with%20spaces/"
  513. "file%20name.html?q=hello%20world";
  514. EXPECT_EQ(
  515. httplib::decode_uri(encodedUri),
  516. "https://example.com/path with spaces/file name.html?q=hello world");
  517. }
  518. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  519. string original =
  520. "https://example.com/path with spaces/file name.html?q=hello world";
  521. string encoded = httplib::encode_uri(original);
  522. string decoded = httplib::decode_uri(encoded);
  523. EXPECT_EQ(decoded, original);
  524. }
  525. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  526. string original = "Piri Tommy Villiers - on & on";
  527. string encoded = httplib::encode_uri_component(original);
  528. string decoded = httplib::decode_uri_component(encoded);
  529. EXPECT_EQ(decoded, original);
  530. }
  531. TEST(TrimTests, TrimStringTests) {
  532. EXPECT_EQ("abc", detail::trim_copy("abc"));
  533. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  534. EXPECT_TRUE(detail::trim_copy("").empty());
  535. }
  536. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  537. // Simple case without quality values
  538. std::vector<std::string> result1;
  539. EXPECT_TRUE(detail::parse_accept_header(
  540. "text/html,application/json,text/plain", result1));
  541. EXPECT_EQ(result1.size(), 3U);
  542. EXPECT_EQ(result1[0], "text/html");
  543. EXPECT_EQ(result1[1], "application/json");
  544. EXPECT_EQ(result1[2], "text/plain");
  545. // With quality values
  546. std::vector<std::string> result2;
  547. EXPECT_TRUE(detail::parse_accept_header(
  548. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  549. EXPECT_EQ(result2.size(), 3U);
  550. EXPECT_EQ(result2[0], "application/json"); // highest q value
  551. EXPECT_EQ(result2[1], "text/html");
  552. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  553. }
  554. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  555. // Mixed with and without quality values
  556. std::vector<std::string> result;
  557. EXPECT_TRUE(detail::parse_accept_header(
  558. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  559. EXPECT_EQ(result.size(), 3U);
  560. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  561. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  562. EXPECT_EQ(result[2], "application/json"); // q=0.5
  563. }
  564. TEST(ParseAcceptHeaderTest, EdgeCases) {
  565. // Empty header
  566. std::vector<std::string> empty_result;
  567. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  568. EXPECT_TRUE(empty_result.empty());
  569. // Single type
  570. std::vector<std::string> single_result;
  571. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  572. EXPECT_EQ(single_result.size(), 1U);
  573. EXPECT_EQ(single_result[0], "application/json");
  574. // Wildcard types
  575. std::vector<std::string> wildcard_result;
  576. EXPECT_TRUE(detail::parse_accept_header(
  577. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  578. EXPECT_EQ(wildcard_result.size(), 3U);
  579. EXPECT_EQ(wildcard_result[0], "application/json");
  580. EXPECT_EQ(wildcard_result[1], "text/*");
  581. EXPECT_EQ(wildcard_result[2], "*/*");
  582. }
  583. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  584. // Common browser Accept header
  585. std::vector<std::string> browser_result;
  586. EXPECT_TRUE(
  587. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  588. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  589. browser_result));
  590. EXPECT_EQ(browser_result.size(), 6U);
  591. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  592. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  593. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  594. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  595. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  596. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  597. // API client header
  598. std::vector<std::string> api_result;
  599. EXPECT_TRUE(detail::parse_accept_header(
  600. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  601. api_result));
  602. EXPECT_EQ(api_result.size(), 3U);
  603. EXPECT_EQ(api_result[0], "application/json");
  604. EXPECT_EQ(api_result[1], "application/xml");
  605. EXPECT_EQ(api_result[2], "text/plain");
  606. }
  607. TEST(ParseAcceptHeaderTest, SpecialCases) {
  608. // Quality value with 3 decimal places
  609. std::vector<std::string> decimal_result;
  610. EXPECT_TRUE(detail::parse_accept_header(
  611. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  612. EXPECT_EQ(decimal_result.size(), 2U);
  613. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  614. EXPECT_EQ(decimal_result[1], "text/html");
  615. // Zero quality (should still be included but with lowest priority)
  616. std::vector<std::string> zero_q_result;
  617. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  618. zero_q_result));
  619. EXPECT_EQ(zero_q_result.size(), 2U);
  620. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  621. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  622. // No spaces around commas
  623. std::vector<std::string> no_space_result;
  624. EXPECT_TRUE(detail::parse_accept_header(
  625. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  626. no_space_result));
  627. EXPECT_EQ(no_space_result.size(), 3U);
  628. EXPECT_EQ(no_space_result[0], "text/html");
  629. EXPECT_EQ(no_space_result[1], "application/json");
  630. EXPECT_EQ(no_space_result[2], "text/plain");
  631. }
  632. TEST(ParseAcceptHeaderTest, InvalidCases) {
  633. std::vector<std::string> result;
  634. // Invalid quality value (> 1.0)
  635. EXPECT_FALSE(
  636. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  637. // Invalid quality value (< 0.0)
  638. EXPECT_FALSE(
  639. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  640. // Invalid quality value (not a number)
  641. EXPECT_FALSE(detail::parse_accept_header(
  642. "text/html;q=invalid,application/json", result));
  643. // Empty quality value
  644. EXPECT_FALSE(
  645. detail::parse_accept_header("text/html;q=,application/json", result));
  646. // Invalid media type format (no slash and not wildcard)
  647. EXPECT_FALSE(
  648. detail::parse_accept_header("invalidtype,application/json", result));
  649. // Empty media type
  650. result.clear();
  651. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  652. // Only commas
  653. result.clear();
  654. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  655. // Valid cases should still work
  656. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  657. EXPECT_EQ(result.size(), 1U);
  658. EXPECT_EQ(result[0], "*/*");
  659. EXPECT_TRUE(detail::parse_accept_header("*", result));
  660. EXPECT_EQ(result.size(), 1U);
  661. EXPECT_EQ(result[0], "*");
  662. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  663. EXPECT_EQ(result.size(), 1U);
  664. EXPECT_EQ(result[0], "text/*");
  665. }
  666. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  667. Server svr;
  668. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  669. EXPECT_EQ(req.accept_content_types.size(), 3U);
  670. EXPECT_EQ(req.accept_content_types[0], "application/json");
  671. EXPECT_EQ(req.accept_content_types[1], "text/html");
  672. EXPECT_EQ(req.accept_content_types[2], "*/*");
  673. res.set_content("ok", "text/plain");
  674. });
  675. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  676. EXPECT_TRUE(false);
  677. res.set_content("bad request", "text/plain");
  678. });
  679. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  680. auto se = detail::scope_exit([&] {
  681. svr.stop();
  682. listen_thread.join();
  683. ASSERT_FALSE(svr.is_running());
  684. });
  685. svr.wait_until_ready();
  686. Client cli("localhost", PORT);
  687. {
  688. auto res =
  689. cli.Get("/accept_ok",
  690. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  691. ASSERT_TRUE(res);
  692. EXPECT_EQ(StatusCode::OK_200, res->status);
  693. }
  694. {
  695. auto res = cli.Get("/accept_bad_request",
  696. {{"Accept", "text/html;q=abc,application/json"}});
  697. ASSERT_TRUE(res);
  698. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  699. }
  700. }
  701. TEST(DivideTest, DivideStringTests) {
  702. auto divide = [](const std::string &str, char d) {
  703. std::string lhs;
  704. std::string rhs;
  705. detail::divide(str, d,
  706. [&](const char *lhs_data, std::size_t lhs_size,
  707. const char *rhs_data, std::size_t rhs_size) {
  708. lhs.assign(lhs_data, lhs_size);
  709. rhs.assign(rhs_data, rhs_size);
  710. });
  711. return std::make_pair(std::move(lhs), std::move(rhs));
  712. };
  713. {
  714. const auto res = divide("", '=');
  715. EXPECT_EQ(res.first, "");
  716. EXPECT_EQ(res.second, "");
  717. }
  718. {
  719. const auto res = divide("=", '=');
  720. EXPECT_EQ(res.first, "");
  721. EXPECT_EQ(res.second, "");
  722. }
  723. {
  724. const auto res = divide(" ", '=');
  725. EXPECT_EQ(res.first, " ");
  726. EXPECT_EQ(res.second, "");
  727. }
  728. {
  729. const auto res = divide("a", '=');
  730. EXPECT_EQ(res.first, "a");
  731. EXPECT_EQ(res.second, "");
  732. }
  733. {
  734. const auto res = divide("a=", '=');
  735. EXPECT_EQ(res.first, "a");
  736. EXPECT_EQ(res.second, "");
  737. }
  738. {
  739. const auto res = divide("=b", '=');
  740. EXPECT_EQ(res.first, "");
  741. EXPECT_EQ(res.second, "b");
  742. }
  743. {
  744. const auto res = divide("a=b", '=');
  745. EXPECT_EQ(res.first, "a");
  746. EXPECT_EQ(res.second, "b");
  747. }
  748. {
  749. const auto res = divide("a=b=", '=');
  750. EXPECT_EQ(res.first, "a");
  751. EXPECT_EQ(res.second, "b=");
  752. }
  753. {
  754. const auto res = divide("a=b=c", '=');
  755. EXPECT_EQ(res.first, "a");
  756. EXPECT_EQ(res.second, "b=c");
  757. }
  758. }
  759. TEST(SplitTest, ParseQueryString) {
  760. string s = "key1=val1&key2=val2&key3=val3";
  761. Params dic;
  762. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  763. [&](const char *b, const char *e) {
  764. string key, val;
  765. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  766. if (key.empty()) {
  767. key.assign(b2, e2);
  768. } else {
  769. val.assign(b2, e2);
  770. }
  771. });
  772. dic.emplace(key, val);
  773. });
  774. EXPECT_EQ("val1", dic.find("key1")->second);
  775. EXPECT_EQ("val2", dic.find("key2")->second);
  776. EXPECT_EQ("val3", dic.find("key3")->second);
  777. }
  778. TEST(SplitTest, ParseInvalidQueryTests) {
  779. {
  780. string s = " ";
  781. Params dict;
  782. detail::parse_query_text(s, dict);
  783. EXPECT_TRUE(dict.empty());
  784. }
  785. {
  786. string s = " = =";
  787. Params dict;
  788. detail::parse_query_text(s, dict);
  789. EXPECT_TRUE(dict.empty());
  790. }
  791. }
  792. TEST(ParseQueryTest, ParseQueryString) {
  793. {
  794. std::string s = "key1=val1&key2=val2&key3=val3";
  795. Params dic;
  796. detail::parse_query_text(s, dic);
  797. EXPECT_EQ("val1", dic.find("key1")->second);
  798. EXPECT_EQ("val2", dic.find("key2")->second);
  799. EXPECT_EQ("val3", dic.find("key3")->second);
  800. }
  801. {
  802. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  803. Params dic;
  804. detail::parse_query_text(s, dic);
  805. EXPECT_EQ("", dic.find("key1")->second);
  806. EXPECT_EQ("val1", dic.find("key2")->second);
  807. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  808. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  809. }
  810. }
  811. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  812. Params dic;
  813. EXPECT_EQ(detail::params_to_query_str(dic), "");
  814. dic.emplace("key1", "val1");
  815. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  816. dic.emplace("key2", "val2");
  817. dic.emplace("key3", "val3");
  818. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  819. }
  820. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  821. string content_type = "multipart/form-data; boundary=something";
  822. string boundary;
  823. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  824. EXPECT_TRUE(ret);
  825. EXPECT_EQ(boundary, "something");
  826. }
  827. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  828. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  829. string boundary;
  830. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  831. EXPECT_TRUE(ret);
  832. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  833. }
  834. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  835. string content_type =
  836. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  837. string boundary;
  838. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  839. EXPECT_TRUE(ret);
  840. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  841. }
  842. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  843. string content_type =
  844. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  845. string boundary;
  846. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  847. EXPECT_TRUE(ret);
  848. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  849. }
  850. TEST(GetHeaderValueTest, DefaultValue) {
  851. Headers headers = {{"Dummy", "Dummy"}};
  852. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  853. EXPECT_STREQ("text/plain", val);
  854. }
  855. TEST(GetHeaderValueTest, DefaultValueInt) {
  856. Headers headers = {{"Dummy", "Dummy"}};
  857. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  858. EXPECT_EQ(100ull, val);
  859. }
  860. TEST(GetHeaderValueTest, RegularValue) {
  861. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  862. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  863. EXPECT_STREQ("text/html", val);
  864. }
  865. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  866. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  867. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  868. EXPECT_STREQ("text/html", val);
  869. }
  870. TEST(GetHeaderValueTest, SetContent) {
  871. Response res;
  872. res.set_content("html", "text/html");
  873. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  874. res.set_content("text", "text/plain");
  875. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  876. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  877. }
  878. TEST(GetHeaderValueTest, RegularValueInt) {
  879. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  880. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  881. EXPECT_EQ(100ull, val);
  882. }
  883. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  884. Headers headers = {{"Content-Length", "x"}};
  885. auto is_invalid_value = false;
  886. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  887. is_invalid_value);
  888. EXPECT_EQ(0ull, val);
  889. EXPECT_TRUE(is_invalid_value);
  890. }
  891. TEST(GetHeaderValueTest, Range) {
  892. {
  893. Headers headers = {make_range_header({{1, -1}})};
  894. auto val = detail::get_header_value(headers, "Range", 0, 0);
  895. EXPECT_STREQ("bytes=1-", val);
  896. }
  897. {
  898. Headers headers = {make_range_header({{-1, 1}})};
  899. auto val = detail::get_header_value(headers, "Range", 0, 0);
  900. EXPECT_STREQ("bytes=-1", val);
  901. }
  902. {
  903. Headers headers = {make_range_header({{1, 10}})};
  904. auto val = detail::get_header_value(headers, "Range", 0, 0);
  905. EXPECT_STREQ("bytes=1-10", val);
  906. }
  907. {
  908. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  909. auto val = detail::get_header_value(headers, "Range", 0, 0);
  910. EXPECT_STREQ("bytes=1-10, 100-", val);
  911. }
  912. {
  913. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  914. auto val = detail::get_header_value(headers, "Range", 0, 0);
  915. EXPECT_STREQ("bytes=1-10, 100-200", val);
  916. }
  917. {
  918. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  919. auto val = detail::get_header_value(headers, "Range", 0, 0);
  920. EXPECT_STREQ("bytes=0-0, -1", val);
  921. }
  922. }
  923. TEST(ParseHeaderValueTest, Range) {
  924. {
  925. Ranges ranges;
  926. auto ret = detail::parse_range_header("bytes=1-", ranges);
  927. EXPECT_TRUE(ret);
  928. EXPECT_EQ(1u, ranges.size());
  929. EXPECT_EQ(1u, ranges[0].first);
  930. EXPECT_EQ(-1, ranges[0].second);
  931. }
  932. {
  933. Ranges ranges;
  934. auto ret = detail::parse_range_header("bytes=-1", ranges);
  935. EXPECT_TRUE(ret);
  936. EXPECT_EQ(1u, ranges.size());
  937. EXPECT_EQ(-1, ranges[0].first);
  938. EXPECT_EQ(1u, ranges[0].second);
  939. }
  940. {
  941. Ranges ranges;
  942. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  943. EXPECT_TRUE(ret);
  944. EXPECT_EQ(1u, ranges.size());
  945. EXPECT_EQ(1u, ranges[0].first);
  946. EXPECT_EQ(10u, ranges[0].second);
  947. }
  948. {
  949. Ranges ranges;
  950. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  951. EXPECT_FALSE(ret);
  952. }
  953. {
  954. Ranges ranges;
  955. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  956. EXPECT_TRUE(ret);
  957. EXPECT_EQ(2u, ranges.size());
  958. EXPECT_EQ(1u, ranges[0].first);
  959. EXPECT_EQ(10u, ranges[0].second);
  960. EXPECT_EQ(100u, ranges[1].first);
  961. EXPECT_EQ(-1, ranges[1].second);
  962. }
  963. {
  964. Ranges ranges;
  965. auto ret =
  966. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  967. EXPECT_TRUE(ret);
  968. EXPECT_EQ(3u, ranges.size());
  969. EXPECT_EQ(1u, ranges[0].first);
  970. EXPECT_EQ(10u, ranges[0].second);
  971. EXPECT_EQ(100u, ranges[1].first);
  972. EXPECT_EQ(200u, ranges[1].second);
  973. EXPECT_EQ(300u, ranges[2].first);
  974. EXPECT_EQ(400u, ranges[2].second);
  975. }
  976. {
  977. Ranges ranges;
  978. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  979. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  980. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  981. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  982. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  983. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  984. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  985. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  986. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  987. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  988. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  989. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  990. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  991. EXPECT_TRUE(ranges.empty());
  992. }
  993. }
  994. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  995. Request req;
  996. req.set_header("Accept-Encoding", "gzip");
  997. Response res;
  998. res.set_header("Content-Type", "text/plain");
  999. auto ret = detail::encoding_type(req, res);
  1000. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1001. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1002. #else
  1003. EXPECT_TRUE(ret == detail::EncodingType::None);
  1004. #endif
  1005. }
  1006. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1007. Request req;
  1008. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1009. Response res;
  1010. res.set_header("Content-Type", "text/plain");
  1011. auto ret = detail::encoding_type(req, res);
  1012. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1013. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1014. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1015. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1016. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1017. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1018. #else
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. #endif
  1021. }
  1022. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1023. Request req;
  1024. req.set_header("Accept-Encoding",
  1025. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1026. Response res;
  1027. res.set_header("Content-Type", "text/plain");
  1028. auto ret = detail::encoding_type(req, res);
  1029. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1030. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1031. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1032. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1033. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1034. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1035. #else
  1036. EXPECT_TRUE(ret == detail::EncodingType::None);
  1037. #endif
  1038. }
  1039. TEST(BufferStreamTest, read) {
  1040. detail::BufferStream strm1;
  1041. Stream &strm = strm1;
  1042. EXPECT_EQ(5, strm.write("hello"));
  1043. char buf[512];
  1044. EXPECT_EQ(2, strm.read(buf, 2));
  1045. EXPECT_EQ('h', buf[0]);
  1046. EXPECT_EQ('e', buf[1]);
  1047. EXPECT_EQ(2, strm.read(buf, 2));
  1048. EXPECT_EQ('l', buf[0]);
  1049. EXPECT_EQ('l', buf[1]);
  1050. EXPECT_EQ(1, strm.read(buf, 1));
  1051. EXPECT_EQ('o', buf[0]);
  1052. EXPECT_EQ(0, strm.read(buf, 1));
  1053. }
  1054. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1055. auto host = "www.httpwatch.com";
  1056. auto ip = hosted_at(host);
  1057. EXPECT_EQ("23.96.13.243", ip);
  1058. std::vector<std::string> addrs;
  1059. hosted_at(host, addrs);
  1060. EXPECT_EQ(1u, addrs.size());
  1061. }
  1062. #if 0 // It depends on each test environment...
  1063. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1064. auto host = "www.youtube.com";
  1065. std::vector<std::string> addrs;
  1066. hosted_at(host, addrs);
  1067. EXPECT_EQ(20u, addrs.size());
  1068. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1069. EXPECT_TRUE(it != addrs.end());
  1070. }
  1071. #endif
  1072. class ChunkedEncodingTest : public ::testing::Test {
  1073. protected:
  1074. ChunkedEncodingTest()
  1075. : cli_(HOST, PORT)
  1076. #ifdef CPPHTTPLIB_SSL_ENABLED
  1077. ,
  1078. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1079. #endif
  1080. {
  1081. cli_.set_connection_timeout(2);
  1082. #ifdef CPPHTTPLIB_SSL_ENABLED
  1083. cli_.enable_server_certificate_verification(false);
  1084. #endif
  1085. }
  1086. virtual void SetUp() {
  1087. read_file("./image.jpg", image_data_);
  1088. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1089. res.set_content("Hello World!", "text/plain");
  1090. });
  1091. svr_.Get(
  1092. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1093. res.set_chunked_content_provider(
  1094. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1095. size_t remaining = image_data_.size() - offset;
  1096. if (remaining == 0) {
  1097. sink.done();
  1098. } else {
  1099. constexpr size_t CHUNK_SIZE = 1024;
  1100. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1101. sink.write(&image_data_[offset], send_size);
  1102. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1103. }
  1104. return true;
  1105. });
  1106. });
  1107. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1108. svr_.wait_until_ready();
  1109. }
  1110. virtual void TearDown() {
  1111. svr_.stop();
  1112. if (!request_threads_.empty()) {
  1113. std::this_thread::sleep_for(std::chrono::seconds(1));
  1114. for (auto &t : request_threads_) {
  1115. t.join();
  1116. }
  1117. }
  1118. t_.join();
  1119. }
  1120. #ifdef CPPHTTPLIB_SSL_ENABLED
  1121. SSLClient cli_;
  1122. SSLServer svr_;
  1123. #else
  1124. Client cli_;
  1125. Server svr_;
  1126. #endif
  1127. thread t_;
  1128. std::vector<thread> request_threads_;
  1129. std::string image_data_;
  1130. };
  1131. TEST_F(ChunkedEncodingTest, NormalGet) {
  1132. auto res = cli_.Get("/chunked");
  1133. ASSERT_TRUE(res);
  1134. std::string out;
  1135. read_file("./image.jpg", out);
  1136. EXPECT_EQ(StatusCode::OK_200, res->status);
  1137. EXPECT_EQ(out, res->body);
  1138. }
  1139. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1140. std::string body;
  1141. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1142. body.append(data, data_length);
  1143. return true;
  1144. });
  1145. ASSERT_TRUE(res);
  1146. std::string out;
  1147. read_file("./image.jpg", out);
  1148. EXPECT_EQ(StatusCode::OK_200, res->status);
  1149. EXPECT_EQ(out, body);
  1150. }
  1151. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1152. std::string body;
  1153. auto res = cli_.Get(
  1154. "/chunked",
  1155. [&](const Response &response) {
  1156. EXPECT_EQ(StatusCode::OK_200, response.status);
  1157. return true;
  1158. },
  1159. [&](const char *data, size_t data_length) {
  1160. body.append(data, data_length);
  1161. return true;
  1162. });
  1163. ASSERT_TRUE(res);
  1164. std::string out;
  1165. read_file("./image.jpg", out);
  1166. EXPECT_EQ(StatusCode::OK_200, res->status);
  1167. EXPECT_EQ(out, body);
  1168. }
  1169. TEST(RangeTest, FromHTTPBin_Online) {
  1170. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1171. auto host = "httpcan.org";
  1172. auto path = std::string{"/range/32"};
  1173. #else
  1174. auto host = "nghttp2.org";
  1175. auto path = std::string{"/httpbin/range/32"};
  1176. #endif
  1177. #ifdef CPPHTTPLIB_SSL_ENABLED
  1178. auto port = 443;
  1179. SSLClient cli(host, port);
  1180. #else
  1181. auto port = 80;
  1182. Client cli(host, port);
  1183. #endif
  1184. cli.set_connection_timeout(5);
  1185. {
  1186. auto res = cli.Get(path);
  1187. ASSERT_TRUE(res);
  1188. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. }
  1191. {
  1192. Headers headers = {make_range_header({{1, -1}})};
  1193. auto res = cli.Get(path, headers);
  1194. ASSERT_TRUE(res);
  1195. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1197. }
  1198. {
  1199. Headers headers = {make_range_header({{1, 10}})};
  1200. auto res = cli.Get(path, headers);
  1201. ASSERT_TRUE(res);
  1202. EXPECT_EQ("bcdefghijk", res->body);
  1203. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1204. }
  1205. {
  1206. Headers headers = {make_range_header({{0, 31}})};
  1207. auto res = cli.Get(path, headers);
  1208. ASSERT_TRUE(res);
  1209. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1210. EXPECT_EQ(StatusCode::OK_200, res->status);
  1211. }
  1212. {
  1213. Headers headers = {make_range_header({{0, -1}})};
  1214. auto res = cli.Get(path, headers);
  1215. ASSERT_TRUE(res);
  1216. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1217. EXPECT_EQ(StatusCode::OK_200, res->status);
  1218. }
  1219. {
  1220. Headers headers = {make_range_header({{0, 32}})};
  1221. auto res = cli.Get(path, headers);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1224. }
  1225. }
  1226. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1227. auto host = "unresolvableaddress.local";
  1228. auto path = std::string{"/"};
  1229. #ifdef CPPHTTPLIB_SSL_ENABLED
  1230. auto port = 443;
  1231. SSLClient cli(host, port);
  1232. #else
  1233. auto port = 80;
  1234. Client cli(host, port);
  1235. #endif
  1236. cli.set_connection_timeout(1);
  1237. {
  1238. auto res = cli.Get(path);
  1239. ASSERT_FALSE(res);
  1240. }
  1241. std::this_thread::sleep_for(std::chrono::seconds(8));
  1242. }
  1243. TEST(ConnectionErrorTest, InvalidHost) {
  1244. auto host = "-abcde.com";
  1245. #ifdef CPPHTTPLIB_SSL_ENABLED
  1246. auto port = 443;
  1247. SSLClient cli(host, port);
  1248. #else
  1249. auto port = 80;
  1250. Client cli(host, port);
  1251. #endif
  1252. cli.set_connection_timeout(std::chrono::seconds(2));
  1253. auto res = cli.Get("/");
  1254. ASSERT_TRUE(!res);
  1255. EXPECT_EQ(Error::Connection, res.error());
  1256. }
  1257. TEST(ConnectionErrorTest, InvalidHost2) {
  1258. auto host = "httpcan.org/";
  1259. #ifdef CPPHTTPLIB_SSL_ENABLED
  1260. SSLClient cli(host);
  1261. #else
  1262. Client cli(host);
  1263. #endif
  1264. cli.set_connection_timeout(std::chrono::seconds(2));
  1265. auto res = cli.Get("/");
  1266. ASSERT_TRUE(!res);
  1267. EXPECT_EQ(Error::Connection, res.error());
  1268. }
  1269. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1270. auto host = "httpcan.org/";
  1271. #ifdef CPPHTTPLIB_SSL_ENABLED
  1272. SSLClient cli(host);
  1273. #else
  1274. Client cli(host);
  1275. #endif
  1276. cli.set_connection_timeout(std::chrono::seconds(2));
  1277. auto res = cli.Get("/");
  1278. ASSERT_TRUE(!res);
  1279. stringstream s;
  1280. s << "error code: " << res.error();
  1281. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1282. }
  1283. TEST(ConnectionErrorTest, InvalidPort) {
  1284. auto host = "localhost";
  1285. auto port = 44380;
  1286. #ifdef CPPHTTPLIB_SSL_ENABLED
  1287. SSLClient cli(host, port);
  1288. #else
  1289. Client cli(host, port);
  1290. #endif
  1291. cli.set_connection_timeout(std::chrono::seconds(2));
  1292. auto res = cli.Get("/");
  1293. ASSERT_TRUE(!res);
  1294. EXPECT_TRUE(Error::Connection == res.error() ||
  1295. Error::ConnectionTimeout == res.error());
  1296. }
  1297. TEST(ConnectionErrorTest, Timeout_Online) {
  1298. auto host = "google.com";
  1299. #ifdef CPPHTTPLIB_SSL_ENABLED
  1300. auto port = 44380;
  1301. SSLClient cli(host, port);
  1302. #else
  1303. auto port = 8080;
  1304. Client cli(host, port);
  1305. #endif
  1306. cli.set_connection_timeout(std::chrono::seconds(2));
  1307. // only probe one address type so that the error reason
  1308. // correlates to the timed-out IPv4, not the unsupported
  1309. // IPv6 connection attempt
  1310. cli.set_address_family(AF_INET);
  1311. auto res = cli.Get("/");
  1312. ASSERT_TRUE(!res);
  1313. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1314. }
  1315. TEST(CancelTest, NoCancel_Online) {
  1316. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1317. auto host = "httpcan.org";
  1318. auto path = std::string{"/range/32"};
  1319. #else
  1320. auto host = "nghttp2.org";
  1321. auto path = std::string{"/httpbin/range/32"};
  1322. #endif
  1323. #ifdef CPPHTTPLIB_SSL_ENABLED
  1324. auto port = 443;
  1325. SSLClient cli(host, port);
  1326. #else
  1327. auto port = 80;
  1328. Client cli(host, port);
  1329. #endif
  1330. cli.set_connection_timeout(std::chrono::seconds(5));
  1331. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1332. ASSERT_TRUE(res);
  1333. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1334. EXPECT_EQ(StatusCode::OK_200, res->status);
  1335. }
  1336. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1337. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1338. auto host = "httpcan.org";
  1339. auto path = std::string{"/range/32"};
  1340. #else
  1341. auto host = "nghttp2.org";
  1342. auto path = std::string{"/httpbin/range/32"};
  1343. #endif
  1344. #ifdef CPPHTTPLIB_SSL_ENABLED
  1345. auto port = 443;
  1346. SSLClient cli(host, port);
  1347. #else
  1348. auto port = 80;
  1349. Client cli(host, port);
  1350. #endif
  1351. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1352. cli.set_connection_timeout(std::chrono::seconds(5));
  1353. ASSERT_TRUE(!res);
  1354. EXPECT_EQ(Error::Canceled, res.error());
  1355. }
  1356. TEST(CancelTest, WithCancelLargePayload_Online) {
  1357. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1358. auto host = "httpcan.org";
  1359. auto path = std::string{"/range/65536"};
  1360. #else
  1361. auto host = "nghttp2.org";
  1362. auto path = std::string{"/httpbin/range/65536"};
  1363. #endif
  1364. #ifdef CPPHTTPLIB_SSL_ENABLED
  1365. auto port = 443;
  1366. SSLClient cli(host, port);
  1367. #else
  1368. auto port = 80;
  1369. Client cli(host, port);
  1370. #endif
  1371. cli.set_connection_timeout(std::chrono::seconds(5));
  1372. uint32_t count = 0;
  1373. auto res =
  1374. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1375. ASSERT_TRUE(!res);
  1376. EXPECT_EQ(Error::Canceled, res.error());
  1377. }
  1378. TEST(CancelTest, NoCancelPost) {
  1379. Server svr;
  1380. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1381. res.set_content("Hello World!", "text/plain");
  1382. });
  1383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1384. auto se = detail::scope_exit([&] {
  1385. svr.stop();
  1386. thread.join();
  1387. ASSERT_FALSE(svr.is_running());
  1388. });
  1389. svr.wait_until_ready();
  1390. Client cli(HOST, PORT);
  1391. cli.set_connection_timeout(std::chrono::seconds(5));
  1392. auto res =
  1393. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1394. "application/json", [](uint64_t, uint64_t) { return true; });
  1395. ASSERT_TRUE(res);
  1396. EXPECT_EQ("Hello World!", res->body);
  1397. EXPECT_EQ(StatusCode::OK_200, res->status);
  1398. }
  1399. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1400. Server svr;
  1401. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1402. res.set_content("Hello World!", "text/plain");
  1403. });
  1404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1405. auto se = detail::scope_exit([&] {
  1406. svr.stop();
  1407. thread.join();
  1408. ASSERT_FALSE(svr.is_running());
  1409. });
  1410. svr.wait_until_ready();
  1411. Client cli(HOST, PORT);
  1412. cli.set_connection_timeout(std::chrono::seconds(5));
  1413. auto res =
  1414. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1415. "application/json", [](uint64_t, uint64_t) { return false; });
  1416. ASSERT_TRUE(!res);
  1417. EXPECT_EQ(Error::Canceled, res.error());
  1418. }
  1419. TEST(CancelTest, WithCancelLargePayloadPost) {
  1420. Server svr;
  1421. svr.set_payload_max_length(200 * 1024 * 1024);
  1422. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1423. res.set_content(LARGE_DATA, "text/plain");
  1424. });
  1425. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1426. auto se = detail::scope_exit([&] {
  1427. svr.stop();
  1428. thread.join();
  1429. ASSERT_FALSE(svr.is_running());
  1430. });
  1431. svr.wait_until_ready();
  1432. Client cli(HOST, PORT);
  1433. cli.set_payload_max_length(200 * 1024 * 1024);
  1434. cli.set_connection_timeout(std::chrono::seconds(5));
  1435. auto res =
  1436. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1437. "application/json", [](uint64_t, uint64_t) { return false; });
  1438. ASSERT_TRUE(!res);
  1439. EXPECT_EQ(Error::Canceled, res.error());
  1440. }
  1441. TEST(CancelTest, NoCancelPut) {
  1442. Server svr;
  1443. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1444. res.set_content("Hello World!", "text/plain");
  1445. });
  1446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1447. auto se = detail::scope_exit([&] {
  1448. svr.stop();
  1449. thread.join();
  1450. ASSERT_FALSE(svr.is_running());
  1451. });
  1452. svr.wait_until_ready();
  1453. Client cli(HOST, PORT);
  1454. cli.set_connection_timeout(std::chrono::seconds(5));
  1455. auto res =
  1456. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1457. "application/json", [](uint64_t, uint64_t) { return true; });
  1458. ASSERT_TRUE(res);
  1459. EXPECT_EQ("Hello World!", res->body);
  1460. EXPECT_EQ(StatusCode::OK_200, res->status);
  1461. }
  1462. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1463. Server svr;
  1464. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1465. res.set_content("Hello World!", "text/plain");
  1466. });
  1467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1468. auto se = detail::scope_exit([&] {
  1469. svr.stop();
  1470. thread.join();
  1471. ASSERT_FALSE(svr.is_running());
  1472. });
  1473. svr.wait_until_ready();
  1474. Client cli(HOST, PORT);
  1475. cli.set_connection_timeout(std::chrono::seconds(5));
  1476. auto res =
  1477. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1478. "application/json", [](uint64_t, uint64_t) { return false; });
  1479. ASSERT_TRUE(!res);
  1480. EXPECT_EQ(Error::Canceled, res.error());
  1481. }
  1482. TEST(CancelTest, WithCancelLargePayloadPut) {
  1483. Server svr;
  1484. svr.set_payload_max_length(200 * 1024 * 1024);
  1485. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1486. res.set_content(LARGE_DATA, "text/plain");
  1487. });
  1488. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1489. auto se = detail::scope_exit([&] {
  1490. svr.stop();
  1491. thread.join();
  1492. ASSERT_FALSE(svr.is_running());
  1493. });
  1494. svr.wait_until_ready();
  1495. Client cli(HOST, PORT);
  1496. cli.set_payload_max_length(200 * 1024 * 1024);
  1497. cli.set_connection_timeout(std::chrono::seconds(5));
  1498. auto res =
  1499. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1500. "application/json", [](uint64_t, uint64_t) { return false; });
  1501. ASSERT_TRUE(!res);
  1502. EXPECT_EQ(Error::Canceled, res.error());
  1503. }
  1504. TEST(CancelTest, NoCancelPatch) {
  1505. Server svr;
  1506. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1507. res.set_content("Hello World!", "text/plain");
  1508. });
  1509. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1510. auto se = detail::scope_exit([&] {
  1511. svr.stop();
  1512. thread.join();
  1513. ASSERT_FALSE(svr.is_running());
  1514. });
  1515. svr.wait_until_ready();
  1516. Client cli(HOST, PORT);
  1517. cli.set_connection_timeout(std::chrono::seconds(5));
  1518. auto res =
  1519. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1520. "application/json", [](uint64_t, uint64_t) { return true; });
  1521. ASSERT_TRUE(res);
  1522. EXPECT_EQ("Hello World!", res->body);
  1523. EXPECT_EQ(StatusCode::OK_200, res->status);
  1524. }
  1525. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1526. Server svr;
  1527. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1528. res.set_content("Hello World!", "text/plain");
  1529. });
  1530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1531. auto se = detail::scope_exit([&] {
  1532. svr.stop();
  1533. thread.join();
  1534. ASSERT_FALSE(svr.is_running());
  1535. });
  1536. svr.wait_until_ready();
  1537. Client cli(HOST, PORT);
  1538. cli.set_connection_timeout(std::chrono::seconds(5));
  1539. auto res =
  1540. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1541. "application/json", [](uint64_t, uint64_t) { return false; });
  1542. ASSERT_TRUE(!res);
  1543. EXPECT_EQ(Error::Canceled, res.error());
  1544. }
  1545. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1546. Server svr;
  1547. svr.set_payload_max_length(200 * 1024 * 1024);
  1548. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1549. res.set_content(LARGE_DATA, "text/plain");
  1550. });
  1551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. thread.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. Client cli(HOST, PORT);
  1559. cli.set_payload_max_length(200 * 1024 * 1024);
  1560. cli.set_connection_timeout(std::chrono::seconds(5));
  1561. auto res =
  1562. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1563. "application/json", [](uint64_t, uint64_t) { return false; });
  1564. ASSERT_TRUE(!res);
  1565. EXPECT_EQ(Error::Canceled, res.error());
  1566. }
  1567. TEST(CancelTest, NoCancelDelete) {
  1568. Server svr;
  1569. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1570. res.set_content("Hello World!", "text/plain");
  1571. });
  1572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1573. auto se = detail::scope_exit([&] {
  1574. svr.stop();
  1575. thread.join();
  1576. ASSERT_FALSE(svr.is_running());
  1577. });
  1578. svr.wait_until_ready();
  1579. Client cli(HOST, PORT);
  1580. cli.set_connection_timeout(std::chrono::seconds(5));
  1581. auto res =
  1582. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1583. "application/json", [](uint64_t, uint64_t) { return true; });
  1584. ASSERT_TRUE(res);
  1585. EXPECT_EQ("Hello World!", res->body);
  1586. EXPECT_EQ(StatusCode::OK_200, res->status);
  1587. }
  1588. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1589. Server svr;
  1590. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1591. res.set_content("Hello World!", "text/plain");
  1592. });
  1593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1594. auto se = detail::scope_exit([&] {
  1595. svr.stop();
  1596. thread.join();
  1597. ASSERT_FALSE(svr.is_running());
  1598. });
  1599. svr.wait_until_ready();
  1600. Client cli(HOST, PORT);
  1601. cli.set_connection_timeout(std::chrono::seconds(5));
  1602. auto res =
  1603. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1604. "application/json", [](uint64_t, uint64_t) { return false; });
  1605. ASSERT_TRUE(!res);
  1606. EXPECT_EQ(Error::Canceled, res.error());
  1607. }
  1608. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1609. Server svr;
  1610. svr.set_payload_max_length(200 * 1024 * 1024);
  1611. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1612. res.set_content(LARGE_DATA, "text/plain");
  1613. });
  1614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1615. auto se = detail::scope_exit([&] {
  1616. svr.stop();
  1617. thread.join();
  1618. ASSERT_FALSE(svr.is_running());
  1619. });
  1620. svr.wait_until_ready();
  1621. Client cli(HOST, PORT);
  1622. cli.set_payload_max_length(200 * 1024 * 1024);
  1623. cli.set_connection_timeout(std::chrono::seconds(5));
  1624. auto res =
  1625. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1626. "application/json", [](uint64_t, uint64_t) { return false; });
  1627. ASSERT_TRUE(!res);
  1628. EXPECT_EQ(Error::Canceled, res.error());
  1629. }
  1630. static std::string remove_whitespace(const std::string &input) {
  1631. std::string output;
  1632. output.reserve(input.size());
  1633. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1634. [](unsigned char c) { return !std::isspace(c); });
  1635. return output;
  1636. }
  1637. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1638. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1639. auto host = "httpcan.org";
  1640. auto path = std::string{"/basic-auth/hello/world"};
  1641. #else
  1642. auto host = "nghttp2.org";
  1643. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1644. #endif
  1645. #ifdef CPPHTTPLIB_SSL_ENABLED
  1646. auto port = 443;
  1647. SSLClient cli(host, port);
  1648. #else
  1649. auto port = 80;
  1650. Client cli(host, port);
  1651. #endif
  1652. {
  1653. auto res = cli.Get(path);
  1654. ASSERT_TRUE(res);
  1655. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1656. }
  1657. {
  1658. auto res =
  1659. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1660. ASSERT_TRUE(res);
  1661. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1662. remove_whitespace(res->body));
  1663. EXPECT_EQ(StatusCode::OK_200, res->status);
  1664. }
  1665. {
  1666. cli.set_basic_auth("hello", "world");
  1667. auto res = cli.Get(path);
  1668. ASSERT_TRUE(res);
  1669. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1670. remove_whitespace(res->body));
  1671. EXPECT_EQ(StatusCode::OK_200, res->status);
  1672. }
  1673. {
  1674. cli.set_basic_auth("hello", "bad");
  1675. auto res = cli.Get(path);
  1676. ASSERT_TRUE(res);
  1677. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1678. }
  1679. {
  1680. cli.set_basic_auth("bad", "world");
  1681. auto res = cli.Get(path);
  1682. ASSERT_TRUE(res);
  1683. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1684. }
  1685. }
  1686. #ifdef CPPHTTPLIB_SSL_ENABLED
  1687. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1688. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1689. auto host = "httpcan.org";
  1690. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1691. auto paths = std::vector<std::string>{
  1692. "/digest-auth/auth/hello/world/MD5",
  1693. "/digest-auth/auth/hello/world/SHA-256",
  1694. "/digest-auth/auth/hello/world/SHA-512",
  1695. };
  1696. #else
  1697. auto host = "nghttp2.org";
  1698. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1699. auto paths = std::vector<std::string>{
  1700. "/httpbin/digest-auth/auth/hello/world/MD5",
  1701. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1702. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1703. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1704. };
  1705. #endif
  1706. auto port = 443;
  1707. SSLClient cli(host, port);
  1708. {
  1709. auto res = cli.Get(unauth_path);
  1710. ASSERT_TRUE(res);
  1711. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1712. }
  1713. {
  1714. cli.set_digest_auth("hello", "world");
  1715. for (const auto &path : paths) {
  1716. auto res = cli.Get(path.c_str());
  1717. ASSERT_TRUE(res);
  1718. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1719. std::string algo(path.substr(path.rfind('/') + 1));
  1720. EXPECT_EQ(
  1721. remove_whitespace("{\"algorithm\":\"" + algo +
  1722. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1723. remove_whitespace(res->body));
  1724. #else
  1725. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1726. remove_whitespace(res->body));
  1727. #endif
  1728. EXPECT_EQ(StatusCode::OK_200, res->status);
  1729. }
  1730. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1731. cli.set_digest_auth("hello", "bad");
  1732. for (const auto &path : paths) {
  1733. auto res = cli.Get(path.c_str());
  1734. ASSERT_TRUE(res);
  1735. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1736. }
  1737. #endif
  1738. }
  1739. }
  1740. #endif
  1741. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1742. auto host = "google.com";
  1743. auto another_host = "example.com";
  1744. auto wrong_ip = "0.0.0.0";
  1745. #ifdef CPPHTTPLIB_SSL_ENABLED
  1746. SSLClient cli(host);
  1747. #else
  1748. Client cli(host);
  1749. #endif
  1750. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1751. auto res = cli.Get("/");
  1752. ASSERT_TRUE(res);
  1753. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1754. }
  1755. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1756. auto host = "google.com";
  1757. auto wrong_ip = "0.0.0.0";
  1758. #ifdef CPPHTTPLIB_SSL_ENABLED
  1759. SSLClient cli(host);
  1760. #else
  1761. Client cli(host);
  1762. #endif
  1763. cli.set_hostname_addr_map({{host, wrong_ip}});
  1764. auto res = cli.Get("/");
  1765. ASSERT_TRUE(!res);
  1766. EXPECT_EQ(Error::Connection, res.error());
  1767. }
  1768. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1769. auto host = "nghttp2.org";
  1770. #ifdef CPPHTTPLIB_SSL_ENABLED
  1771. SSLClient cli(host);
  1772. #else
  1773. Client cli(host);
  1774. #endif
  1775. cli.set_follow_location(true);
  1776. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1777. ASSERT_TRUE(res);
  1778. EXPECT_EQ(StatusCode::OK_200, res->status);
  1779. }
  1780. TEST(RedirectTest, Redirect_Online) {
  1781. auto host = "nghttp2.org";
  1782. #ifdef CPPHTTPLIB_SSL_ENABLED
  1783. SSLClient cli(host);
  1784. #else
  1785. Client cli(host);
  1786. #endif
  1787. cli.set_follow_location(true);
  1788. auto res = cli.Get("/httpbin/redirect/3");
  1789. ASSERT_TRUE(res);
  1790. EXPECT_EQ(StatusCode::OK_200, res->status);
  1791. }
  1792. TEST(RelativeRedirectTest, Redirect_Online) {
  1793. auto host = "nghttp2.org";
  1794. #ifdef CPPHTTPLIB_SSL_ENABLED
  1795. SSLClient cli(host);
  1796. #else
  1797. Client cli(host);
  1798. #endif
  1799. cli.set_follow_location(true);
  1800. auto res = cli.Get("/httpbin/relative-redirect/3");
  1801. ASSERT_TRUE(res);
  1802. EXPECT_EQ(StatusCode::OK_200, res->status);
  1803. }
  1804. TEST(TooManyRedirectTest, Redirect_Online) {
  1805. auto host = "nghttp2.org";
  1806. #ifdef CPPHTTPLIB_SSL_ENABLED
  1807. SSLClient cli(host);
  1808. #else
  1809. Client cli(host);
  1810. #endif
  1811. cli.set_follow_location(true);
  1812. auto res = cli.Get("/httpbin/redirect/21");
  1813. ASSERT_TRUE(!res);
  1814. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1815. }
  1816. #ifdef CPPHTTPLIB_SSL_ENABLED
  1817. TEST(YahooRedirectTest, Redirect_Online) {
  1818. Client cli("yahoo.com");
  1819. auto res = cli.Get("/");
  1820. ASSERT_TRUE(res);
  1821. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1822. cli.set_follow_location(true);
  1823. res = cli.Get("/");
  1824. ASSERT_TRUE(res);
  1825. EXPECT_EQ(StatusCode::OK_200, res->status);
  1826. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1827. }
  1828. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1829. #define REDIR_HOST "httpbingo.org"
  1830. #define REDIR_PATH "/redirect-to"
  1831. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1832. SSLClient cli(REDIR_HOST);
  1833. cli.set_follow_location(true);
  1834. auto res =
  1835. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1836. ASSERT_TRUE(res);
  1837. EXPECT_EQ(StatusCode::OK_200, res->status);
  1838. }
  1839. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1840. SSLClient cli(REDIR_HOST);
  1841. cli.set_follow_location(true);
  1842. Params params;
  1843. params.emplace("url", "http://example.com");
  1844. params.emplace("status_code", "302");
  1845. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1846. ASSERT_TRUE(res);
  1847. EXPECT_EQ(StatusCode::OK_200, res->status);
  1848. }
  1849. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1850. SSLClient cli(REDIR_HOST);
  1851. cli.set_follow_location(true);
  1852. Params params;
  1853. params.emplace("url", "http://example.com");
  1854. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1855. ASSERT_TRUE(res);
  1856. EXPECT_EQ(StatusCode::OK_200, res->status);
  1857. }
  1858. TEST(UrlWithSpace, Redirect_Online) {
  1859. SSLClient cli("edge.forgecdn.net");
  1860. cli.set_follow_location(true);
  1861. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1862. ASSERT_TRUE(res);
  1863. EXPECT_EQ(StatusCode::OK_200, res->status);
  1864. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1865. }
  1866. #endif
  1867. #if !defined(_WIN32) && !defined(_WIN64)
  1868. TEST(ReceiveSignals, Signal) {
  1869. auto setupSignalHandlers = []() {
  1870. struct sigaction act;
  1871. sigemptyset(&act.sa_mask);
  1872. act.sa_flags = SA_SIGINFO;
  1873. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1874. switch (sig) {
  1875. case SIGINT:
  1876. default: break;
  1877. }
  1878. };
  1879. ::sigaction(SIGINT, &act, nullptr);
  1880. };
  1881. Server svr;
  1882. int port = 0;
  1883. auto thread = std::thread([&]() {
  1884. setupSignalHandlers();
  1885. port = svr.bind_to_any_port(HOST);
  1886. svr.listen_after_bind();
  1887. });
  1888. auto se = detail::scope_exit([&] {
  1889. svr.stop();
  1890. thread.join();
  1891. ASSERT_FALSE(svr.is_running());
  1892. });
  1893. svr.wait_until_ready();
  1894. ASSERT_TRUE(svr.is_running());
  1895. pthread_kill(thread.native_handle(), SIGINT);
  1896. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1897. ASSERT_TRUE(svr.is_running());
  1898. }
  1899. #endif
  1900. TEST(RedirectToDifferentPort, Redirect) {
  1901. Server svr1;
  1902. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1903. res.set_content("Hello World!", "text/plain");
  1904. });
  1905. int svr1_port = 0;
  1906. auto thread1 = std::thread([&]() {
  1907. svr1_port = svr1.bind_to_any_port(HOST);
  1908. svr1.listen_after_bind();
  1909. });
  1910. Server svr2;
  1911. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1912. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1913. });
  1914. int svr2_port = 0;
  1915. auto thread2 = std::thread([&]() {
  1916. svr2_port = svr2.bind_to_any_port(HOST);
  1917. svr2.listen_after_bind();
  1918. });
  1919. auto se = detail::scope_exit([&] {
  1920. svr2.stop();
  1921. thread2.join();
  1922. svr1.stop();
  1923. thread1.join();
  1924. ASSERT_FALSE(svr2.is_running());
  1925. ASSERT_FALSE(svr1.is_running());
  1926. });
  1927. svr1.wait_until_ready();
  1928. svr2.wait_until_ready();
  1929. Client cli("localhost", svr2_port);
  1930. cli.set_follow_location(true);
  1931. auto res = cli.Get("/2");
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(StatusCode::OK_200, res->status);
  1934. EXPECT_EQ("Hello World!", res->body);
  1935. }
  1936. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1937. Server svr;
  1938. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1939. // Port number that overflows int — should not crash
  1940. res.set_redirect("http://localhost:99999999999999999999/target");
  1941. });
  1942. auto port = svr.bind_to_any_port(HOST);
  1943. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1944. auto se = detail::scope_exit([&] {
  1945. svr.stop();
  1946. thread.join();
  1947. ASSERT_FALSE(svr.is_running());
  1948. });
  1949. svr.wait_until_ready();
  1950. Client cli(HOST, port);
  1951. cli.set_follow_location(true);
  1952. auto res = cli.Get("/redir");
  1953. // Should fail gracefully, not crash (no valid response due to bad port)
  1954. EXPECT_FALSE(res);
  1955. }
  1956. TEST(RedirectFromPageWithContent, Redirect) {
  1957. Server svr;
  1958. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1959. res.set_content("___", "text/plain");
  1960. res.set_redirect("/2");
  1961. });
  1962. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1963. res.set_content("Hello World!", "text/plain");
  1964. });
  1965. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1966. auto se = detail::scope_exit([&] {
  1967. svr.stop();
  1968. th.join();
  1969. ASSERT_FALSE(svr.is_running());
  1970. });
  1971. svr.wait_until_ready();
  1972. {
  1973. Client cli("localhost", PORT);
  1974. cli.set_follow_location(true);
  1975. std::string body;
  1976. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1977. body.append(data, data_length);
  1978. return true;
  1979. });
  1980. ASSERT_TRUE(res);
  1981. EXPECT_EQ(StatusCode::OK_200, res->status);
  1982. EXPECT_EQ("Hello World!", body);
  1983. }
  1984. {
  1985. Client cli("localhost", PORT);
  1986. std::string body;
  1987. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1988. body.append(data, data_length);
  1989. return true;
  1990. });
  1991. ASSERT_TRUE(res);
  1992. EXPECT_EQ(StatusCode::Found_302, res->status);
  1993. EXPECT_EQ("___", body);
  1994. }
  1995. }
  1996. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1997. Server svr;
  1998. auto port_str = std::to_string(PORT);
  1999. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2000. auto expected_host = "[::1]:" + port_str;
  2001. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2002. res.set_content("___", "text/plain");
  2003. // res.set_redirect("/2");
  2004. res.set_redirect(redirect_url);
  2005. });
  2006. svr.Get("/2", [&](const Request &req, Response &res) {
  2007. auto host_header = req.headers.find("Host");
  2008. ASSERT_TRUE(host_header != req.headers.end());
  2009. EXPECT_EQ(expected_host, host_header->second);
  2010. res.set_content("Hello World!", "text/plain");
  2011. });
  2012. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2013. auto se = detail::scope_exit([&] {
  2014. svr.stop();
  2015. th.join();
  2016. ASSERT_FALSE(svr.is_running());
  2017. });
  2018. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2019. // actually starts anything, so the condition !svr.is_running() will
  2020. // always remain true, and the loop never stops.
  2021. // This basically counts how many milliseconds have passed since the
  2022. // call to svr.listen(), and if after 5 seconds nothing started yet
  2023. // aborts the test.
  2024. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2025. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2026. ASSERT_LT(milliseconds, 5000U);
  2027. }
  2028. {
  2029. Client cli("::1", PORT);
  2030. cli.set_follow_location(true);
  2031. std::string body;
  2032. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2033. body.append(data, data_length);
  2034. return true;
  2035. });
  2036. ASSERT_TRUE(res);
  2037. EXPECT_EQ(StatusCode::OK_200, res->status);
  2038. EXPECT_EQ("Hello World!", body);
  2039. }
  2040. {
  2041. Client cli("::1", PORT);
  2042. std::string body;
  2043. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2044. body.append(data, data_length);
  2045. return true;
  2046. });
  2047. ASSERT_TRUE(res);
  2048. EXPECT_EQ(StatusCode::Found_302, res->status);
  2049. EXPECT_EQ("___", body);
  2050. }
  2051. }
  2052. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2053. Server svr;
  2054. svr.Get("/foo", [](const Request &req, Response &res) {
  2055. auto a = req.params.find("a");
  2056. if (a != req.params.end()) {
  2057. res.set_content((*a).second, "text/plain");
  2058. res.status = StatusCode::OK_200;
  2059. } else {
  2060. res.status = StatusCode::BadRequest_400;
  2061. }
  2062. });
  2063. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2064. auto se = detail::scope_exit([&] {
  2065. svr.stop();
  2066. thread.join();
  2067. ASSERT_FALSE(svr.is_running());
  2068. });
  2069. svr.wait_until_ready();
  2070. {
  2071. Client cli(HOST, PORT);
  2072. cli.set_path_encode(false);
  2073. auto res = cli.Get("/foo?a=explicitly+encoded");
  2074. ASSERT_TRUE(res);
  2075. EXPECT_EQ(StatusCode::OK_200, res->status);
  2076. // This expects it back with a space, as the `+` won't have been
  2077. // url-encoded, and server-side the params get decoded turning `+`
  2078. // into spaces.
  2079. EXPECT_EQ("explicitly encoded", res->body);
  2080. }
  2081. }
  2082. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2083. Server svr;
  2084. svr.Get("/", [](const Request &req, Response &) {
  2085. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2086. });
  2087. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2088. auto se = detail::scope_exit([&] {
  2089. svr.stop();
  2090. thread.join();
  2091. ASSERT_FALSE(svr.is_running());
  2092. });
  2093. svr.wait_until_ready();
  2094. {
  2095. Client cli(HOST, PORT);
  2096. cli.set_path_encode(false);
  2097. auto res = cli.Get("/?something=%0A");
  2098. ASSERT_TRUE(res);
  2099. EXPECT_EQ(StatusCode::OK_200, res->status);
  2100. }
  2101. }
  2102. TEST(BindServerTest, DISABLED_BindDualStack) {
  2103. Server svr;
  2104. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2105. res.set_content("Hello World!", "text/plain");
  2106. });
  2107. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2108. auto se = detail::scope_exit([&] {
  2109. svr.stop();
  2110. thread.join();
  2111. ASSERT_FALSE(svr.is_running());
  2112. });
  2113. svr.wait_until_ready();
  2114. {
  2115. Client cli("127.0.0.1", PORT);
  2116. auto res = cli.Get("/1");
  2117. ASSERT_TRUE(res);
  2118. EXPECT_EQ(StatusCode::OK_200, res->status);
  2119. EXPECT_EQ("Hello World!", res->body);
  2120. }
  2121. {
  2122. Client cli("::1", PORT);
  2123. auto res = cli.Get("/1");
  2124. ASSERT_TRUE(res);
  2125. EXPECT_EQ(StatusCode::OK_200, res->status);
  2126. EXPECT_EQ("Hello World!", res->body);
  2127. }
  2128. }
  2129. TEST(BindServerTest, BindAndListenSeparately) {
  2130. Server svr;
  2131. int port = svr.bind_to_any_port("0.0.0.0");
  2132. ASSERT_TRUE(svr.is_valid());
  2133. ASSERT_TRUE(port > 0);
  2134. svr.stop();
  2135. }
  2136. #ifdef CPPHTTPLIB_SSL_ENABLED
  2137. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2139. CLIENT_CA_CERT_DIR);
  2140. int port = svr.bind_to_any_port("0.0.0.0");
  2141. ASSERT_TRUE(svr.is_valid());
  2142. ASSERT_TRUE(port > 0);
  2143. svr.stop();
  2144. }
  2145. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2146. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2147. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2148. int port = svr.bind_to_any_port("0.0.0.0");
  2149. ASSERT_TRUE(svr.is_valid());
  2150. ASSERT_TRUE(port > 0);
  2151. svr.stop();
  2152. }
  2153. TEST(BindServerTest, UpdateCertsPem) {
  2154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2155. int port = svr.bind_to_any_port("0.0.0.0");
  2156. ASSERT_TRUE(svr.is_valid());
  2157. ASSERT_TRUE(port > 0);
  2158. // Read PEM files
  2159. std::string cert_pem, key_pem, ca_pem;
  2160. read_file(SERVER_CERT_FILE, cert_pem);
  2161. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2162. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2163. // Update server certificates using PEM API
  2164. ASSERT_TRUE(
  2165. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2166. ASSERT_TRUE(svr.is_valid());
  2167. svr.stop();
  2168. }
  2169. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2170. // Start server with client CA (enables client auth)
  2171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2172. ASSERT_TRUE(svr.is_valid());
  2173. bool handler_called = false;
  2174. svr.Get("/test", [&](const Request &req, Response &res) {
  2175. handler_called = true;
  2176. // Verify client certificate is present
  2177. auto cert = req.peer_cert();
  2178. EXPECT_TRUE(static_cast<bool>(cert));
  2179. res.set_content("ok", "text/plain");
  2180. });
  2181. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2182. auto se = detail::scope_exit([&] {
  2183. svr.stop();
  2184. t.join();
  2185. ASSERT_FALSE(svr.is_running());
  2186. });
  2187. svr.wait_until_ready();
  2188. // Read PEM files
  2189. std::string cert_pem, key_pem, ca_pem;
  2190. read_file(SERVER_CERT_FILE, cert_pem);
  2191. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2192. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2193. // Update server certificates and client CA using PEM API while server running
  2194. ASSERT_TRUE(
  2195. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2196. // Connect with client certificate
  2197. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2198. cli.enable_server_certificate_verification(false);
  2199. cli.set_connection_timeout(30);
  2200. auto res = cli.Get("/test");
  2201. ASSERT_TRUE(res);
  2202. ASSERT_EQ(StatusCode::OK_200, res->status);
  2203. ASSERT_TRUE(handler_called);
  2204. EXPECT_EQ("ok", res->body);
  2205. }
  2206. #endif
  2207. TEST(ErrorHandlerTest, ContentLength) {
  2208. Server svr;
  2209. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2210. res.status = StatusCode::OK_200;
  2211. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2212. "text/html"); // <= Content-Length still 13
  2213. });
  2214. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2215. res.set_content("Hello World!\n", "text/plain");
  2216. res.status = 524;
  2217. });
  2218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2219. auto se = detail::scope_exit([&] {
  2220. svr.stop();
  2221. thread.join();
  2222. ASSERT_FALSE(svr.is_running());
  2223. });
  2224. svr.wait_until_ready();
  2225. {
  2226. Client cli(HOST, PORT);
  2227. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2228. ASSERT_TRUE(res);
  2229. EXPECT_EQ(StatusCode::OK_200, res->status);
  2230. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2231. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2232. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2233. }
  2234. }
  2235. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2236. TEST(ExceptionTest, WithoutExceptionHandler) {
  2237. Server svr;
  2238. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2239. throw std::runtime_error("exception...");
  2240. });
  2241. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2242. throw std::runtime_error("exception\r\n...");
  2243. });
  2244. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2245. auto se = detail::scope_exit([&] {
  2246. svr.stop();
  2247. listen_thread.join();
  2248. ASSERT_FALSE(svr.is_running());
  2249. });
  2250. svr.wait_until_ready();
  2251. Client cli("localhost", PORT);
  2252. {
  2253. auto res = cli.Get("/exception");
  2254. ASSERT_TRUE(res);
  2255. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2256. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2257. }
  2258. {
  2259. auto res = cli.Get("/unknown");
  2260. ASSERT_TRUE(res);
  2261. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2262. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2263. }
  2264. }
  2265. TEST(ExceptionTest, WithExceptionHandler) {
  2266. Server svr;
  2267. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2268. std::exception_ptr ep) {
  2269. EXPECT_FALSE(ep == nullptr);
  2270. try {
  2271. std::rethrow_exception(ep);
  2272. } catch (std::exception &e) {
  2273. EXPECT_EQ("abc", std::string(e.what()));
  2274. } catch (...) {}
  2275. res.status = StatusCode::InternalServerError_500;
  2276. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2277. "text/html"); // <= Content-Length still 13 at this point
  2278. });
  2279. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2280. res.set_content("Hello World!\n", "text/plain");
  2281. throw std::runtime_error("abc");
  2282. });
  2283. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2284. auto se = detail::scope_exit([&] {
  2285. svr.stop();
  2286. thread.join();
  2287. ASSERT_FALSE(svr.is_running());
  2288. });
  2289. svr.wait_until_ready();
  2290. for (size_t i = 0; i < 10; i++) {
  2291. Client cli(HOST, PORT);
  2292. for (size_t j = 0; j < 100; j++) {
  2293. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2294. ASSERT_TRUE(res);
  2295. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2296. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2297. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2298. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2299. }
  2300. cli.set_keep_alive(true);
  2301. for (size_t j = 0; j < 100; j++) {
  2302. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2303. ASSERT_TRUE(res);
  2304. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2305. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2306. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2307. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2308. }
  2309. }
  2310. }
  2311. TEST(ExceptionTest, AndErrorHandler) {
  2312. Server svr;
  2313. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2314. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2315. });
  2316. svr.set_exception_handler(
  2317. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2318. EXPECT_FALSE(ep == nullptr);
  2319. try {
  2320. std::rethrow_exception(ep);
  2321. } catch (std::exception &e) {
  2322. res.set_content(e.what(), "text/html");
  2323. } catch (...) {}
  2324. res.status = StatusCode::InternalServerError_500;
  2325. });
  2326. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2327. throw std::runtime_error("EXCEPTION");
  2328. });
  2329. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2330. res.set_content("ERROR", "text/html");
  2331. res.status = StatusCode::InternalServerError_500;
  2332. });
  2333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2334. auto se = detail::scope_exit([&] {
  2335. svr.stop();
  2336. thread.join();
  2337. ASSERT_FALSE(svr.is_running());
  2338. });
  2339. svr.wait_until_ready();
  2340. Client cli(HOST, PORT);
  2341. {
  2342. auto res = cli.Get("/exception");
  2343. ASSERT_TRUE(res);
  2344. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2345. EXPECT_EQ("EXCEPTION", res->body);
  2346. }
  2347. {
  2348. auto res = cli.Get("/error");
  2349. ASSERT_TRUE(res);
  2350. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2351. EXPECT_EQ("ERROR", res->body);
  2352. }
  2353. {
  2354. auto res = cli.Get("/invalid");
  2355. ASSERT_TRUE(res);
  2356. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2357. EXPECT_EQ("NOT_FOUND", res->body);
  2358. }
  2359. }
  2360. #endif
  2361. TEST(NoContentTest, ContentLength) {
  2362. Server svr;
  2363. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2364. res.status = StatusCode::NoContent_204;
  2365. });
  2366. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2367. auto se = detail::scope_exit([&] {
  2368. svr.stop();
  2369. thread.join();
  2370. ASSERT_FALSE(svr.is_running());
  2371. });
  2372. svr.wait_until_ready();
  2373. {
  2374. Client cli(HOST, PORT);
  2375. auto res = cli.Get("/hi");
  2376. ASSERT_TRUE(res);
  2377. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2378. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2379. }
  2380. }
  2381. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2382. #ifdef CPPHTTPLIB_SSL_ENABLED
  2383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2384. ASSERT_TRUE(svr.is_valid());
  2385. #else
  2386. Server svr;
  2387. #endif
  2388. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2389. if (req.path == "/routing_handler") {
  2390. res.set_header("PRE_ROUTING", "on");
  2391. res.set_content("Routing Handler", "text/plain");
  2392. return httplib::Server::HandlerResponse::Handled;
  2393. }
  2394. return httplib::Server::HandlerResponse::Unhandled;
  2395. });
  2396. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2397. res.set_content("Error", "text/html");
  2398. });
  2399. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2400. if (req.path == "/routing_handler") {
  2401. res.set_header("POST_ROUTING", "on");
  2402. }
  2403. });
  2404. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2405. res.set_content("Hello World!\n", "text/plain");
  2406. });
  2407. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2408. auto se = detail::scope_exit([&] {
  2409. svr.stop();
  2410. thread.join();
  2411. ASSERT_FALSE(svr.is_running());
  2412. });
  2413. svr.wait_until_ready();
  2414. {
  2415. #ifdef CPPHTTPLIB_SSL_ENABLED
  2416. SSLClient cli(HOST, PORT);
  2417. cli.enable_server_certificate_verification(false);
  2418. #else
  2419. Client cli(HOST, PORT);
  2420. #endif
  2421. auto res = cli.Get("/routing_handler");
  2422. ASSERT_TRUE(res);
  2423. EXPECT_EQ(StatusCode::OK_200, res->status);
  2424. EXPECT_EQ("Routing Handler", res->body);
  2425. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2426. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2427. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2428. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2429. }
  2430. {
  2431. #ifdef CPPHTTPLIB_SSL_ENABLED
  2432. SSLClient cli(HOST, PORT);
  2433. cli.enable_server_certificate_verification(false);
  2434. #else
  2435. Client cli(HOST, PORT);
  2436. #endif
  2437. auto res = cli.Get("/hi");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(StatusCode::OK_200, res->status);
  2440. EXPECT_EQ("Hello World!\n", res->body);
  2441. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2442. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2443. }
  2444. {
  2445. #ifdef CPPHTTPLIB_SSL_ENABLED
  2446. SSLClient cli(HOST, PORT);
  2447. cli.enable_server_certificate_verification(false);
  2448. #else
  2449. Client cli(HOST, PORT);
  2450. #endif
  2451. auto res = cli.Get("/aaa");
  2452. ASSERT_TRUE(res);
  2453. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2454. EXPECT_EQ("Error", res->body);
  2455. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2456. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2457. }
  2458. }
  2459. TEST(RequestHandlerTest, PreRequestHandler) {
  2460. auto route_path = "/user/:user";
  2461. Server svr;
  2462. svr.Get("/hi", [](const Request &, Response &res) {
  2463. res.set_content("hi", "text/plain");
  2464. });
  2465. svr.Get(route_path, [](const Request &req, Response &res) {
  2466. res.set_content(req.path_params.at("user"), "text/plain");
  2467. });
  2468. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2469. if (req.matched_route == route_path) {
  2470. auto user = req.path_params.at("user");
  2471. if (user != "john") {
  2472. res.status = StatusCode::Forbidden_403;
  2473. res.set_content("error", "text/html");
  2474. return Server::HandlerResponse::Handled;
  2475. }
  2476. }
  2477. return Server::HandlerResponse::Unhandled;
  2478. });
  2479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2480. auto se = detail::scope_exit([&] {
  2481. svr.stop();
  2482. thread.join();
  2483. ASSERT_FALSE(svr.is_running());
  2484. });
  2485. svr.wait_until_ready();
  2486. Client cli(HOST, PORT);
  2487. {
  2488. auto res = cli.Get("/hi");
  2489. ASSERT_TRUE(res);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. EXPECT_EQ("hi", res->body);
  2492. }
  2493. {
  2494. auto res = cli.Get("/user/john");
  2495. ASSERT_TRUE(res);
  2496. EXPECT_EQ(StatusCode::OK_200, res->status);
  2497. EXPECT_EQ("john", res->body);
  2498. }
  2499. {
  2500. auto res = cli.Get("/user/invalid-user");
  2501. ASSERT_TRUE(res);
  2502. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2503. EXPECT_EQ("error", res->body);
  2504. }
  2505. }
  2506. TEST(AnyTest, BasicOperations) {
  2507. // Default construction
  2508. httplib::any a;
  2509. EXPECT_FALSE(a.has_value());
  2510. // Value construction and any_cast (pointer form, noexcept)
  2511. httplib::any b(42);
  2512. EXPECT_TRUE(b.has_value());
  2513. auto *p = httplib::any_cast<int>(&b);
  2514. ASSERT_NE(nullptr, p);
  2515. EXPECT_EQ(42, *p);
  2516. // Type mismatch → nullptr
  2517. auto *q = httplib::any_cast<std::string>(&b);
  2518. EXPECT_EQ(nullptr, q);
  2519. // any_cast (value form) succeeds
  2520. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2521. // any_cast (value form) throws on type mismatch
  2522. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2523. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2524. #endif
  2525. // Copy
  2526. httplib::any c = b;
  2527. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2528. // Move
  2529. httplib::any d = std::move(c);
  2530. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2531. // Assignment with different type
  2532. b = std::string("hello");
  2533. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2534. // Reset
  2535. b.reset();
  2536. EXPECT_FALSE(b.has_value());
  2537. }
  2538. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2539. struct AuthCtx {
  2540. std::string user_id;
  2541. };
  2542. Server svr;
  2543. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2544. res.user_data["auth"] = AuthCtx{"alice"};
  2545. return Server::HandlerResponse::Unhandled;
  2546. });
  2547. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2548. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2549. ASSERT_NE(nullptr, ctx);
  2550. res.set_content("Hello " + ctx->user_id, "text/plain");
  2551. });
  2552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli(HOST, PORT);
  2560. auto res = cli.Get("/me");
  2561. ASSERT_TRUE(res);
  2562. EXPECT_EQ(StatusCode::OK_200, res->status);
  2563. EXPECT_EQ("Hello alice", res->body);
  2564. }
  2565. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2566. struct RoleCtx {
  2567. std::string role;
  2568. };
  2569. Server svr;
  2570. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2571. res.user_data["role"] = RoleCtx{"admin"};
  2572. return Server::HandlerResponse::Unhandled;
  2573. });
  2574. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2575. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2576. ASSERT_NE(nullptr, ctx);
  2577. res.set_content(ctx->role, "text/plain");
  2578. });
  2579. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2580. auto se = detail::scope_exit([&] {
  2581. svr.stop();
  2582. thread.join();
  2583. ASSERT_FALSE(svr.is_running());
  2584. });
  2585. svr.wait_until_ready();
  2586. Client cli(HOST, PORT);
  2587. auto res = cli.Get("/role");
  2588. ASSERT_TRUE(res);
  2589. EXPECT_EQ(StatusCode::OK_200, res->status);
  2590. EXPECT_EQ("admin", res->body);
  2591. }
  2592. TEST(InvalidFormatTest, StatusCode) {
  2593. Server svr;
  2594. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2595. res.set_content("Hello World!\n", "text/plain");
  2596. res.status = 9999; // Status should be a three-digit code...
  2597. });
  2598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2599. auto se = detail::scope_exit([&] {
  2600. svr.stop();
  2601. thread.join();
  2602. ASSERT_FALSE(svr.is_running());
  2603. });
  2604. svr.wait_until_ready();
  2605. {
  2606. Client cli(HOST, PORT);
  2607. auto res = cli.Get("/hi");
  2608. ASSERT_FALSE(res);
  2609. }
  2610. }
  2611. TEST(URLFragmentTest, WithFragment) {
  2612. Server svr;
  2613. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2614. EXPECT_TRUE(req.target == "/hi");
  2615. });
  2616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2617. auto se = detail::scope_exit([&] {
  2618. svr.stop();
  2619. thread.join();
  2620. ASSERT_FALSE(svr.is_running());
  2621. });
  2622. svr.wait_until_ready();
  2623. {
  2624. Client cli(HOST, PORT);
  2625. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2626. EXPECT_TRUE(res);
  2627. EXPECT_EQ(StatusCode::OK_200, res->status);
  2628. res = cli.Get("/hi%23key1=val1=key2=val2");
  2629. EXPECT_TRUE(res);
  2630. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2631. }
  2632. }
  2633. TEST(HeaderWriter, SetHeaderWriter) {
  2634. Server svr;
  2635. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2636. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2637. return detail::write_headers(strm, hdrs);
  2638. });
  2639. svr.Get("/hi", [](const Request &req, Response &res) {
  2640. auto it = req.headers.find("CustomClientHeader");
  2641. EXPECT_TRUE(it != req.headers.end());
  2642. EXPECT_EQ(it->second, "CustomClientValue");
  2643. res.set_content("Hello World!\n", "text/plain");
  2644. });
  2645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2646. auto se = detail::scope_exit([&] {
  2647. svr.stop();
  2648. thread.join();
  2649. ASSERT_FALSE(svr.is_running());
  2650. });
  2651. svr.wait_until_ready();
  2652. {
  2653. Client cli(HOST, PORT);
  2654. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2655. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2656. return detail::write_headers(strm, hdrs);
  2657. });
  2658. auto res = cli.Get("/hi");
  2659. EXPECT_TRUE(res);
  2660. EXPECT_EQ(StatusCode::OK_200, res->status);
  2661. auto it = res->headers.find("CustomServerHeader");
  2662. EXPECT_TRUE(it != res->headers.end());
  2663. EXPECT_EQ(it->second, "CustomServerValue");
  2664. }
  2665. }
  2666. class ServerTest : public ::testing::Test {
  2667. protected:
  2668. ServerTest()
  2669. : cli_(HOST, PORT)
  2670. #ifdef CPPHTTPLIB_SSL_ENABLED
  2671. ,
  2672. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2673. #endif
  2674. {
  2675. #ifdef CPPHTTPLIB_SSL_ENABLED
  2676. cli_.enable_server_certificate_verification(false);
  2677. #endif
  2678. // Allow LARGE_DATA (100MB) responses
  2679. cli_.set_payload_max_length(200 * 1024 * 1024);
  2680. }
  2681. virtual void SetUp() {
  2682. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2683. svr_.set_payload_max_length(200 * 1024 * 1024);
  2684. svr_.set_mount_point("/", "./www");
  2685. svr_.set_mount_point("/mount", "./www2");
  2686. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2687. svr_.Get("/hi",
  2688. [&](const Request & /*req*/, Response &res) {
  2689. res.set_content("Hello World!", "text/plain");
  2690. })
  2691. .Get("/file_content",
  2692. [&](const Request & /*req*/, Response &res) {
  2693. res.set_file_content("./www/dir/test.html");
  2694. })
  2695. .Get("/file_content_with_content_type",
  2696. [&](const Request & /*req*/, Response &res) {
  2697. res.set_file_content("./www/file", "text/plain");
  2698. })
  2699. .Get("/invalid_file_content",
  2700. [&](const Request & /*req*/, Response &res) {
  2701. res.set_file_content("./www/dir/invalid_file_path");
  2702. })
  2703. .Get("/http_response_splitting",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2706. EXPECT_EQ(0U, res.headers.size());
  2707. EXPECT_FALSE(res.has_header("a"));
  2708. res.set_header("a", "1\nSet-Cookie: a=1");
  2709. EXPECT_EQ(0U, res.headers.size());
  2710. EXPECT_FALSE(res.has_header("a"));
  2711. res.set_header("a", "1\rSet-Cookie: a=1");
  2712. EXPECT_EQ(0U, res.headers.size());
  2713. EXPECT_FALSE(res.has_header("a"));
  2714. res.set_header("a\r\nb", "0");
  2715. EXPECT_EQ(0U, res.headers.size());
  2716. EXPECT_FALSE(res.has_header("a"));
  2717. res.set_header("a\rb", "0");
  2718. EXPECT_EQ(0U, res.headers.size());
  2719. EXPECT_FALSE(res.has_header("a"));
  2720. res.set_header("a\nb", "0");
  2721. EXPECT_EQ(0U, res.headers.size());
  2722. EXPECT_FALSE(res.has_header("a"));
  2723. res.set_redirect("1\r\nSet-Cookie: a=1");
  2724. EXPECT_EQ(0U, res.headers.size());
  2725. EXPECT_FALSE(res.has_header("Location"));
  2726. })
  2727. .Get("/slow",
  2728. [&](const Request & /*req*/, Response &res) {
  2729. std::this_thread::sleep_for(std::chrono::seconds(2));
  2730. res.set_content("slow", "text/plain");
  2731. })
  2732. #if 0
  2733. .Post("/slowpost",
  2734. [&](const Request & /*req*/, Response &res) {
  2735. std::this_thread::sleep_for(std::chrono::seconds(2));
  2736. res.set_content("slow", "text/plain");
  2737. })
  2738. #endif
  2739. .Get("/remote_addr",
  2740. [&](const Request &req, Response &res) {
  2741. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2742. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2743. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2744. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2745. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2746. #endif
  2747. res.set_content(req.remote_addr, "text/plain");
  2748. })
  2749. .Get("/local_addr",
  2750. [&](const Request &req, Response &res) {
  2751. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2752. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2753. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2754. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2755. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2756. #endif
  2757. auto local_addr = req.local_addr;
  2758. auto local_port = std::to_string(req.local_port);
  2759. res.set_content(local_addr.append(":").append(local_port),
  2760. "text/plain");
  2761. })
  2762. .Get("/endwith%",
  2763. [&](const Request & /*req*/, Response &res) {
  2764. res.set_content("Hello World!", "text/plain");
  2765. })
  2766. .Get("/a\\+\\+b",
  2767. [&](const Request &req, Response &res) {
  2768. ASSERT_TRUE(req.has_param("a +b"));
  2769. auto val = req.get_param_value("a +b");
  2770. res.set_content(val, "text/plain");
  2771. })
  2772. .Get("/", [&](const Request & /*req*/,
  2773. Response &res) { res.set_redirect("/hi"); })
  2774. .Post("/1",
  2775. [](const Request & /*req*/, Response &res) {
  2776. res.set_redirect("/2", StatusCode::SeeOther_303);
  2777. })
  2778. .Get("/2",
  2779. [](const Request & /*req*/, Response &res) {
  2780. res.set_content("redirected.", "text/plain");
  2781. res.status = StatusCode::OK_200;
  2782. })
  2783. .Post("/person",
  2784. [&](const Request &req, Response &res) {
  2785. if (req.has_param("name") && req.has_param("note")) {
  2786. persons_[req.get_param_value("name")] =
  2787. req.get_param_value("note");
  2788. } else {
  2789. res.status = StatusCode::BadRequest_400;
  2790. }
  2791. })
  2792. .Put("/person",
  2793. [&](const Request &req, Response &res) {
  2794. if (req.has_param("name") && req.has_param("note")) {
  2795. persons_[req.get_param_value("name")] =
  2796. req.get_param_value("note");
  2797. } else {
  2798. res.status = StatusCode::BadRequest_400;
  2799. }
  2800. })
  2801. .Get("/person/(.*)",
  2802. [&](const Request &req, Response &res) {
  2803. string name = req.matches[1];
  2804. if (persons_.find(name) != persons_.end()) {
  2805. auto note = persons_[name];
  2806. res.set_content(note, "text/plain");
  2807. } else {
  2808. res.status = StatusCode::NotFound_404;
  2809. }
  2810. })
  2811. .Delete("/person",
  2812. [&](const Request &req, Response &res) {
  2813. if (req.has_param("name")) {
  2814. string name = req.get_param_value("name");
  2815. if (persons_.find(name) != persons_.end()) {
  2816. persons_.erase(name);
  2817. res.set_content("DELETED", "text/plain");
  2818. } else {
  2819. res.status = StatusCode::NotFound_404;
  2820. }
  2821. } else {
  2822. res.status = StatusCode::BadRequest_400;
  2823. }
  2824. })
  2825. .Post("/x-www-form-urlencoded-json",
  2826. [&](const Request &req, Response &res) {
  2827. auto json = req.get_param_value("json");
  2828. ASSERT_EQ(JSON_DATA, json);
  2829. res.set_content(json, "appliation/json");
  2830. res.status = StatusCode::OK_200;
  2831. })
  2832. .Get("/streamed-chunked",
  2833. [&](const Request & /*req*/, Response &res) {
  2834. res.set_chunked_content_provider(
  2835. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2836. sink.os << "123";
  2837. sink.os << "456";
  2838. sink.os << "789";
  2839. sink.done();
  2840. return true;
  2841. });
  2842. })
  2843. .Get("/streamed-chunked-with-prohibited-trailer",
  2844. [&](const Request & /*req*/, Response &res) {
  2845. auto i = new int(0);
  2846. // Declare both a prohibited trailer (Content-Length) and an
  2847. // allowed one
  2848. res.set_header("Trailer", "Content-Length, X-Allowed");
  2849. res.set_chunked_content_provider(
  2850. "text/plain",
  2851. [i](size_t /*offset*/, DataSink &sink) {
  2852. switch (*i) {
  2853. case 0: sink.os << "123"; break;
  2854. case 1: sink.os << "456"; break;
  2855. case 2: sink.os << "789"; break;
  2856. case 3: {
  2857. sink.done_with_trailer(
  2858. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2859. } break;
  2860. }
  2861. (*i)++;
  2862. return true;
  2863. },
  2864. [i](bool success) {
  2865. EXPECT_TRUE(success);
  2866. delete i;
  2867. });
  2868. })
  2869. .Get("/streamed-chunked2",
  2870. [&](const Request & /*req*/, Response &res) {
  2871. auto i = new int(0);
  2872. res.set_chunked_content_provider(
  2873. "text/plain",
  2874. [i](size_t /*offset*/, DataSink &sink) {
  2875. switch (*i) {
  2876. case 0: sink.os << "123"; break;
  2877. case 1: sink.os << "456"; break;
  2878. case 2: sink.os << "789"; break;
  2879. case 3: sink.done(); break;
  2880. }
  2881. (*i)++;
  2882. return true;
  2883. },
  2884. [i](bool success) {
  2885. EXPECT_TRUE(success);
  2886. delete i;
  2887. });
  2888. })
  2889. .Get("/streamed-chunked-with-trailer",
  2890. [&](const Request & /*req*/, Response &res) {
  2891. auto i = new int(0);
  2892. res.set_header("Trailer", "Dummy1, Dummy2");
  2893. res.set_chunked_content_provider(
  2894. "text/plain",
  2895. [i](size_t /*offset*/, DataSink &sink) {
  2896. switch (*i) {
  2897. case 0: sink.os << "123"; break;
  2898. case 1: sink.os << "456"; break;
  2899. case 2: sink.os << "789"; break;
  2900. case 3: {
  2901. sink.done_with_trailer(
  2902. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2903. } break;
  2904. }
  2905. (*i)++;
  2906. return true;
  2907. },
  2908. [i](bool success) {
  2909. EXPECT_TRUE(success);
  2910. delete i;
  2911. });
  2912. })
  2913. .Get("/streamed",
  2914. [&](const Request & /*req*/, Response &res) {
  2915. res.set_content_provider(
  2916. 6, "text/plain",
  2917. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2918. sink.os << (offset < 3 ? "a" : "b");
  2919. return true;
  2920. });
  2921. })
  2922. .Get("/streamed-with-range",
  2923. [&](const Request &req, Response &res) {
  2924. auto data = new std::string("abcdefg");
  2925. res.set_content_provider(
  2926. data->size(), "text/plain",
  2927. [data](size_t offset, size_t length, DataSink &sink) {
  2928. size_t DATA_CHUNK_SIZE = 4;
  2929. const auto &d = *data;
  2930. auto out_len =
  2931. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2932. auto ret =
  2933. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2934. EXPECT_TRUE(ret);
  2935. return true;
  2936. },
  2937. [data, &req](bool success) {
  2938. EXPECT_EQ(success, !req.has_param("error"));
  2939. delete data;
  2940. });
  2941. })
  2942. .Get("/streamed-cancel",
  2943. [&](const Request & /*req*/, Response &res) {
  2944. res.set_content_provider(
  2945. size_t(-1), "text/plain",
  2946. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2947. sink.os << "data_chunk";
  2948. return true;
  2949. });
  2950. })
  2951. .Get("/regex-with-delimiter",
  2952. [&](const Request &req, Response & /*res*/) {
  2953. ASSERT_TRUE(req.has_param("key"));
  2954. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2955. })
  2956. .Get("/with-range",
  2957. [&](const Request & /*req*/, Response &res) {
  2958. res.set_content("abcdefg", "text/plain");
  2959. })
  2960. .Get("/test-start-time",
  2961. [&](const Request &req, Response & /*res*/) {
  2962. EXPECT_NE(req.start_time_,
  2963. std::chrono::steady_clock::time_point::min());
  2964. })
  2965. .Get("/with-range-customized-response",
  2966. [&](const Request & /*req*/, Response &res) {
  2967. res.status = StatusCode::BadRequest_400;
  2968. res.set_content(JSON_DATA, "application/json");
  2969. })
  2970. .Post("/chunked",
  2971. [&](const Request &req, Response & /*res*/) {
  2972. EXPECT_EQ(req.body, "dechunked post body");
  2973. })
  2974. .Post("/large-chunked",
  2975. [&](const Request &req, Response & /*res*/) {
  2976. std::string expected(6 * 30 * 1024u, 'a');
  2977. EXPECT_EQ(req.body, expected);
  2978. })
  2979. .Post("/multipart",
  2980. [&](const Request &req, Response & /*res*/) {
  2981. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2982. req.form.get_field_count("text2") +
  2983. req.form.get_field_count("file3") +
  2984. req.form.get_field_count("file4"));
  2985. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2986. req.form.get_file_count("file2"));
  2987. ASSERT_TRUE(!req.form.has_file("???"));
  2988. ASSERT_TRUE(!req.form.has_field("???"));
  2989. ASSERT_TRUE(req.body.empty());
  2990. {
  2991. const auto &text = req.form.get_field("text1");
  2992. EXPECT_EQ("text default", text);
  2993. }
  2994. {
  2995. const auto &text = req.form.get_field("text2");
  2996. EXPECT_EQ("aωb", text);
  2997. }
  2998. {
  2999. const auto &file = req.form.get_file("file1");
  3000. EXPECT_EQ("hello.txt", file.filename);
  3001. EXPECT_EQ("text/plain", file.content_type);
  3002. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3003. }
  3004. {
  3005. const auto &file = req.form.get_file("file2");
  3006. EXPECT_EQ("world.json", file.filename);
  3007. EXPECT_EQ("application/json", file.content_type);
  3008. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3009. }
  3010. {
  3011. const auto &text = req.form.get_field("file3");
  3012. EXPECT_EQ(0u, text.size());
  3013. }
  3014. {
  3015. const auto &text = req.form.get_field("file4");
  3016. EXPECT_EQ(0u, text.size());
  3017. }
  3018. })
  3019. .Post("/multipart/multi_file_values",
  3020. [&](const Request &req, Response & /*res*/) {
  3021. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3022. req.form.get_field_count("multi_text1"));
  3023. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3024. ASSERT_TRUE(!req.form.has_file("???"));
  3025. ASSERT_TRUE(!req.form.has_field("???"));
  3026. ASSERT_TRUE(req.body.empty());
  3027. {
  3028. const auto &text = req.form.get_field("text");
  3029. EXPECT_EQ("default text", text);
  3030. }
  3031. {
  3032. const auto &text1_values = req.form.get_fields("multi_text1");
  3033. EXPECT_EQ(2u, text1_values.size());
  3034. EXPECT_EQ("aaaaa", text1_values[0]);
  3035. EXPECT_EQ("bbbbb", text1_values[1]);
  3036. }
  3037. {
  3038. const auto &file1_values = req.form.get_files("multi_file1");
  3039. EXPECT_EQ(2u, file1_values.size());
  3040. auto file1 = file1_values[0];
  3041. EXPECT_EQ(file1.filename, "hello.txt");
  3042. EXPECT_EQ(file1.content_type, "text/plain");
  3043. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3044. auto file2 = file1_values[1];
  3045. EXPECT_EQ(file2.filename, "world.json");
  3046. EXPECT_EQ(file2.content_type, "application/json");
  3047. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3048. }
  3049. })
  3050. .Post("/empty",
  3051. [&](const Request &req, Response &res) {
  3052. EXPECT_EQ(req.body, "");
  3053. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3054. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3055. res.set_content("empty", "text/plain");
  3056. })
  3057. .Post("/empty-no-content-type",
  3058. [&](const Request &req, Response &res) {
  3059. EXPECT_EQ(req.body, "");
  3060. EXPECT_FALSE(req.has_header("Content-Type"));
  3061. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3062. res.set_content("empty-no-content-type", "text/plain");
  3063. })
  3064. .Post("/path-only",
  3065. [&](const Request &req, Response &res) {
  3066. EXPECT_EQ(req.body, "");
  3067. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3068. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3069. res.set_content("path-only", "text/plain");
  3070. })
  3071. .Post("/path-headers-only",
  3072. [&](const Request &req, Response &res) {
  3073. EXPECT_EQ(req.body, "");
  3074. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3075. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3076. EXPECT_EQ("world", req.get_header_value("hello"));
  3077. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3078. res.set_content("path-headers-only", "text/plain");
  3079. })
  3080. .Post("/post-large",
  3081. [&](const Request &req, Response &res) {
  3082. EXPECT_EQ(req.body, LARGE_DATA);
  3083. res.set_content(req.body, "text/plain");
  3084. })
  3085. .Post("/post-loopback",
  3086. [&](const Request &, Response &res,
  3087. ContentReader const &content_reader) {
  3088. std::string body;
  3089. content_reader([&](const char *data, size_t data_length) {
  3090. body.append(data, data_length);
  3091. return true;
  3092. });
  3093. res.set_content(body, "text/plain");
  3094. })
  3095. .Put("/put-loopback",
  3096. [&](const Request &, Response &res,
  3097. ContentReader const &content_reader) {
  3098. std::string body;
  3099. content_reader([&](const char *data, size_t data_length) {
  3100. body.append(data, data_length);
  3101. return true;
  3102. });
  3103. res.set_content(body, "text/plain");
  3104. })
  3105. .Patch("/patch-loopback",
  3106. [&](const Request &, Response &res,
  3107. ContentReader const &content_reader) {
  3108. std::string body;
  3109. content_reader([&](const char *data, size_t data_length) {
  3110. body.append(data, data_length);
  3111. return true;
  3112. });
  3113. res.set_content(body, "text/plain");
  3114. })
  3115. .Put("/empty-no-content-type",
  3116. [&](const Request &req, Response &res) {
  3117. EXPECT_EQ(req.body, "");
  3118. EXPECT_FALSE(req.has_header("Content-Type"));
  3119. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3120. res.set_content("empty-no-content-type", "text/plain");
  3121. })
  3122. .Put("/put",
  3123. [&](const Request &req, Response &res) {
  3124. EXPECT_EQ(req.body, "PUT");
  3125. res.set_content(req.body, "text/plain");
  3126. })
  3127. .Put("/put-large",
  3128. [&](const Request &req, Response &res) {
  3129. EXPECT_EQ(req.body, LARGE_DATA);
  3130. res.set_content(req.body, "text/plain");
  3131. })
  3132. .Patch("/patch",
  3133. [&](const Request &req, Response &res) {
  3134. EXPECT_EQ(req.body, "PATCH");
  3135. res.set_content(req.body, "text/plain");
  3136. })
  3137. .Delete("/delete",
  3138. [&](const Request & /*req*/, Response &res) {
  3139. res.set_content("DELETE", "text/plain");
  3140. })
  3141. .Delete("/delete-body",
  3142. [&](const Request &req, Response &res) {
  3143. EXPECT_EQ(req.body, "content");
  3144. res.set_content(req.body, "text/plain");
  3145. })
  3146. .Options(R"(\*)",
  3147. [&](const Request & /*req*/, Response &res) {
  3148. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3149. })
  3150. .Get("/request-target",
  3151. [&](const Request &req, Response & /*res*/) {
  3152. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3153. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3154. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3155. })
  3156. .Get("/long-query-value",
  3157. [&](const Request &req, Response & /*res*/) {
  3158. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3159. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3160. })
  3161. .Get("/too-long-query-value",
  3162. [&](const Request &req, Response & /*res*/) {
  3163. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3164. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3165. })
  3166. .Get("/array-param",
  3167. [&](const Request &req, Response & /*res*/) {
  3168. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3169. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3170. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3171. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3172. })
  3173. .Post("/validate-no-multiple-headers",
  3174. [&](const Request &req, Response & /*res*/) {
  3175. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3176. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3177. })
  3178. .Post("/content_receiver",
  3179. [&](const Request &req, Response &res,
  3180. const ContentReader &content_reader) {
  3181. if (req.is_multipart_form_data()) {
  3182. std::vector<FormData> items;
  3183. content_reader(
  3184. [&](const FormData &file) {
  3185. items.push_back(file);
  3186. return true;
  3187. },
  3188. [&](const char *data, size_t data_length) {
  3189. items.back().content.append(data, data_length);
  3190. return true;
  3191. });
  3192. EXPECT_EQ(5u, items.size());
  3193. {
  3194. const auto &file = get_file_value(items, "text1");
  3195. EXPECT_TRUE(file.filename.empty());
  3196. EXPECT_EQ("text default", file.content);
  3197. }
  3198. {
  3199. const auto &file = get_file_value(items, "text2");
  3200. EXPECT_TRUE(file.filename.empty());
  3201. EXPECT_EQ("aωb", file.content);
  3202. }
  3203. {
  3204. const auto &file = get_file_value(items, "file1");
  3205. EXPECT_EQ("hello.txt", file.filename);
  3206. EXPECT_EQ("text/plain", file.content_type);
  3207. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3208. }
  3209. {
  3210. const auto &file = get_file_value(items, "file2");
  3211. EXPECT_EQ("world.json", file.filename);
  3212. EXPECT_EQ("application/json", file.content_type);
  3213. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3214. }
  3215. {
  3216. const auto &file = get_file_value(items, "file3");
  3217. EXPECT_TRUE(file.filename.empty());
  3218. EXPECT_EQ("application/octet-stream", file.content_type);
  3219. EXPECT_EQ(0u, file.content.size());
  3220. }
  3221. } else {
  3222. std::string body;
  3223. content_reader([&](const char *data, size_t data_length) {
  3224. EXPECT_EQ(7U, data_length);
  3225. body.append(data, data_length);
  3226. return true;
  3227. });
  3228. EXPECT_EQ(body, "content");
  3229. res.set_content(body, "text/plain");
  3230. }
  3231. })
  3232. .Put("/content_receiver",
  3233. [&](const Request & /*req*/, Response &res,
  3234. const ContentReader &content_reader) {
  3235. std::string body;
  3236. content_reader([&](const char *data, size_t data_length) {
  3237. body.append(data, data_length);
  3238. return true;
  3239. });
  3240. EXPECT_EQ(body, "content");
  3241. res.set_content(body, "text/plain");
  3242. })
  3243. .Patch("/content_receiver",
  3244. [&](const Request & /*req*/, Response &res,
  3245. const ContentReader &content_reader) {
  3246. std::string body;
  3247. content_reader([&](const char *data, size_t data_length) {
  3248. body.append(data, data_length);
  3249. return true;
  3250. });
  3251. EXPECT_EQ(body, "content");
  3252. res.set_content(body, "text/plain");
  3253. })
  3254. .Post("/query-string-and-body",
  3255. [&](const Request &req, Response & /*res*/) {
  3256. ASSERT_TRUE(req.has_param("key"));
  3257. EXPECT_EQ(req.get_param_value("key"), "value");
  3258. EXPECT_EQ(req.body, "content");
  3259. })
  3260. .Get("/last-request",
  3261. [&](const Request &req, Response & /*res*/) {
  3262. EXPECT_EQ("close", req.get_header_value("Connection"));
  3263. })
  3264. .Get(R"(/redirect/(\d+))",
  3265. [&](const Request &req, Response &res) {
  3266. auto num = std::stoi(req.matches[1]) + 1;
  3267. std::string url = "/redirect/" + std::to_string(num);
  3268. res.set_redirect(url);
  3269. })
  3270. .Post("/binary",
  3271. [&](const Request &req, Response &res) {
  3272. EXPECT_EQ(4U, req.body.size());
  3273. EXPECT_EQ("application/octet-stream",
  3274. req.get_header_value("Content-Type"));
  3275. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3276. res.set_content(req.body, "application/octet-stream");
  3277. })
  3278. .Put("/binary",
  3279. [&](const Request &req, Response &res) {
  3280. EXPECT_EQ(4U, req.body.size());
  3281. EXPECT_EQ("application/octet-stream",
  3282. req.get_header_value("Content-Type"));
  3283. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3284. res.set_content(req.body, "application/octet-stream");
  3285. })
  3286. .Patch("/binary",
  3287. [&](const Request &req, Response &res) {
  3288. EXPECT_EQ(4U, req.body.size());
  3289. EXPECT_EQ("application/octet-stream",
  3290. req.get_header_value("Content-Type"));
  3291. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3292. res.set_content(req.body, "application/octet-stream");
  3293. })
  3294. .Delete("/binary",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(4U, req.body.size());
  3297. EXPECT_EQ("application/octet-stream",
  3298. req.get_header_value("Content-Type"));
  3299. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3300. res.set_content(req.body, "application/octet-stream");
  3301. })
  3302. .Get("/issue1772",
  3303. [&](const Request & /*req*/, Response &res) {
  3304. res.status = 401;
  3305. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3306. })
  3307. .Delete("/issue609",
  3308. [](const httplib::Request &, httplib::Response &res,
  3309. const httplib::ContentReader &) {
  3310. res.set_content("ok", "text/plain");
  3311. })
  3312. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3313. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3314. .Get("/compress",
  3315. [&](const Request & /*req*/, Response &res) {
  3316. res.set_content(
  3317. "12345678901234567890123456789012345678901234567890123456789"
  3318. "01234567890123456789012345678901234567890",
  3319. "text/plain");
  3320. })
  3321. .Get("/compress-with-charset",
  3322. [&](const Request & /*req*/, Response &res) {
  3323. res.set_content(
  3324. "12345678901234567890123456789012345678901234567890123456789"
  3325. "01234567890123456789012345678901234567890",
  3326. "application/json; charset=utf-8");
  3327. })
  3328. .Get("/nocompress",
  3329. [&](const Request & /*req*/, Response &res) {
  3330. res.set_content(
  3331. "12345678901234567890123456789012345678901234567890123456789"
  3332. "01234567890123456789012345678901234567890",
  3333. "application/octet-stream");
  3334. })
  3335. .Post("/compress-multipart",
  3336. [&](const Request &req, Response & /*res*/) {
  3337. EXPECT_EQ(2u, req.form.fields.size());
  3338. ASSERT_TRUE(!req.form.has_field("???"));
  3339. {
  3340. const auto &text = req.form.get_field("key1");
  3341. EXPECT_EQ("test", text);
  3342. }
  3343. {
  3344. const auto &text = req.form.get_field("key2");
  3345. EXPECT_EQ("--abcdefg123", text);
  3346. }
  3347. })
  3348. #endif
  3349. ;
  3350. persons_["john"] = "programmer";
  3351. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3352. svr_.wait_until_ready();
  3353. }
  3354. virtual void TearDown() {
  3355. svr_.stop();
  3356. if (!request_threads_.empty()) {
  3357. std::this_thread::sleep_for(std::chrono::seconds(1));
  3358. for (auto &t : request_threads_) {
  3359. t.join();
  3360. }
  3361. }
  3362. t_.join();
  3363. }
  3364. map<string, string> persons_;
  3365. #ifdef CPPHTTPLIB_SSL_ENABLED
  3366. SSLClient cli_;
  3367. SSLServer svr_;
  3368. #else
  3369. Client cli_;
  3370. Server svr_;
  3371. #endif
  3372. thread t_;
  3373. std::vector<thread> request_threads_;
  3374. };
  3375. TEST_F(ServerTest, GetMethod200) {
  3376. auto res = cli_.Get("/hi");
  3377. ASSERT_TRUE(res);
  3378. EXPECT_EQ("HTTP/1.1", res->version);
  3379. EXPECT_EQ(StatusCode::OK_200, res->status);
  3380. EXPECT_EQ("OK", res->reason);
  3381. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3382. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3383. EXPECT_EQ("Hello World!", res->body);
  3384. }
  3385. TEST_F(ServerTest, GetEmptyFile) {
  3386. auto res = cli_.Get("/empty_file");
  3387. ASSERT_TRUE(res);
  3388. EXPECT_EQ(StatusCode::OK_200, res->status);
  3389. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3390. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3391. EXPECT_EQ("", res->body);
  3392. }
  3393. TEST_F(ServerTest, GetFileContent) {
  3394. auto res = cli_.Get("/file_content");
  3395. ASSERT_TRUE(res);
  3396. EXPECT_EQ(StatusCode::OK_200, res->status);
  3397. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3398. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3399. EXPECT_EQ("test.html", res->body);
  3400. }
  3401. TEST_F(ServerTest, GetFileContentWithRange) {
  3402. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3405. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3406. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3407. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3408. EXPECT_EQ("est", res->body);
  3409. }
  3410. TEST_F(ServerTest, GetFileContentWithContentType) {
  3411. auto res = cli_.Get("/file_content_with_content_type");
  3412. ASSERT_TRUE(res);
  3413. EXPECT_EQ(StatusCode::OK_200, res->status);
  3414. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3415. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3416. EXPECT_EQ("file\n", res->body);
  3417. }
  3418. TEST_F(ServerTest, GetInvalidFileContent) {
  3419. auto res = cli_.Get("/invalid_file_content");
  3420. ASSERT_TRUE(res);
  3421. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3422. }
  3423. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3424. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3425. ASSERT_TRUE(res);
  3426. EXPECT_EQ("HTTP/1.1", res->version);
  3427. EXPECT_EQ(StatusCode::OK_200, res->status);
  3428. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3429. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3430. EXPECT_EQ("Hello World!", res->body);
  3431. }
  3432. TEST_F(ServerTest, GetMethod302) {
  3433. auto res = cli_.Get("/");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::Found_302, res->status);
  3436. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3437. }
  3438. TEST_F(ServerTest, GetMethod302Redirect) {
  3439. cli_.set_follow_location(true);
  3440. auto res = cli_.Get("/");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ(StatusCode::OK_200, res->status);
  3443. EXPECT_EQ("Hello World!", res->body);
  3444. EXPECT_EQ("/hi", res->location);
  3445. }
  3446. TEST_F(ServerTest, GetMethod404) {
  3447. auto res = cli_.Get("/invalid");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3450. }
  3451. TEST_F(ServerTest, HeadMethod200) {
  3452. auto res = cli_.Head("/hi");
  3453. ASSERT_TRUE(res);
  3454. EXPECT_EQ(StatusCode::OK_200, res->status);
  3455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3456. EXPECT_TRUE(res->body.empty());
  3457. }
  3458. TEST_F(ServerTest, HeadMethod200Static) {
  3459. auto res = cli_.Head("/mount/dir/index.html");
  3460. ASSERT_TRUE(res);
  3461. EXPECT_EQ(StatusCode::OK_200, res->status);
  3462. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3463. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3464. EXPECT_TRUE(res->body.empty());
  3465. }
  3466. TEST_F(ServerTest, HeadMethod404) {
  3467. auto res = cli_.Head("/invalid");
  3468. ASSERT_TRUE(res);
  3469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3470. EXPECT_TRUE(res->body.empty());
  3471. }
  3472. TEST_F(ServerTest, GetMethodPersonJohn) {
  3473. auto res = cli_.Get("/person/john");
  3474. ASSERT_TRUE(res);
  3475. EXPECT_EQ(StatusCode::OK_200, res->status);
  3476. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3477. EXPECT_EQ("programmer", res->body);
  3478. }
  3479. TEST_F(ServerTest, PostMethod1) {
  3480. auto res = cli_.Get("/person/john1");
  3481. ASSERT_TRUE(res);
  3482. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3483. res = cli_.Post("/person", "name=john1&note=coder",
  3484. "application/x-www-form-urlencoded");
  3485. ASSERT_TRUE(res);
  3486. ASSERT_EQ(StatusCode::OK_200, res->status);
  3487. res = cli_.Get("/person/john1");
  3488. ASSERT_TRUE(res);
  3489. ASSERT_EQ(StatusCode::OK_200, res->status);
  3490. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3491. ASSERT_EQ("coder", res->body);
  3492. }
  3493. TEST_F(ServerTest, PostMethod2) {
  3494. auto res = cli_.Get("/person/john2");
  3495. ASSERT_TRUE(res);
  3496. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3497. Params params;
  3498. params.emplace("name", "john2");
  3499. params.emplace("note", "coder");
  3500. res = cli_.Post("/person", params);
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. res = cli_.Get("/person/john2");
  3504. ASSERT_TRUE(res);
  3505. ASSERT_EQ(StatusCode::OK_200, res->status);
  3506. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3507. ASSERT_EQ("coder", res->body);
  3508. }
  3509. TEST_F(ServerTest, PutMethod3) {
  3510. auto res = cli_.Get("/person/john3");
  3511. ASSERT_TRUE(res);
  3512. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3513. Params params;
  3514. params.emplace("name", "john3");
  3515. params.emplace("note", "coder");
  3516. res = cli_.Put("/person", params);
  3517. ASSERT_TRUE(res);
  3518. ASSERT_EQ(StatusCode::OK_200, res->status);
  3519. res = cli_.Get("/person/john3");
  3520. ASSERT_TRUE(res);
  3521. ASSERT_EQ(StatusCode::OK_200, res->status);
  3522. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3523. ASSERT_EQ("coder", res->body);
  3524. }
  3525. TEST_F(ServerTest, DeleteMethod1) {
  3526. auto res = cli_.Get("/person/john4");
  3527. ASSERT_TRUE(res);
  3528. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3529. Params params;
  3530. params.emplace("name", "john4");
  3531. params.emplace("note", "coder");
  3532. res = cli_.Post("/person", params);
  3533. ASSERT_TRUE(res);
  3534. ASSERT_EQ(StatusCode::OK_200, res->status);
  3535. res = cli_.Get("/person/john4");
  3536. ASSERT_TRUE(res);
  3537. ASSERT_EQ(StatusCode::OK_200, res->status);
  3538. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3539. ASSERT_EQ("coder", res->body);
  3540. Params delete_params;
  3541. delete_params.emplace("name", "john4");
  3542. res = cli_.Delete("/person", delete_params);
  3543. ASSERT_TRUE(res);
  3544. ASSERT_EQ(StatusCode::OK_200, res->status);
  3545. ASSERT_EQ("DELETED", res->body);
  3546. res = cli_.Get("/person/john4");
  3547. ASSERT_TRUE(res);
  3548. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3549. }
  3550. TEST_F(ServerTest, DeleteMethod2) {
  3551. auto res = cli_.Get("/person/john5");
  3552. ASSERT_TRUE(res);
  3553. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3554. Params params;
  3555. params.emplace("name", "john5");
  3556. params.emplace("note", "developer");
  3557. res = cli_.Post("/person", params);
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::OK_200, res->status);
  3560. res = cli_.Get("/person/john5");
  3561. ASSERT_TRUE(res);
  3562. ASSERT_EQ(StatusCode::OK_200, res->status);
  3563. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3564. ASSERT_EQ("developer", res->body);
  3565. Params delete_params;
  3566. delete_params.emplace("name", "john5");
  3567. Headers headers;
  3568. headers.emplace("Custom-Header", "test-value");
  3569. res = cli_.Delete("/person", headers, delete_params);
  3570. ASSERT_TRUE(res);
  3571. ASSERT_EQ(StatusCode::OK_200, res->status);
  3572. ASSERT_EQ("DELETED", res->body);
  3573. res = cli_.Get("/person/john5");
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3576. }
  3577. TEST_F(ServerTest, DeleteMethod3) {
  3578. auto res = cli_.Get("/person/john6");
  3579. ASSERT_TRUE(res);
  3580. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3581. Params params;
  3582. params.emplace("name", "john6");
  3583. params.emplace("note", "tester");
  3584. res = cli_.Post("/person", params);
  3585. ASSERT_TRUE(res);
  3586. ASSERT_EQ(StatusCode::OK_200, res->status);
  3587. res = cli_.Get("/person/john6");
  3588. ASSERT_TRUE(res);
  3589. ASSERT_EQ(StatusCode::OK_200, res->status);
  3590. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3591. ASSERT_EQ("tester", res->body);
  3592. Params delete_params;
  3593. delete_params.emplace("name", "john6");
  3594. Headers headers;
  3595. headers.emplace("Custom-Header", "test-value");
  3596. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3597. ASSERT_TRUE(res);
  3598. ASSERT_EQ(StatusCode::OK_200, res->status);
  3599. ASSERT_EQ("DELETED", res->body);
  3600. res = cli_.Get("/person/john6");
  3601. ASSERT_TRUE(res);
  3602. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3603. }
  3604. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3605. Params params;
  3606. params.emplace("json", JSON_DATA);
  3607. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3608. ASSERT_TRUE(res);
  3609. ASSERT_EQ(StatusCode::OK_200, res->status);
  3610. ASSERT_EQ(JSON_DATA, res->body);
  3611. }
  3612. TEST_F(ServerTest, PostEmptyContent) {
  3613. auto res = cli_.Post("/empty", "", "text/plain");
  3614. ASSERT_TRUE(res);
  3615. ASSERT_EQ(StatusCode::OK_200, res->status);
  3616. ASSERT_EQ("empty", res->body);
  3617. }
  3618. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3619. auto res = cli_.Post("/empty-no-content-type");
  3620. ASSERT_TRUE(res);
  3621. ASSERT_EQ(StatusCode::OK_200, res->status);
  3622. ASSERT_EQ("empty-no-content-type", res->body);
  3623. }
  3624. TEST_F(ServerTest, PostPathOnly) {
  3625. auto res = cli_.Post("/path-only");
  3626. ASSERT_TRUE(res);
  3627. ASSERT_EQ(StatusCode::OK_200, res->status);
  3628. ASSERT_EQ("path-only", res->body);
  3629. }
  3630. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3631. auto res = cli_.Post("/path-headers-only",
  3632. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3633. ASSERT_TRUE(res);
  3634. ASSERT_EQ(StatusCode::OK_200, res->status);
  3635. ASSERT_EQ("path-headers-only", res->body);
  3636. }
  3637. TEST_F(ServerTest, PostLarge) {
  3638. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3639. ASSERT_TRUE(res);
  3640. ASSERT_EQ(StatusCode::OK_200, res->status);
  3641. EXPECT_EQ(LARGE_DATA, res->body);
  3642. }
  3643. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3644. auto res = cli_.Put("/empty-no-content-type");
  3645. ASSERT_TRUE(res);
  3646. ASSERT_EQ(StatusCode::OK_200, res->status);
  3647. ASSERT_EQ("empty-no-content-type", res->body);
  3648. }
  3649. TEST_F(ServerTest, GetMethodDir) {
  3650. auto res = cli_.Get("/dir/");
  3651. ASSERT_TRUE(res);
  3652. EXPECT_EQ(StatusCode::OK_200, res->status);
  3653. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3654. auto body = R"(<html>
  3655. <head>
  3656. </head>
  3657. <body>
  3658. <a href="/dir/test.html">Test</a>
  3659. <a href="/hi">hi</a>
  3660. </body>
  3661. </html>
  3662. )";
  3663. EXPECT_EQ(body, res->body);
  3664. }
  3665. TEST_F(ServerTest, GetMethodDirTest) {
  3666. auto res = cli_.Get("/dir/test.html");
  3667. ASSERT_TRUE(res);
  3668. EXPECT_EQ(StatusCode::OK_200, res->status);
  3669. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3670. EXPECT_EQ("test.html", res->body);
  3671. }
  3672. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3673. auto res = cli_.Get("/dir/../dir/test.html");
  3674. ASSERT_TRUE(res);
  3675. EXPECT_EQ(StatusCode::OK_200, res->status);
  3676. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3677. EXPECT_EQ("test.html", res->body);
  3678. }
  3679. TEST_F(ServerTest, GetMethodInvalidPath) {
  3680. auto res = cli_.Get("/dir/../test.html");
  3681. ASSERT_TRUE(res);
  3682. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3683. }
  3684. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3685. auto res = cli_.Get("/../www/dir/test.html");
  3686. ASSERT_TRUE(res);
  3687. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3688. }
  3689. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3690. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3691. ASSERT_TRUE(res);
  3692. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3693. }
  3694. TEST_F(ServerTest, GetMethodDirMountTest) {
  3695. auto res = cli_.Get("/mount/dir/test.html");
  3696. ASSERT_TRUE(res);
  3697. EXPECT_EQ(StatusCode::OK_200, res->status);
  3698. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3699. EXPECT_EQ("test.html", res->body);
  3700. }
  3701. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3702. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3703. ASSERT_TRUE(res);
  3704. EXPECT_EQ(StatusCode::OK_200, res->status);
  3705. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3706. EXPECT_EQ("test.html", res->body);
  3707. }
  3708. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3709. auto res = cli_.Get("/mount/dir/../test.html");
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3712. }
  3713. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3714. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3715. ASSERT_TRUE(res);
  3716. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3717. }
  3718. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3719. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3720. ASSERT_TRUE(res);
  3721. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3722. }
  3723. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3724. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3725. ASSERT_TRUE(res);
  3726. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3727. }
  3728. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3729. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3732. }
  3733. TEST_F(ServerTest, PostMethod303) {
  3734. auto res = cli_.Post("/1", "body", "text/plain");
  3735. ASSERT_TRUE(res);
  3736. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3737. EXPECT_EQ("/2", res->get_header_value("Location"));
  3738. }
  3739. TEST_F(ServerTest, PostMethod303Redirect) {
  3740. cli_.set_follow_location(true);
  3741. auto res = cli_.Post("/1", "body", "text/plain");
  3742. ASSERT_TRUE(res);
  3743. EXPECT_EQ(StatusCode::OK_200, res->status);
  3744. EXPECT_EQ("redirected.", res->body);
  3745. EXPECT_EQ("/2", res->location);
  3746. }
  3747. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3748. auto res = cli_.Get("/dir/test.abcde");
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::OK_200, res->status);
  3751. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3752. EXPECT_EQ("abcde", res->body);
  3753. }
  3754. TEST_F(ServerTest, StaticFileRange) {
  3755. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3756. ASSERT_TRUE(res);
  3757. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3758. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3759. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3760. EXPECT_EQ(true, res->has_header("Content-Range"));
  3761. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3762. EXPECT_EQ(std::string("cd"), res->body);
  3763. }
  3764. TEST_F(ServerTest, StaticFileRanges) {
  3765. auto res =
  3766. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3767. ASSERT_TRUE(res);
  3768. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3769. EXPECT_TRUE(
  3770. res->get_header_value("Content-Type")
  3771. .find(
  3772. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3773. 0);
  3774. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3775. }
  3776. TEST_F(ServerTest, StaticFileRangeHead) {
  3777. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3778. ASSERT_TRUE(res);
  3779. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3780. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3781. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3782. EXPECT_EQ(true, res->has_header("Content-Range"));
  3783. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3784. }
  3785. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3786. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3787. ASSERT_TRUE(res);
  3788. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3789. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3790. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3791. EXPECT_EQ(true, res->has_header("Content-Range"));
  3792. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3793. res->get_header_value("Content-Range"));
  3794. EXPECT_EQ("LAST\n", res->body);
  3795. }
  3796. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3797. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3798. ASSERT_TRUE(res);
  3799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3800. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3801. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3802. EXPECT_EQ(true, res->has_header("Content-Range"));
  3803. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3804. }
  3805. TEST_F(ServerTest, StaticFileBigFile) {
  3806. auto res = cli_.Get("/dir/1MB.txt");
  3807. ASSERT_TRUE(res);
  3808. EXPECT_EQ(StatusCode::OK_200, res->status);
  3809. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3810. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3811. }
  3812. TEST_F(ServerTest, InvalidBaseDirMount) {
  3813. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3814. }
  3815. TEST_F(ServerTest, Binary) {
  3816. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3817. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3818. "application/octet-stream");
  3819. ASSERT_TRUE(res);
  3820. ASSERT_EQ(StatusCode::OK_200, res->status);
  3821. ASSERT_EQ(4U, res->body.size());
  3822. res = cli_.Put("/binary", binary.data(), binary.size(),
  3823. "application/octet-stream");
  3824. ASSERT_TRUE(res);
  3825. ASSERT_EQ(StatusCode::OK_200, res->status);
  3826. ASSERT_EQ(4U, res->body.size());
  3827. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3828. "application/octet-stream");
  3829. ASSERT_TRUE(res);
  3830. ASSERT_EQ(StatusCode::OK_200, res->status);
  3831. ASSERT_EQ(4U, res->body.size());
  3832. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3833. "application/octet-stream");
  3834. ASSERT_TRUE(res);
  3835. ASSERT_EQ(StatusCode::OK_200, res->status);
  3836. ASSERT_EQ(4U, res->body.size());
  3837. }
  3838. TEST_F(ServerTest, BinaryString) {
  3839. auto binary = std::string("\x00\x01\x02\x03", 4);
  3840. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3841. ASSERT_TRUE(res);
  3842. ASSERT_EQ(StatusCode::OK_200, res->status);
  3843. ASSERT_EQ(4U, res->body.size());
  3844. res = cli_.Put("/binary", binary, "application/octet-stream");
  3845. ASSERT_TRUE(res);
  3846. ASSERT_EQ(StatusCode::OK_200, res->status);
  3847. ASSERT_EQ(4U, res->body.size());
  3848. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3849. ASSERT_TRUE(res);
  3850. ASSERT_EQ(StatusCode::OK_200, res->status);
  3851. ASSERT_EQ(4U, res->body.size());
  3852. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3853. ASSERT_TRUE(res);
  3854. ASSERT_EQ(StatusCode::OK_200, res->status);
  3855. ASSERT_EQ(4U, res->body.size());
  3856. }
  3857. TEST_F(ServerTest, EmptyRequest) {
  3858. auto res = cli_.Get("");
  3859. ASSERT_TRUE(!res);
  3860. EXPECT_EQ(Error::Connection, res.error());
  3861. }
  3862. TEST_F(ServerTest, LongRequest) {
  3863. std::string request;
  3864. for (size_t i = 0; i < 545; i++) {
  3865. request += "/TooLongRequest";
  3866. }
  3867. request += "OK";
  3868. auto res = cli_.Get(request.c_str());
  3869. ASSERT_TRUE(res);
  3870. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3871. }
  3872. TEST_F(ServerTest, TooLongRequest) {
  3873. std::string request;
  3874. for (size_t i = 0; i < 546; i++) {
  3875. request += "/TooLongRequest";
  3876. }
  3877. request += "_NG";
  3878. auto start = std::chrono::high_resolution_clock::now();
  3879. cli_.set_keep_alive(true);
  3880. auto res = cli_.Get(request.c_str());
  3881. auto end = std::chrono::high_resolution_clock::now();
  3882. auto elapsed =
  3883. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3884. .count();
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3887. EXPECT_LE(elapsed, 1000);
  3888. EXPECT_EQ("close", res->get_header_value("Connection"));
  3889. EXPECT_FALSE(cli_.is_socket_open());
  3890. }
  3891. TEST_F(ServerTest, AlmostTooLongRequest) {
  3892. // test for #2046 - URI length check shouldn't include other content on req
  3893. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3894. // leading /, space, HTTP/1.1)
  3895. std::string request =
  3896. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3897. auto res = cli_.Get(request.c_str());
  3898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3900. }
  3901. TEST_F(ServerTest, LongHeader) {
  3902. Request req;
  3903. req.method = "GET";
  3904. req.path = "/hi";
  3905. std::string host_and_port;
  3906. host_and_port += HOST;
  3907. host_and_port += ":";
  3908. host_and_port += std::to_string(PORT);
  3909. req.headers.emplace("Host", host_and_port.c_str());
  3910. req.headers.emplace("Accept", "*/*");
  3911. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3912. req.headers.emplace(
  3913. "Header-Name",
  3914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@");
  3943. auto res = std::make_shared<Response>();
  3944. auto error = Error::Success;
  3945. auto ret = cli_.send(req, *res, error);
  3946. ASSERT_TRUE(ret);
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. }
  3949. TEST_F(ServerTest, LongQueryValue) {
  3950. auto start = std::chrono::high_resolution_clock::now();
  3951. cli_.set_keep_alive(true);
  3952. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3953. auto end = std::chrono::high_resolution_clock::now();
  3954. auto elapsed =
  3955. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3956. .count();
  3957. ASSERT_TRUE(res);
  3958. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3959. EXPECT_LE(elapsed, 1000);
  3960. EXPECT_EQ("close", res->get_header_value("Connection"));
  3961. EXPECT_FALSE(cli_.is_socket_open());
  3962. }
  3963. TEST_F(ServerTest, TooLongQueryValue) {
  3964. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3965. ASSERT_FALSE(res);
  3966. EXPECT_EQ(Error::Read, res.error());
  3967. }
  3968. TEST_F(ServerTest, TooLongHeader) {
  3969. Request req;
  3970. req.method = "GET";
  3971. req.path = "/hi";
  3972. std::string host_and_port;
  3973. host_and_port += HOST;
  3974. host_and_port += ":";
  3975. host_and_port += std::to_string(PORT);
  3976. req.headers.emplace("Host", host_and_port.c_str());
  3977. req.headers.emplace("Accept", "*/*");
  3978. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3979. req.headers.emplace(
  3980. "Header-Name",
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4009. "@@@@@@@@@@@@@@@@@");
  4010. auto res = std::make_shared<Response>();
  4011. auto error = Error::Success;
  4012. auto ret = cli_.send(req, *res, error);
  4013. ASSERT_TRUE(ret);
  4014. EXPECT_EQ(StatusCode::OK_200, res->status);
  4015. }
  4016. TEST_F(ServerTest, HeaderCountAtLimit) {
  4017. // Test with headers just under the 100 limit
  4018. httplib::Headers headers;
  4019. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4020. // This should keep us just under the 100 header limit
  4021. for (int i = 0; i < 95; i++) {
  4022. std::string name = "X-Test-Header-" + std::to_string(i);
  4023. std::string value = "value" + std::to_string(i);
  4024. headers.emplace(name, value);
  4025. }
  4026. // This should work fine as we're under the limit
  4027. auto res = cli_.Get("/hi", headers);
  4028. EXPECT_TRUE(res);
  4029. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4030. }
  4031. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4032. // Test with many headers to exceed the 100 limit
  4033. httplib::Headers headers;
  4034. // Add 150 headers to definitely exceed the 100 limit
  4035. for (int i = 0; i < 150; i++) {
  4036. std::string name = "X-Test-Header-" + std::to_string(i);
  4037. std::string value = "value" + std::to_string(i);
  4038. headers.emplace(name, value);
  4039. }
  4040. // This should fail due to exceeding header count limit
  4041. cli_.set_keep_alive(true);
  4042. auto res = cli_.Get("/hi", headers);
  4043. // The server should respond with 400 Bad Request
  4044. ASSERT_TRUE(res);
  4045. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4046. EXPECT_EQ("close", res->get_header_value("Connection"));
  4047. EXPECT_FALSE(cli_.is_socket_open());
  4048. }
  4049. TEST_F(ServerTest, PercentEncoding) {
  4050. auto res = cli_.Get("/e%6edwith%");
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::OK_200, res->status);
  4053. }
  4054. TEST_F(ServerTest, PercentEncodingUnicode) {
  4055. auto res = cli_.Get("/e%u006edwith%");
  4056. ASSERT_TRUE(res);
  4057. EXPECT_EQ(StatusCode::OK_200, res->status);
  4058. }
  4059. TEST_F(ServerTest, InvalidPercentEncoding) {
  4060. auto res = cli_.Get("/%endwith%");
  4061. ASSERT_TRUE(res);
  4062. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4063. }
  4064. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4065. auto res = cli_.Get("/%uendwith%");
  4066. ASSERT_TRUE(res);
  4067. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4068. }
  4069. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4070. auto res = cli_.Get("/hello?aaa=bbb%");
  4071. ASSERT_TRUE(res);
  4072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4073. }
  4074. TEST_F(ServerTest, PlusSignEncoding) {
  4075. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::OK_200, res->status);
  4078. EXPECT_EQ("a +b", res->body);
  4079. }
  4080. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4081. // This test simulates a potential DoS attack using many headers
  4082. // to verify our security fix prevents memory exhaustion
  4083. httplib::Headers attack_headers;
  4084. // Attempt to add many headers like an attacker would (200 headers to far
  4085. // exceed limit)
  4086. for (int i = 0; i < 200; i++) {
  4087. std::string name = "X-Attack-Header-" + std::to_string(i);
  4088. std::string value = "attack_payload_" + std::to_string(i);
  4089. attack_headers.emplace(name, value);
  4090. }
  4091. // Try to POST with excessive headers
  4092. cli_.set_keep_alive(true);
  4093. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4094. // Should either fail or return 400 Bad Request due to security limit
  4095. if (res) {
  4096. // If we get a response, it should be 400 Bad Request
  4097. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4098. EXPECT_EQ("close", res->get_header_value("Connection"));
  4099. }
  4100. EXPECT_FALSE(cli_.is_socket_open());
  4101. }
  4102. TEST_F(ServerTest, MultipartFormData) {
  4103. UploadFormDataItems items = {
  4104. {"text1", "text default", "", ""},
  4105. {"text2", "aωb", "", ""},
  4106. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4107. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4108. {"file3", "", "", "application/octet-stream"},
  4109. {"file4", "", "", " application/json tmp-string "}};
  4110. auto res = cli_.Post("/multipart", items);
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::OK_200, res->status);
  4113. }
  4114. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4115. UploadFormDataItems items = {
  4116. {"text", "default text", "", ""},
  4117. {"multi_text1", "aaaaa", "", ""},
  4118. {"multi_text1", "bbbbb", "", ""},
  4119. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4120. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4121. "application/json"},
  4122. };
  4123. auto res = cli_.Post("/multipart/multi_file_values", items);
  4124. ASSERT_TRUE(res);
  4125. EXPECT_EQ(StatusCode::OK_200, res->status);
  4126. }
  4127. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4128. auto res = cli_.Get("/hi");
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::OK_200, res->status);
  4131. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4132. EXPECT_EQ("Hello World!", res->body);
  4133. }
  4134. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4135. Request req;
  4136. req.method = "POST";
  4137. req.path = "/chunked";
  4138. std::string host_and_port;
  4139. host_and_port += HOST;
  4140. host_and_port += ":";
  4141. host_and_port += std::to_string(PORT);
  4142. req.headers.emplace("Host", host_and_port.c_str());
  4143. req.headers.emplace("Accept", "*/*");
  4144. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4145. req.headers.emplace("Content-Type", "text/plain");
  4146. req.headers.emplace("Content-Length", "0");
  4147. req.headers.emplace(
  4148. "Transfer-Encoding",
  4149. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4150. // Client does not chunk, so make a chunked body manually.
  4151. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4152. auto res = std::make_shared<Response>();
  4153. auto error = Error::Success;
  4154. auto ret = cli_.send(req, *res, error);
  4155. ASSERT_TRUE(ret);
  4156. EXPECT_EQ(StatusCode::OK_200, res->status);
  4157. }
  4158. TEST_F(ServerTest, GetStreamed2) {
  4159. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4160. ASSERT_TRUE(res);
  4161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4162. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4163. EXPECT_EQ(true, res->has_header("Content-Range"));
  4164. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4165. EXPECT_EQ(std::string("ab"), res->body);
  4166. }
  4167. TEST_F(ServerTest, GetStreamed) {
  4168. auto res = cli_.Get("/streamed");
  4169. ASSERT_TRUE(res);
  4170. EXPECT_EQ(StatusCode::OK_200, res->status);
  4171. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4172. EXPECT_EQ(std::string("aaabbb"), res->body);
  4173. }
  4174. TEST_F(ServerTest, GetStreamedWithRange1) {
  4175. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4178. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4179. EXPECT_EQ(true, res->has_header("Content-Range"));
  4180. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4181. EXPECT_EQ(std::string("def"), res->body);
  4182. }
  4183. TEST_F(ServerTest, GetStreamedWithRange2) {
  4184. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4185. ASSERT_TRUE(res);
  4186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4187. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4188. EXPECT_EQ(true, res->has_header("Content-Range"));
  4189. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4190. EXPECT_EQ(std::string("bcdefg"), res->body);
  4191. }
  4192. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4193. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4194. ASSERT_TRUE(res);
  4195. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4196. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4197. EXPECT_EQ(true, res->has_header("Content-Range"));
  4198. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4199. EXPECT_EQ(std::string("efg"), res->body);
  4200. }
  4201. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4202. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4203. ASSERT_TRUE(res);
  4204. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4205. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4206. EXPECT_EQ(false, res->has_header("Content-Range"));
  4207. EXPECT_EQ(0U, res->body.size());
  4208. }
  4209. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4210. auto res = cli_.Get("/streamed-with-range",
  4211. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4212. "92233720368547758079223372036854775807"}});
  4213. ASSERT_TRUE(res);
  4214. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4215. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4216. EXPECT_EQ(false, res->has_header("Content-Range"));
  4217. EXPECT_EQ(0U, res->body.size());
  4218. }
  4219. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4220. auto res = cli_.Get(
  4221. "/with-range",
  4222. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4223. {"Accept-Encoding", ""}});
  4224. ASSERT_TRUE(res);
  4225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4226. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4227. EXPECT_EQ(true, res->has_header("Content-Range"));
  4228. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4229. EXPECT_EQ(std::string("abcdefg"), res->body);
  4230. }
  4231. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4232. auto res = cli_.Get("/with-range", {
  4233. {"Range", "bytes=0-"},
  4234. {"Accept-Encoding", ""},
  4235. });
  4236. ASSERT_TRUE(res);
  4237. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4238. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4239. EXPECT_EQ(true, res->has_header("Content-Range"));
  4240. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4241. EXPECT_EQ(std::string("abcdefg"), res->body);
  4242. }
  4243. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4244. auto res =
  4245. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4246. ASSERT_TRUE(res);
  4247. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4248. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4249. EXPECT_EQ(false, res->has_header("Content-Range"));
  4250. EXPECT_EQ(267U, res->body.size());
  4251. // Check that both range contents are present
  4252. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4253. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4254. // Check that Content-Range headers are present for both ranges
  4255. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4256. std::string::npos);
  4257. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4258. std::string::npos);
  4259. }
  4260. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4261. Ranges ranges;
  4262. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4263. ranges.emplace_back(0, -1);
  4264. }
  4265. auto res =
  4266. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4269. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4270. EXPECT_EQ(false, res->has_header("Content-Range"));
  4271. EXPECT_EQ(0U, res->body.size());
  4272. }
  4273. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4274. auto res =
  4275. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4276. ASSERT_TRUE(res);
  4277. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4278. EXPECT_EQ(5U, res->body.size());
  4279. // Check that overlapping ranges are coalesced into a single range
  4280. EXPECT_EQ("bcdef", res->body);
  4281. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4282. // Should be single range, not multipart
  4283. EXPECT_TRUE(res->has_header("Content-Range"));
  4284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4285. }
  4286. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4287. auto res =
  4288. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4291. EXPECT_EQ(268U, res->body.size());
  4292. // Check that both range contents are present
  4293. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4294. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4295. // Check that Content-Range headers are present for both ranges
  4296. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4297. std::string::npos);
  4298. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4299. std::string::npos);
  4300. }
  4301. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4302. auto res =
  4303. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4304. ASSERT_TRUE(res);
  4305. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4306. EXPECT_EQ(269U, res->body.size());
  4307. // Check that both duplicate range contents are present
  4308. size_t first_abc = res->body.find("abc\r\n");
  4309. EXPECT_TRUE(first_abc != std::string::npos);
  4310. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4311. EXPECT_TRUE(second_abc != std::string::npos);
  4312. // Check that Content-Range headers are present for both ranges
  4313. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4314. EXPECT_TRUE(first_range != std::string::npos);
  4315. size_t second_range =
  4316. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4317. EXPECT_TRUE(second_range != std::string::npos);
  4318. }
  4319. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4320. auto res = cli_.Get("/streamed-with-range?error",
  4321. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4322. ASSERT_TRUE(res);
  4323. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4324. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4325. EXPECT_EQ(false, res->has_header("Content-Range"));
  4326. EXPECT_EQ(0U, res->body.size());
  4327. }
  4328. TEST_F(ServerTest, GetStreamedEndless) {
  4329. uint64_t offset = 0;
  4330. auto res = cli_.Get("/streamed-cancel",
  4331. [&](const char * /*data*/, uint64_t data_length) {
  4332. if (offset < 100) {
  4333. offset += data_length;
  4334. return true;
  4335. }
  4336. return false;
  4337. });
  4338. ASSERT_TRUE(!res);
  4339. EXPECT_EQ(Error::Canceled, res.error());
  4340. }
  4341. TEST_F(ServerTest, ClientStop) {
  4342. std::atomic_size_t count{4};
  4343. std::vector<std::thread> threads;
  4344. for (auto i = count.load(); i != 0; --i) {
  4345. threads.emplace_back([&]() {
  4346. auto res = cli_.Get("/streamed-cancel",
  4347. [&](const char *, uint64_t) { return true; });
  4348. --count;
  4349. ASSERT_TRUE(!res);
  4350. EXPECT_TRUE(res.error() == Error::Canceled ||
  4351. res.error() == Error::Read || res.error() == Error::Write);
  4352. });
  4353. }
  4354. std::this_thread::sleep_for(std::chrono::seconds(2));
  4355. while (count != 0) {
  4356. cli_.stop();
  4357. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4358. }
  4359. for (auto &t : threads) {
  4360. t.join();
  4361. }
  4362. }
  4363. TEST_F(ServerTest, GetWithRange1) {
  4364. auto res = cli_.Get("/with-range", {
  4365. make_range_header({{3, 5}}),
  4366. {"Accept-Encoding", ""},
  4367. });
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4370. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4371. EXPECT_EQ(true, res->has_header("Content-Range"));
  4372. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4373. EXPECT_EQ(std::string("def"), res->body);
  4374. }
  4375. TEST_F(ServerTest, GetWithRange2) {
  4376. auto res = cli_.Get("/with-range", {
  4377. make_range_header({{1, -1}}),
  4378. {"Accept-Encoding", ""},
  4379. });
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4382. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4383. EXPECT_EQ(true, res->has_header("Content-Range"));
  4384. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4385. EXPECT_EQ(std::string("bcdefg"), res->body);
  4386. }
  4387. TEST_F(ServerTest, GetWithRange3) {
  4388. auto res = cli_.Get("/with-range", {
  4389. make_range_header({{0, 0}}),
  4390. {"Accept-Encoding", ""},
  4391. });
  4392. ASSERT_TRUE(res);
  4393. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4394. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4395. EXPECT_EQ(true, res->has_header("Content-Range"));
  4396. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4397. EXPECT_EQ(std::string("a"), res->body);
  4398. }
  4399. TEST_F(ServerTest, GetWithRange4) {
  4400. auto res = cli_.Get("/with-range", {
  4401. make_range_header({{-1, 2}}),
  4402. {"Accept-Encoding", ""},
  4403. });
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4406. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4407. EXPECT_EQ(true, res->has_header("Content-Range"));
  4408. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4409. EXPECT_EQ(std::string("fg"), res->body);
  4410. }
  4411. TEST_F(ServerTest, GetWithRange5) {
  4412. auto res = cli_.Get("/with-range", {
  4413. make_range_header({{0, 5}}),
  4414. {"Accept-Encoding", ""},
  4415. });
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4418. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4419. EXPECT_EQ(true, res->has_header("Content-Range"));
  4420. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4421. EXPECT_EQ(std::string("abcdef"), res->body);
  4422. }
  4423. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4424. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4425. ASSERT_TRUE(res);
  4426. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4427. }
  4428. TEST_F(ServerTest, GetWithRangeMultipart) {
  4429. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4430. ASSERT_TRUE(res);
  4431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4432. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4433. EXPECT_EQ(false, res->has_header("Content-Range"));
  4434. EXPECT_EQ(267U, res->body.size());
  4435. }
  4436. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4437. auto res =
  4438. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4439. ASSERT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4441. }
  4442. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4443. auto res = cli_.Get("/with-range-customized-response",
  4444. {{make_range_header({{1, 2}})}});
  4445. ASSERT_TRUE(res);
  4446. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4447. EXPECT_EQ(true, res->has_header("Content-Length"));
  4448. EXPECT_EQ(false, res->has_header("Content-Range"));
  4449. EXPECT_EQ(JSON_DATA, res->body);
  4450. }
  4451. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4452. auto res = cli_.Get("/with-range-customized-response",
  4453. {{make_range_header({{1, 2}, {4, 5}})}});
  4454. ASSERT_TRUE(res);
  4455. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4456. EXPECT_EQ(true, res->has_header("Content-Length"));
  4457. EXPECT_EQ(false, res->has_header("Content-Range"));
  4458. EXPECT_EQ(JSON_DATA, res->body);
  4459. }
  4460. TEST_F(ServerTest, Issue1772) {
  4461. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4462. ASSERT_TRUE(res);
  4463. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4464. }
  4465. TEST_F(ServerTest, Issue609) {
  4466. auto res = cli_.Delete("/issue609");
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. EXPECT_EQ(std::string("ok"), res->body);
  4470. }
  4471. TEST_F(ServerTest, GetStreamedChunked) {
  4472. auto res = cli_.Get("/streamed-chunked");
  4473. ASSERT_TRUE(res);
  4474. EXPECT_EQ(StatusCode::OK_200, res->status);
  4475. EXPECT_EQ(std::string("123456789"), res->body);
  4476. }
  4477. TEST_F(ServerTest, GetStreamedChunked2) {
  4478. auto res = cli_.Get("/streamed-chunked2");
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::OK_200, res->status);
  4481. EXPECT_EQ(std::string("123456789"), res->body);
  4482. }
  4483. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4484. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4485. ASSERT_TRUE(res);
  4486. EXPECT_EQ(StatusCode::OK_200, res->status);
  4487. EXPECT_EQ(std::string("123456789"), res->body);
  4488. EXPECT_TRUE(res->has_header("Trailer"));
  4489. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4490. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4491. // Trailers are now stored separately from headers (security fix)
  4492. EXPECT_EQ(2U, res->trailers.size());
  4493. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4494. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4495. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4496. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4497. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4498. // Verify trailers are NOT in headers (security verification)
  4499. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4500. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4501. }
  4502. TEST_F(ServerTest, LargeChunkedPost) {
  4503. Request req;
  4504. req.method = "POST";
  4505. req.path = "/large-chunked";
  4506. std::string host_and_port;
  4507. host_and_port += HOST;
  4508. host_and_port += ":";
  4509. host_and_port += std::to_string(PORT);
  4510. req.headers.emplace("Host", host_and_port.c_str());
  4511. req.headers.emplace("Accept", "*/*");
  4512. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4513. req.headers.emplace("Content-Type", "text/plain");
  4514. req.headers.emplace("Content-Length", "0");
  4515. req.headers.emplace("Transfer-Encoding", "chunked");
  4516. std::string long_string(30 * 1024u, 'a');
  4517. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4518. // Attempt to make a large enough post to exceed OS buffers, to test that
  4519. // the server handles short reads if the full chunk data isn't available.
  4520. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4521. auto res = std::make_shared<Response>();
  4522. auto error = Error::Success;
  4523. auto ret = cli_.send(req, *res, error);
  4524. ASSERT_TRUE(ret);
  4525. EXPECT_EQ(StatusCode::OK_200, res->status);
  4526. }
  4527. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4528. auto res = cli_.Get("/remote_addr");
  4529. ASSERT_TRUE(res);
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4532. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4533. }
  4534. TEST_F(ServerTest, GetMethodLocalAddr) {
  4535. auto res = cli_.Get("/local_addr");
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::OK_200, res->status);
  4538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4539. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4540. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4541. }
  4542. TEST_F(ServerTest, HTTPResponseSplitting) {
  4543. auto res = cli_.Get("/http_response_splitting");
  4544. ASSERT_TRUE(res);
  4545. EXPECT_EQ(StatusCode::OK_200, res->status);
  4546. }
  4547. TEST_F(ServerTest, SlowRequest) {
  4548. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4549. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4550. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4551. }
  4552. #if 0
  4553. TEST_F(ServerTest, SlowPost) {
  4554. char buffer[64 * 1024];
  4555. memset(buffer, 0x42, sizeof(buffer));
  4556. auto res = cli_.Post(
  4557. "/slowpost", 64 * 1024 * 1024,
  4558. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4559. auto ret = sink.write(buffer, sizeof(buffer));
  4560. EXPECT_TRUE(ret);
  4561. return true;
  4562. },
  4563. "text/plain");
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. }
  4567. TEST_F(ServerTest, SlowPostFail) {
  4568. char buffer[64 * 1024];
  4569. memset(buffer, 0x42, sizeof(buffer));
  4570. cli_.set_write_timeout(std::chrono::seconds(0));
  4571. auto res = cli_.Post(
  4572. "/slowpost", 64 * 1024 * 1024,
  4573. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4574. sink.write(buffer, sizeof(buffer));
  4575. return true;
  4576. },
  4577. "text/plain");
  4578. ASSERT_TRUE(!res);
  4579. EXPECT_EQ(Error::Write, res.error());
  4580. }
  4581. #endif
  4582. TEST_F(ServerTest, Put) {
  4583. auto res = cli_.Put("/put", "PUT", "text/plain");
  4584. ASSERT_TRUE(res);
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. EXPECT_EQ("PUT", res->body);
  4587. }
  4588. TEST_F(ServerTest, PutWithContentProvider) {
  4589. auto res = cli_.Put(
  4590. "/put", 3,
  4591. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4592. sink.os << "PUT";
  4593. return true;
  4594. },
  4595. "text/plain");
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::OK_200, res->status);
  4598. EXPECT_EQ("PUT", res->body);
  4599. }
  4600. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4601. auto res = cli_.Post(
  4602. "/post", 42,
  4603. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4604. return false;
  4605. },
  4606. "text/plain");
  4607. ASSERT_TRUE(!res);
  4608. EXPECT_EQ(Error::Canceled, res.error());
  4609. }
  4610. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4611. auto res = cli_.Put(
  4612. "/put",
  4613. [](size_t /*offset*/, DataSink &sink) {
  4614. sink.os << "PUT";
  4615. sink.done();
  4616. return true;
  4617. },
  4618. "text/plain");
  4619. ASSERT_TRUE(res);
  4620. EXPECT_EQ(StatusCode::OK_200, res->status);
  4621. EXPECT_EQ("PUT", res->body);
  4622. }
  4623. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4624. auto res = cli_.Post(
  4625. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4626. "text/plain");
  4627. ASSERT_TRUE(!res);
  4628. EXPECT_EQ(Error::Canceled, res.error());
  4629. }
  4630. TEST_F(ServerTest, PostLoopBack) {
  4631. std::string body;
  4632. auto res = cli_.Post(
  4633. "/post-loopback", 9,
  4634. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4635. EXPECT_EQ(9u, length);
  4636. sink.write("123", 3);
  4637. sink.write("456", 3);
  4638. sink.write("789", 3);
  4639. return true;
  4640. },
  4641. "text/plain",
  4642. [&body](const char *data, size_t data_length) {
  4643. body.append(data, data_length);
  4644. return true;
  4645. });
  4646. ASSERT_TRUE(res);
  4647. EXPECT_EQ(StatusCode::OK_200, res->status);
  4648. EXPECT_EQ("123456789", body);
  4649. }
  4650. TEST_F(ServerTest, PutLoopBack) {
  4651. std::string body;
  4652. auto res = cli_.Put(
  4653. "/put-loopback", 9,
  4654. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4655. EXPECT_EQ(9u, length);
  4656. sink.write("123", 3);
  4657. sink.write("456", 3);
  4658. sink.write("789", 3);
  4659. return true;
  4660. },
  4661. "text/plain",
  4662. [&body](const char *data, size_t data_length) {
  4663. body.append(data, data_length);
  4664. return true;
  4665. });
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("123456789", body);
  4669. }
  4670. TEST_F(ServerTest, PatchLoopBack) {
  4671. std::string body;
  4672. auto res = cli_.Patch(
  4673. "/patch-loopback", 9,
  4674. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4675. EXPECT_EQ(9u, length);
  4676. sink.write("123", 3);
  4677. sink.write("456", 3);
  4678. sink.write("789", 3);
  4679. return true;
  4680. },
  4681. "text/plain",
  4682. [&body](const char *data, size_t data_length) {
  4683. body.append(data, data_length);
  4684. return true;
  4685. });
  4686. ASSERT_TRUE(res);
  4687. EXPECT_EQ(StatusCode::OK_200, res->status);
  4688. EXPECT_EQ("123456789", body);
  4689. }
  4690. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4691. std::string body;
  4692. auto res = cli_.Post(
  4693. "/post-loopback",
  4694. [](size_t /*offset*/, DataSink &sink) {
  4695. sink.write("123", 3);
  4696. sink.write("456", 3);
  4697. sink.write("789", 3);
  4698. sink.done();
  4699. return true;
  4700. },
  4701. "text/plain",
  4702. [&body](const char *data, size_t data_length) {
  4703. body.append(data, data_length);
  4704. return true;
  4705. });
  4706. ASSERT_TRUE(res);
  4707. EXPECT_EQ(StatusCode::OK_200, res->status);
  4708. EXPECT_EQ("123456789", body);
  4709. }
  4710. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4711. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4712. cli_.set_compress(true);
  4713. auto res = cli_.Put(
  4714. "/put", 3,
  4715. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4716. sink.os << "PUT";
  4717. return true;
  4718. },
  4719. "text/plain");
  4720. ASSERT_TRUE(res);
  4721. EXPECT_EQ(StatusCode::OK_200, res->status);
  4722. EXPECT_EQ("PUT", res->body);
  4723. }
  4724. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4725. cli_.set_compress(true);
  4726. auto res = cli_.Post(
  4727. "/post", 42,
  4728. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4729. return false;
  4730. },
  4731. "text/plain");
  4732. ASSERT_TRUE(!res);
  4733. EXPECT_EQ(Error::Canceled, res.error());
  4734. }
  4735. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4736. cli_.set_compress(true);
  4737. auto res = cli_.Put(
  4738. "/put",
  4739. [](size_t /*offset*/, DataSink &sink) {
  4740. sink.os << "PUT";
  4741. sink.done();
  4742. return true;
  4743. },
  4744. "text/plain");
  4745. ASSERT_TRUE(res);
  4746. EXPECT_EQ(StatusCode::OK_200, res->status);
  4747. EXPECT_EQ("PUT", res->body);
  4748. }
  4749. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4750. cli_.set_compress(true);
  4751. auto res = cli_.Post(
  4752. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4753. "text/plain");
  4754. ASSERT_TRUE(!res);
  4755. EXPECT_EQ(Error::Canceled, res.error());
  4756. }
  4757. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4758. cli_.set_compress(true);
  4759. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4760. ASSERT_TRUE(res);
  4761. EXPECT_EQ(StatusCode::OK_200, res->status);
  4762. EXPECT_EQ(LARGE_DATA, res->body);
  4763. }
  4764. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4765. #ifdef CPPHTTPLIB_SSL_ENABLED
  4766. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4767. Client cli(s.c_str());
  4768. cli.enable_server_certificate_verification(false);
  4769. #else
  4770. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4771. Client cli(s.c_str());
  4772. #endif
  4773. cli.set_compress(true);
  4774. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4775. ASSERT_TRUE(res);
  4776. EXPECT_EQ(StatusCode::OK_200, res->status);
  4777. EXPECT_EQ(LARGE_DATA, res->body);
  4778. // The compressed size should be less than a 10th of the original. May vary
  4779. // depending on the zlib library.
  4780. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4781. static_cast<uint64_t>(10 * 1024 * 1024));
  4782. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4783. }
  4784. TEST_F(ServerTest, PutContentWithDeflate) {
  4785. cli_.set_compress(false);
  4786. Headers headers;
  4787. headers.emplace("Content-Encoding", "deflate");
  4788. // PUT in deflate format:
  4789. auto res = cli_.Put("/put", headers,
  4790. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ("PUT", res->body);
  4794. }
  4795. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4796. Headers headers;
  4797. headers.emplace("Accept-Encoding", "gzip, deflate");
  4798. auto res = cli_.Get("/streamed-chunked", headers);
  4799. ASSERT_TRUE(res);
  4800. EXPECT_EQ(StatusCode::OK_200, res->status);
  4801. EXPECT_EQ(std::string("123456789"), res->body);
  4802. }
  4803. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4804. Headers headers;
  4805. headers.emplace("Accept-Encoding", "gzip, deflate");
  4806. auto res = cli_.Get("/streamed-chunked2", headers);
  4807. ASSERT_TRUE(res);
  4808. EXPECT_EQ(StatusCode::OK_200, res->status);
  4809. EXPECT_EQ(std::string("123456789"), res->body);
  4810. }
  4811. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4812. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. }
  4816. TEST(GzipDecompressor, ChunkedDecompression) {
  4817. std::string data;
  4818. for (size_t i = 0; i < 32 * 1024; ++i) {
  4819. data.push_back(static_cast<char>('a' + i % 26));
  4820. }
  4821. std::string compressed_data;
  4822. {
  4823. httplib::detail::gzip_compressor compressor;
  4824. bool result = compressor.compress(
  4825. data.data(), data.size(),
  4826. /*last=*/true,
  4827. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4828. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4829. compressed_data_size);
  4830. return true;
  4831. });
  4832. ASSERT_TRUE(result);
  4833. }
  4834. std::string decompressed_data;
  4835. {
  4836. httplib::detail::gzip_decompressor decompressor;
  4837. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4838. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4839. size_t chunk_size = 130;
  4840. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4841. chunk_begin += chunk_size) {
  4842. size_t current_chunk_size =
  4843. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4844. bool result = decompressor.decompress(
  4845. compressed_data.data() + chunk_begin, current_chunk_size,
  4846. [&](const char *decompressed_data_chunk,
  4847. size_t decompressed_data_chunk_size) {
  4848. decompressed_data.insert(decompressed_data.size(),
  4849. decompressed_data_chunk,
  4850. decompressed_data_chunk_size);
  4851. return true;
  4852. });
  4853. ASSERT_TRUE(result);
  4854. }
  4855. }
  4856. ASSERT_EQ(data, decompressed_data);
  4857. }
  4858. TEST(GzipDecompressor, DeflateDecompression) {
  4859. std::string original_text = "Raw deflate without gzip";
  4860. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4861. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4862. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4863. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4864. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4865. std::string decompressed_data;
  4866. {
  4867. httplib::detail::gzip_decompressor decompressor;
  4868. bool result = decompressor.decompress(
  4869. compressed_data.data(), compressed_data.size(),
  4870. [&](const char *decompressed_data_chunk,
  4871. size_t decompressed_data_chunk_size) {
  4872. decompressed_data.insert(decompressed_data.size(),
  4873. decompressed_data_chunk,
  4874. decompressed_data_chunk_size);
  4875. return true;
  4876. });
  4877. ASSERT_TRUE(result);
  4878. }
  4879. ASSERT_EQ(original_text, decompressed_data);
  4880. }
  4881. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4882. std::string original_text = "Raw deflate without gzip";
  4883. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4884. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4885. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4886. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4887. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4888. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4889. std::string decompressed_data;
  4890. {
  4891. httplib::detail::gzip_decompressor decompressor;
  4892. bool result = decompressor.decompress(
  4893. compressed_data.data(), compressed_data.size(),
  4894. [&](const char *decompressed_data_chunk,
  4895. size_t decompressed_data_chunk_size) {
  4896. decompressed_data.insert(decompressed_data.size(),
  4897. decompressed_data_chunk,
  4898. decompressed_data_chunk_size);
  4899. return true;
  4900. });
  4901. ASSERT_TRUE(result);
  4902. }
  4903. ASSERT_EQ(original_text, decompressed_data);
  4904. }
  4905. #ifdef _WIN32
  4906. TEST(GzipDecompressor, LargeRandomData) {
  4907. // prepare large random data that is difficult to be compressed and is
  4908. // expected to have large size even when compressed
  4909. std::random_device seed_gen;
  4910. std::mt19937 random(seed_gen());
  4911. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4912. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4913. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4914. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4915. // compress data over 4GiB
  4916. std::string compressed_data;
  4917. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4918. httplib::detail::gzip_compressor compressor;
  4919. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4920. data.size() * sizeof(std::uint32_t), true,
  4921. [&](const char *data, size_t size) {
  4922. compressed_data.insert(
  4923. compressed_data.size(), data, size);
  4924. return true;
  4925. });
  4926. ASSERT_TRUE(result);
  4927. // FIXME: compressed data size is expected to be greater than 4GiB,
  4928. // but there is no guarantee
  4929. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4930. // decompress data over 4GiB
  4931. std::string decompressed_data;
  4932. decompressed_data.reserve(data_size);
  4933. httplib::detail::gzip_decompressor decompressor;
  4934. result = decompressor.decompress(
  4935. compressed_data.data(), compressed_data.size(),
  4936. [&](const char *data, size_t size) {
  4937. decompressed_data.insert(decompressed_data.size(), data, size);
  4938. return true;
  4939. });
  4940. ASSERT_TRUE(result);
  4941. // compare
  4942. ASSERT_EQ(data_size, decompressed_data.size());
  4943. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4944. 0);
  4945. }
  4946. #endif
  4947. #endif
  4948. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4949. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4950. Headers headers;
  4951. headers.emplace("Accept-Encoding", "br");
  4952. auto res = cli_.Get("/streamed-chunked", headers);
  4953. ASSERT_TRUE(res);
  4954. EXPECT_EQ(StatusCode::OK_200, res->status);
  4955. EXPECT_EQ(std::string("123456789"), res->body);
  4956. }
  4957. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4958. Headers headers;
  4959. headers.emplace("Accept-Encoding", "br");
  4960. auto res = cli_.Get("/streamed-chunked2", headers);
  4961. ASSERT_TRUE(res);
  4962. EXPECT_EQ(StatusCode::OK_200, res->status);
  4963. EXPECT_EQ(std::string("123456789"), res->body);
  4964. }
  4965. #endif
  4966. TEST_F(ServerTest, Patch) {
  4967. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4968. ASSERT_TRUE(res);
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("PATCH", res->body);
  4971. }
  4972. TEST_F(ServerTest, Delete) {
  4973. auto res = cli_.Delete("/delete");
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("DELETE", res->body);
  4977. }
  4978. TEST_F(ServerTest, DeleteContentReceiver) {
  4979. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4980. ASSERT_TRUE(res);
  4981. EXPECT_EQ(StatusCode::OK_200, res->status);
  4982. EXPECT_EQ("content", res->body);
  4983. }
  4984. TEST_F(ServerTest, Options) {
  4985. auto res = cli_.Options("*");
  4986. ASSERT_TRUE(res);
  4987. EXPECT_EQ(StatusCode::OK_200, res->status);
  4988. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4989. EXPECT_TRUE(res->body.empty());
  4990. }
  4991. TEST_F(ServerTest, URL) {
  4992. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4993. ASSERT_TRUE(res);
  4994. EXPECT_EQ(StatusCode::OK_200, res->status);
  4995. }
  4996. TEST_F(ServerTest, ArrayParam) {
  4997. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4998. ASSERT_TRUE(res);
  4999. EXPECT_EQ(StatusCode::OK_200, res->status);
  5000. }
  5001. TEST_F(ServerTest, NoMultipleHeaders) {
  5002. Headers headers = {{"Content-Length", "5"}};
  5003. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5004. "text/plain");
  5005. ASSERT_TRUE(res);
  5006. EXPECT_EQ(StatusCode::OK_200, res->status);
  5007. }
  5008. TEST_F(ServerTest, PostContentReceiver) {
  5009. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5010. ASSERT_TRUE(res);
  5011. ASSERT_EQ(StatusCode::OK_200, res->status);
  5012. ASSERT_EQ("content", res->body);
  5013. }
  5014. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5015. UploadFormDataItems items = {
  5016. {"text1", "text default", "", ""},
  5017. {"text2", "aωb", "", ""},
  5018. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5019. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5020. {"file3", "", "", "application/octet-stream"},
  5021. };
  5022. auto res = cli_.Post("/content_receiver", items);
  5023. ASSERT_TRUE(res);
  5024. EXPECT_EQ(StatusCode::OK_200, res->status);
  5025. }
  5026. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5027. UploadFormDataItems items = {
  5028. {"text1", "text default", "", ""},
  5029. {"text2", "aωb", "", ""},
  5030. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5031. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5032. {"file3", "", "", "application/octet-stream"},
  5033. };
  5034. auto boundary = std::string("+++++");
  5035. std::string body;
  5036. for (const auto &item : items) {
  5037. body += "--" + boundary + "\r\n";
  5038. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5039. if (!item.filename.empty()) {
  5040. body += "; filename=\"" + item.filename + "\"";
  5041. }
  5042. body += "\r\n";
  5043. if (!item.content_type.empty()) {
  5044. body += "Content-Type: " + item.content_type + "\r\n";
  5045. }
  5046. body += "\r\n";
  5047. body += item.content + "\r\n";
  5048. }
  5049. body += "--" + boundary + "--\r\n";
  5050. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5051. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5052. ASSERT_TRUE(res);
  5053. EXPECT_EQ(StatusCode::OK_200, res->status);
  5054. }
  5055. TEST_F(ServerTest, PostContentReceiverGzip) {
  5056. cli_.set_compress(true);
  5057. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5058. ASSERT_TRUE(res);
  5059. ASSERT_EQ(StatusCode::OK_200, res->status);
  5060. ASSERT_EQ("content", res->body);
  5061. }
  5062. TEST_F(ServerTest, PutContentReceiver) {
  5063. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5064. ASSERT_TRUE(res);
  5065. ASSERT_EQ(StatusCode::OK_200, res->status);
  5066. ASSERT_EQ("content", res->body);
  5067. }
  5068. TEST_F(ServerTest, PatchContentReceiver) {
  5069. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5070. ASSERT_TRUE(res);
  5071. ASSERT_EQ(StatusCode::OK_200, res->status);
  5072. ASSERT_EQ("content", res->body);
  5073. }
  5074. template <typename ClientType>
  5075. void TestWithHeadersAndContentReceiver(
  5076. ClientType &cli,
  5077. std::function<Result(ClientType &, const std::string &, const Headers &,
  5078. const std::string &, const std::string &,
  5079. ContentReceiver, DownloadProgress)>
  5080. request_func) {
  5081. Headers headers;
  5082. headers.emplace("X-Custom-Header", "test-value");
  5083. std::string received_body;
  5084. auto res = request_func(
  5085. cli, "/content_receiver", headers, "content", "application/json",
  5086. [&](const char *data, size_t data_length) {
  5087. received_body.append(data, data_length);
  5088. return true;
  5089. },
  5090. nullptr);
  5091. ASSERT_TRUE(res);
  5092. EXPECT_EQ(StatusCode::OK_200, res->status);
  5093. EXPECT_EQ("content", received_body);
  5094. }
  5095. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5096. #ifdef CPPHTTPLIB_SSL_ENABLED
  5097. using ClientT = SSLClient;
  5098. #else
  5099. using ClientT = Client;
  5100. #endif
  5101. TestWithHeadersAndContentReceiver<ClientT>(
  5102. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5103. const std::string &body, const std::string &content_type,
  5104. ContentReceiver receiver, DownloadProgress progress) {
  5105. return cli.Post(path, headers, body, content_type, receiver, progress);
  5106. });
  5107. }
  5108. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5109. #ifdef CPPHTTPLIB_SSL_ENABLED
  5110. using ClientT = SSLClient;
  5111. #else
  5112. using ClientT = Client;
  5113. #endif
  5114. TestWithHeadersAndContentReceiver<ClientT>(
  5115. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5116. const std::string &body, const std::string &content_type,
  5117. ContentReceiver receiver, DownloadProgress progress) {
  5118. return cli.Put(path, headers, body, content_type, receiver, progress);
  5119. });
  5120. }
  5121. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5122. #ifdef CPPHTTPLIB_SSL_ENABLED
  5123. using ClientT = SSLClient;
  5124. #else
  5125. using ClientT = Client;
  5126. #endif
  5127. TestWithHeadersAndContentReceiver<ClientT>(
  5128. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5129. const std::string &body, const std::string &content_type,
  5130. ContentReceiver receiver, DownloadProgress progress) {
  5131. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5132. });
  5133. }
  5134. template <typename ClientType>
  5135. void TestWithHeadersAndContentReceiverWithProgress(
  5136. ClientType &cli,
  5137. std::function<Result(ClientType &, const std::string &, const Headers &,
  5138. const std::string &, const std::string &,
  5139. ContentReceiver, DownloadProgress)>
  5140. request_func) {
  5141. Headers headers;
  5142. headers.emplace("X-Test-Header", "progress-test");
  5143. std::string received_body;
  5144. auto progress_called = false;
  5145. auto res = request_func(
  5146. cli, "/content_receiver", headers, "content", "text/plain",
  5147. [&](const char *data, size_t data_length) {
  5148. received_body.append(data, data_length);
  5149. return true;
  5150. },
  5151. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5152. progress_called = true;
  5153. return true;
  5154. });
  5155. ASSERT_TRUE(res);
  5156. EXPECT_EQ(StatusCode::OK_200, res->status);
  5157. EXPECT_EQ("content", received_body);
  5158. EXPECT_TRUE(progress_called);
  5159. }
  5160. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5161. #ifdef CPPHTTPLIB_SSL_ENABLED
  5162. using ClientT = SSLClient;
  5163. #else
  5164. using ClientT = Client;
  5165. #endif
  5166. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5167. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5168. const std::string &body, const std::string &content_type,
  5169. ContentReceiver receiver, DownloadProgress progress) {
  5170. return cli.Post(path, headers, body, content_type, receiver, progress);
  5171. });
  5172. }
  5173. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5174. #ifdef CPPHTTPLIB_SSL_ENABLED
  5175. using ClientT = SSLClient;
  5176. #else
  5177. using ClientT = Client;
  5178. #endif
  5179. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5180. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5181. const std::string &body, const std::string &content_type,
  5182. ContentReceiver receiver, DownloadProgress progress) {
  5183. return cli.Put(path, headers, body, content_type, receiver, progress);
  5184. });
  5185. }
  5186. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5187. #ifdef CPPHTTPLIB_SSL_ENABLED
  5188. using ClientT = SSLClient;
  5189. #else
  5190. using ClientT = Client;
  5191. #endif
  5192. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5193. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5194. const std::string &body, const std::string &content_type,
  5195. ContentReceiver receiver, DownloadProgress progress) {
  5196. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5197. });
  5198. }
  5199. template <typename ClientType>
  5200. void TestWithHeadersAndContentReceiverError(
  5201. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5202. const Headers &, const std::string &,
  5203. const std::string &, ContentReceiver)>
  5204. request_func) {
  5205. Headers headers;
  5206. headers.emplace("X-Error-Test", "true");
  5207. std::string received_body;
  5208. auto receiver_failed = false;
  5209. auto res =
  5210. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5211. [&](const char *data, size_t data_length) {
  5212. received_body.append(data, data_length);
  5213. receiver_failed = true;
  5214. return false;
  5215. });
  5216. ASSERT_FALSE(res);
  5217. EXPECT_TRUE(receiver_failed);
  5218. }
  5219. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5220. #ifdef CPPHTTPLIB_SSL_ENABLED
  5221. using ClientT = SSLClient;
  5222. #else
  5223. using ClientT = Client;
  5224. #endif
  5225. TestWithHeadersAndContentReceiverError<ClientT>(
  5226. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5227. const std::string &body, const std::string &content_type,
  5228. ContentReceiver receiver) {
  5229. return cli.Post(path, headers, body, content_type, receiver);
  5230. });
  5231. }
  5232. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5233. #ifdef CPPHTTPLIB_SSL_ENABLED
  5234. using ClientT = SSLClient;
  5235. #else
  5236. using ClientT = Client;
  5237. #endif
  5238. TestWithHeadersAndContentReceiverError<ClientT>(
  5239. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5240. const std::string &body, const std::string &content_type,
  5241. ContentReceiver receiver) {
  5242. return cli.Put(path, headers, body, content_type, receiver);
  5243. });
  5244. }
  5245. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5246. #ifdef CPPHTTPLIB_SSL_ENABLED
  5247. using ClientT = SSLClient;
  5248. #else
  5249. using ClientT = Client;
  5250. #endif
  5251. TestWithHeadersAndContentReceiverError<ClientT>(
  5252. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5253. const std::string &body, const std::string &content_type,
  5254. ContentReceiver receiver) {
  5255. return cli.Patch(path, headers, body, content_type, receiver);
  5256. });
  5257. }
  5258. TEST_F(ServerTest, PostQueryStringAndBody) {
  5259. auto res =
  5260. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5261. ASSERT_TRUE(res);
  5262. ASSERT_EQ(StatusCode::OK_200, res->status);
  5263. }
  5264. TEST_F(ServerTest, HTTP2Magic) {
  5265. Request req;
  5266. req.method = "PRI";
  5267. req.path = "*";
  5268. req.body = "SM";
  5269. auto res = std::make_shared<Response>();
  5270. auto error = Error::Success;
  5271. auto ret = cli_.send(req, *res, error);
  5272. ASSERT_TRUE(ret);
  5273. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5274. }
  5275. TEST_F(ServerTest, KeepAlive) {
  5276. auto res = cli_.Get("/hi");
  5277. ASSERT_TRUE(res);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5280. EXPECT_EQ("Hello World!", res->body);
  5281. res = cli_.Get("/hi");
  5282. ASSERT_TRUE(res);
  5283. EXPECT_EQ(StatusCode::OK_200, res->status);
  5284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5285. EXPECT_EQ("Hello World!", res->body);
  5286. res = cli_.Get("/hi");
  5287. ASSERT_TRUE(res);
  5288. EXPECT_EQ(StatusCode::OK_200, res->status);
  5289. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5290. EXPECT_EQ("Hello World!", res->body);
  5291. res = cli_.Get("/not-exist");
  5292. ASSERT_TRUE(res);
  5293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5294. res = cli_.Post("/empty", "", "text/plain");
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5298. EXPECT_EQ("empty", res->body);
  5299. EXPECT_EQ("close", res->get_header_value("Connection"));
  5300. res = cli_.Post(
  5301. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5302. "text/plain");
  5303. ASSERT_TRUE(res);
  5304. EXPECT_EQ(StatusCode::OK_200, res->status);
  5305. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5306. EXPECT_EQ("empty", res->body);
  5307. cli_.set_keep_alive(false);
  5308. res = cli_.Get("/last-request");
  5309. ASSERT_TRUE(res);
  5310. EXPECT_EQ(StatusCode::OK_200, res->status);
  5311. EXPECT_EQ("close", res->get_header_value("Connection"));
  5312. }
  5313. TEST_F(ServerTest, TooManyRedirect) {
  5314. cli_.set_follow_location(true);
  5315. auto res = cli_.Get("/redirect/0");
  5316. ASSERT_TRUE(!res);
  5317. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5318. }
  5319. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5320. Request req;
  5321. req.method = "FOOBAR";
  5322. req.path = "/hi";
  5323. cli_.set_keep_alive(true);
  5324. auto res = cli_.send(req);
  5325. ASSERT_TRUE(res);
  5326. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5327. EXPECT_EQ("close", res->get_header_value("Connection"));
  5328. EXPECT_FALSE(cli_.is_socket_open());
  5329. }
  5330. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5331. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5332. TEST_F(ServerTest, Gzip) {
  5333. Headers headers;
  5334. headers.emplace("Accept-Encoding", "gzip, deflate");
  5335. auto res = cli_.Get("/compress", headers);
  5336. ASSERT_TRUE(res);
  5337. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5340. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5341. "7890123456789012345678901234567890",
  5342. res->body);
  5343. EXPECT_EQ(StatusCode::OK_200, res->status);
  5344. }
  5345. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5346. Headers headers;
  5347. headers.emplace("Accept-Encoding", "gzip, deflate");
  5348. auto res = cli_.Get("/compress-with-charset", headers);
  5349. ASSERT_TRUE(res);
  5350. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5351. EXPECT_EQ("application/json; charset=utf-8",
  5352. res->get_header_value("Content-Type"));
  5353. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5354. "7890123456789012345678901234567890",
  5355. res->body);
  5356. EXPECT_EQ(StatusCode::OK_200, res->status);
  5357. }
  5358. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5359. Headers headers;
  5360. headers.emplace("Accept-Encoding", "");
  5361. auto res = cli_.Get("/compress", headers);
  5362. ASSERT_TRUE(res);
  5363. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5366. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5367. "7890123456789012345678901234567890",
  5368. res->body);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. }
  5371. TEST_F(ServerTest, GzipWithContentReceiver) {
  5372. Headers headers;
  5373. headers.emplace("Accept-Encoding", "gzip, deflate");
  5374. std::string body;
  5375. auto res = cli_.Get("/compress", headers,
  5376. [&](const char *data, uint64_t data_length) {
  5377. EXPECT_EQ(100U, data_length);
  5378. body.append(data, data_length);
  5379. return true;
  5380. });
  5381. ASSERT_TRUE(res);
  5382. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5383. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5384. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5385. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5386. "7890123456789012345678901234567890",
  5387. body);
  5388. EXPECT_EQ(StatusCode::OK_200, res->status);
  5389. }
  5390. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5391. Headers headers;
  5392. headers.emplace("Accept-Encoding", "gzip, deflate");
  5393. cli_.set_decompress(false);
  5394. auto res = cli_.Get("/compress", headers);
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5399. EXPECT_EQ(33U, res->body.size());
  5400. EXPECT_EQ(StatusCode::OK_200, res->status);
  5401. }
  5402. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5403. Headers headers;
  5404. headers.emplace("Accept-Encoding", "");
  5405. std::string body;
  5406. auto res = cli_.Get("/compress", headers,
  5407. [&](const char *data, uint64_t data_length) {
  5408. EXPECT_EQ(100U, data_length);
  5409. body.append(data, data_length);
  5410. return true;
  5411. });
  5412. ASSERT_TRUE(res);
  5413. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5414. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5415. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5416. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5417. "7890123456789012345678901234567890",
  5418. body);
  5419. EXPECT_EQ(StatusCode::OK_200, res->status);
  5420. }
  5421. TEST_F(ServerTest, NoGzip) {
  5422. Headers headers;
  5423. headers.emplace("Accept-Encoding", "gzip, deflate");
  5424. auto res = cli_.Get("/nocompress", headers);
  5425. ASSERT_TRUE(res);
  5426. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5427. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5428. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5429. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5430. "7890123456789012345678901234567890",
  5431. res->body);
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. }
  5434. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5435. Headers headers;
  5436. headers.emplace("Accept-Encoding", "gzip, deflate");
  5437. std::string body;
  5438. auto res = cli_.Get("/nocompress", headers,
  5439. [&](const char *data, uint64_t data_length) {
  5440. EXPECT_EQ(100U, data_length);
  5441. body.append(data, data_length);
  5442. return true;
  5443. });
  5444. ASSERT_TRUE(res);
  5445. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5446. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5447. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5448. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5449. "7890123456789012345678901234567890",
  5450. body);
  5451. EXPECT_EQ(StatusCode::OK_200, res->status);
  5452. }
  5453. TEST_F(ServerTest, MultipartFormDataGzip) {
  5454. UploadFormDataItems items = {
  5455. {"key1", "test", "", ""},
  5456. {"key2", "--abcdefg123", "", ""},
  5457. };
  5458. cli_.set_compress(true);
  5459. auto res = cli_.Post("/compress-multipart", items);
  5460. ASSERT_TRUE(res);
  5461. EXPECT_EQ(StatusCode::OK_200, res->status);
  5462. }
  5463. #endif
  5464. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5465. TEST_F(ServerTest, Brotli) {
  5466. Headers headers;
  5467. headers.emplace("Accept-Encoding", "br");
  5468. auto res = cli_.Get("/compress", headers);
  5469. ASSERT_TRUE(res);
  5470. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5472. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5473. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5474. "7890123456789012345678901234567890",
  5475. res->body);
  5476. EXPECT_EQ(StatusCode::OK_200, res->status);
  5477. }
  5478. #endif
  5479. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5480. TEST_F(ServerTest, Zstd) {
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "zstd");
  5483. auto res = cli_.Get("/compress", headers);
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5488. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5489. "7890123456789012345678901234567890",
  5490. res->body);
  5491. EXPECT_EQ(StatusCode::OK_200, res->status);
  5492. }
  5493. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5494. Headers headers;
  5495. headers.emplace("Accept-Encoding", "");
  5496. auto res = cli_.Get("/compress", headers);
  5497. ASSERT_TRUE(res);
  5498. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5500. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5501. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5502. "7890123456789012345678901234567890",
  5503. res->body);
  5504. EXPECT_EQ(StatusCode::OK_200, res->status);
  5505. }
  5506. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5507. Headers headers;
  5508. headers.emplace("Accept-Encoding", "zstd");
  5509. std::string body;
  5510. auto res = cli_.Get("/compress", headers,
  5511. [&](const char *data, uint64_t data_length) {
  5512. EXPECT_EQ(100U, data_length);
  5513. body.append(data, data_length);
  5514. return true;
  5515. });
  5516. ASSERT_TRUE(res);
  5517. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5520. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5521. "7890123456789012345678901234567890",
  5522. body);
  5523. EXPECT_EQ(StatusCode::OK_200, res->status);
  5524. }
  5525. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5526. Headers headers;
  5527. headers.emplace("Accept-Encoding", "zstd");
  5528. cli_.set_decompress(false);
  5529. auto res = cli_.Get("/compress", headers);
  5530. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5531. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5532. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5533. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5534. ASSERT_TRUE(res);
  5535. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5536. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5537. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. ASSERT_EQ(26U, res->body.size());
  5540. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5541. 0);
  5542. }
  5543. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5544. Headers headers;
  5545. headers.emplace("Accept-Encoding", "");
  5546. std::string body;
  5547. auto res = cli_.Get("/compress", headers,
  5548. [&](const char *data, uint64_t data_length) {
  5549. EXPECT_EQ(100U, data_length);
  5550. body.append(data, data_length);
  5551. return true;
  5552. });
  5553. ASSERT_TRUE(res);
  5554. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5556. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5558. "7890123456789012345678901234567890",
  5559. body);
  5560. EXPECT_EQ(StatusCode::OK_200, res->status);
  5561. }
  5562. TEST_F(ServerTest, NoZstd) {
  5563. Headers headers;
  5564. headers.emplace("Accept-Encoding", "zstd");
  5565. auto res = cli_.Get("/nocompress", headers);
  5566. ASSERT_TRUE(res);
  5567. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5568. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5569. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5571. "7890123456789012345678901234567890",
  5572. res->body);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. }
  5575. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5576. Headers headers;
  5577. headers.emplace("Accept-Encoding", "zstd");
  5578. std::string body;
  5579. auto res = cli_.Get("/nocompress", headers,
  5580. [&](const char *data, uint64_t data_length) {
  5581. EXPECT_EQ(100U, data_length);
  5582. body.append(data, data_length);
  5583. return true;
  5584. });
  5585. ASSERT_TRUE(res);
  5586. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5587. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5588. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5589. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5590. "7890123456789012345678901234567890",
  5591. body);
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. }
  5594. // TODO: How to enable zstd ??
  5595. TEST_F(ServerTest, MultipartFormDataZstd) {
  5596. UploadFormDataItems items = {
  5597. {"key1", "test", "", ""},
  5598. {"key2", "--abcdefg123", "", ""},
  5599. };
  5600. Headers headers;
  5601. headers.emplace("Accept-Encoding", "zstd");
  5602. cli_.set_compress(true);
  5603. auto res = cli_.Post("/compress-multipart", headers, items);
  5604. ASSERT_TRUE(res);
  5605. EXPECT_EQ(StatusCode::OK_200, res->status);
  5606. }
  5607. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5608. Headers headers;
  5609. headers.emplace("Accept-Encoding", "zstd");
  5610. cli_.set_compress(true);
  5611. auto res = cli_.Put(
  5612. "/put", headers, 3,
  5613. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5614. sink.os << "PUT";
  5615. return true;
  5616. },
  5617. "text/plain");
  5618. ASSERT_TRUE(res);
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. EXPECT_EQ("PUT", res->body);
  5621. }
  5622. // Pre-compression logging tests
  5623. TEST_F(ServerTest, PreCompressionLogging) {
  5624. // Test data for compression (matches the actual /compress endpoint content)
  5625. const std::string test_content =
  5626. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5627. "3456789012345678901234567890";
  5628. // Variables to capture logging data
  5629. std::string pre_compression_body;
  5630. std::string pre_compression_content_type;
  5631. std::string pre_compression_content_encoding;
  5632. std::string post_compression_body;
  5633. std::string post_compression_content_type;
  5634. std::string post_compression_content_encoding;
  5635. // Set up pre-compression logger
  5636. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5637. const Response &res) {
  5638. pre_compression_body = res.body;
  5639. pre_compression_content_type = res.get_header_value("Content-Type");
  5640. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5641. });
  5642. // Set up post-compression logger
  5643. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5644. post_compression_body = res.body;
  5645. post_compression_content_type = res.get_header_value("Content-Type");
  5646. post_compression_content_encoding =
  5647. res.get_header_value("Content-Encoding");
  5648. });
  5649. // Test with gzip compression
  5650. Headers headers;
  5651. headers.emplace("Accept-Encoding", "gzip");
  5652. auto res = cli_.Get("/compress", headers);
  5653. // Verify response was compressed
  5654. ASSERT_TRUE(res);
  5655. EXPECT_EQ(StatusCode::OK_200, res->status);
  5656. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5657. // Verify pre-compression logger captured uncompressed content
  5658. EXPECT_EQ(test_content, pre_compression_body);
  5659. EXPECT_EQ("text/plain", pre_compression_content_type);
  5660. EXPECT_TRUE(pre_compression_content_encoding
  5661. .empty()); // No encoding header before compression
  5662. // Verify post-compression logger captured compressed content
  5663. EXPECT_NE(test_content,
  5664. post_compression_body); // Should be different after compression
  5665. EXPECT_EQ("text/plain", post_compression_content_type);
  5666. EXPECT_EQ("gzip", post_compression_content_encoding);
  5667. // Verify compressed content is smaller
  5668. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5669. }
  5670. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5671. const std::string test_content =
  5672. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5673. "3456789012345678901234567890";
  5674. std::string pre_compression_body;
  5675. std::string post_compression_body;
  5676. svr_.set_pre_compression_logger(
  5677. [&](const Request & /*req*/, const Response &res) {
  5678. pre_compression_body = res.body;
  5679. });
  5680. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5681. post_compression_body = res.body;
  5682. });
  5683. Headers headers;
  5684. headers.emplace("Accept-Encoding", "br");
  5685. auto res = cli_.Get("/compress", headers);
  5686. ASSERT_TRUE(res);
  5687. EXPECT_EQ(StatusCode::OK_200, res->status);
  5688. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5689. // Verify pre-compression content is uncompressed
  5690. EXPECT_EQ(test_content, pre_compression_body);
  5691. // Verify post-compression content is compressed
  5692. EXPECT_NE(test_content, post_compression_body);
  5693. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5694. }
  5695. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5696. const std::string test_content =
  5697. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5698. "3456789012345678901234567890";
  5699. std::string pre_compression_body;
  5700. std::string post_compression_body;
  5701. svr_.set_pre_compression_logger(
  5702. [&](const Request & /*req*/, const Response &res) {
  5703. pre_compression_body = res.body;
  5704. });
  5705. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5706. post_compression_body = res.body;
  5707. });
  5708. // Request without compression (use /nocompress endpoint)
  5709. Headers headers;
  5710. auto res = cli_.Get("/nocompress", headers);
  5711. ASSERT_TRUE(res);
  5712. EXPECT_EQ(StatusCode::OK_200, res->status);
  5713. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5714. // Pre-compression logger should not be called when no compression is applied
  5715. EXPECT_TRUE(
  5716. pre_compression_body.empty()); // Pre-compression logger not called
  5717. EXPECT_EQ(
  5718. test_content,
  5719. post_compression_body); // Post-compression logger captures final content
  5720. }
  5721. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5722. const std::string test_content =
  5723. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5724. "3456789012345678901234567890";
  5725. std::string pre_compression_body;
  5726. bool pre_logger_called = false;
  5727. // Set only pre-compression logger
  5728. svr_.set_pre_compression_logger(
  5729. [&](const Request & /*req*/, const Response &res) {
  5730. pre_compression_body = res.body;
  5731. pre_logger_called = true;
  5732. });
  5733. Headers headers;
  5734. headers.emplace("Accept-Encoding", "gzip");
  5735. auto res = cli_.Get("/compress", headers);
  5736. ASSERT_TRUE(res);
  5737. EXPECT_EQ(StatusCode::OK_200, res->status);
  5738. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5739. // Verify pre-compression logger was called
  5740. EXPECT_TRUE(pre_logger_called);
  5741. EXPECT_EQ(test_content, pre_compression_body);
  5742. }
  5743. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5744. {
  5745. // Test with Expect: 100-continue header - success case
  5746. // Server returns 100 Continue, client sends body, server returns 200 OK
  5747. Request req;
  5748. req.method = "POST";
  5749. req.path = "/post-large";
  5750. req.set_header("Expect", "100-continue");
  5751. req.body = LARGE_DATA;
  5752. Response res;
  5753. auto error = Error::Success;
  5754. cli_.set_keep_alive(true);
  5755. auto ret = cli_.send(req, res, error);
  5756. EXPECT_TRUE(ret);
  5757. EXPECT_EQ(StatusCode::OK_200, res.status);
  5758. EXPECT_EQ(LARGE_DATA, res.body);
  5759. }
  5760. {
  5761. // Test with Expect: 100-continue header - error case
  5762. // Client should not send the body when server returns an error
  5763. Request req;
  5764. req.method = "POST";
  5765. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5766. req.set_header("Expect", "100-continue");
  5767. req.body = LARGE_DATA;
  5768. Response res;
  5769. auto error = Error::Success;
  5770. auto start = std::chrono::high_resolution_clock::now();
  5771. cli_.set_keep_alive(true);
  5772. auto ret = cli_.send(req, res, error);
  5773. auto end = std::chrono::high_resolution_clock::now();
  5774. auto elapsed =
  5775. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5776. .count();
  5777. // With Expect: 100-continue, request completes successfully but with error
  5778. EXPECT_TRUE(ret);
  5779. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5780. EXPECT_EQ("close", res.get_header_value("Connection"));
  5781. EXPECT_FALSE(cli_.is_socket_open());
  5782. EXPECT_LE(elapsed, 200);
  5783. }
  5784. {
  5785. // Send an extra GET request to ensure error recovery without hanging
  5786. Request req;
  5787. req.method = "GET";
  5788. req.path = "/hi";
  5789. auto start = std::chrono::high_resolution_clock::now();
  5790. auto res = cli_.send(req);
  5791. auto end = std::chrono::high_resolution_clock::now();
  5792. auto elapsed =
  5793. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5794. .count();
  5795. ASSERT_TRUE(res);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. EXPECT_EQ("Hello World!", res->body);
  5798. EXPECT_LE(elapsed, 500);
  5799. }
  5800. }
  5801. TEST(ZstdDecompressor, ChunkedDecompression) {
  5802. std::string data;
  5803. for (size_t i = 0; i < 32 * 1024; ++i) {
  5804. data.push_back(static_cast<char>('a' + i % 26));
  5805. }
  5806. std::string compressed_data;
  5807. {
  5808. httplib::detail::zstd_compressor compressor;
  5809. bool result = compressor.compress(
  5810. data.data(), data.size(),
  5811. /*last=*/true,
  5812. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5813. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5814. compressed_data_size);
  5815. return true;
  5816. });
  5817. ASSERT_TRUE(result);
  5818. }
  5819. std::string decompressed_data;
  5820. {
  5821. httplib::detail::zstd_decompressor decompressor;
  5822. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5823. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5824. size_t chunk_size = 130;
  5825. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5826. chunk_begin += chunk_size) {
  5827. size_t current_chunk_size =
  5828. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5829. bool result = decompressor.decompress(
  5830. compressed_data.data() + chunk_begin, current_chunk_size,
  5831. [&](const char *decompressed_data_chunk,
  5832. size_t decompressed_data_chunk_size) {
  5833. decompressed_data.insert(decompressed_data.size(),
  5834. decompressed_data_chunk,
  5835. decompressed_data_chunk_size);
  5836. return true;
  5837. });
  5838. ASSERT_TRUE(result);
  5839. }
  5840. }
  5841. ASSERT_EQ(data, decompressed_data);
  5842. }
  5843. TEST(ZstdDecompressor, Decompress) {
  5844. std::string original_text = "Compressed with ZSTD";
  5845. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5846. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5847. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5848. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5849. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5850. std::string decompressed_data;
  5851. {
  5852. httplib::detail::zstd_decompressor decompressor;
  5853. bool result = decompressor.decompress(
  5854. compressed_data.data(), compressed_data.size(),
  5855. [&](const char *decompressed_data_chunk,
  5856. size_t decompressed_data_chunk_size) {
  5857. decompressed_data.insert(decompressed_data.size(),
  5858. decompressed_data_chunk,
  5859. decompressed_data_chunk_size);
  5860. return true;
  5861. });
  5862. ASSERT_TRUE(result);
  5863. }
  5864. ASSERT_EQ(original_text, decompressed_data);
  5865. }
  5866. #endif
  5867. // Sends a raw request to a server listening at HOST:PORT.
  5868. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5869. std::string *resp = nullptr) {
  5870. auto error = Error::Success;
  5871. auto client_sock = detail::create_client_socket(
  5872. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5873. /*connection_timeout_sec=*/5, 0,
  5874. /*read_timeout_sec=*/5, 0,
  5875. /*write_timeout_sec=*/5, 0, std::string(), error);
  5876. if (client_sock == INVALID_SOCKET) { return false; }
  5877. auto ret = detail::process_client_socket(
  5878. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5879. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5880. if (req.size() !=
  5881. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5882. return false;
  5883. }
  5884. char buf[512];
  5885. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5886. while (line_reader.getline()) {
  5887. if (resp) { *resp += line_reader.ptr(); }
  5888. }
  5889. return true;
  5890. });
  5891. detail::close_socket(client_sock);
  5892. return ret;
  5893. }
  5894. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5895. Server svr;
  5896. std::string header_value;
  5897. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5898. header_value = req.get_header_value("foo");
  5899. res.set_content("ok", "text/plain");
  5900. });
  5901. thread t = thread([&] { svr.listen(HOST, PORT); });
  5902. auto se = detail::scope_exit([&] {
  5903. svr.stop();
  5904. t.join();
  5905. ASSERT_FALSE(svr.is_running());
  5906. });
  5907. svr.wait_until_ready();
  5908. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5909. // like characters are not treated the same - use vertical tab and escape.
  5910. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5911. "foo: \t \v bar \x1B\t \r\n"
  5912. "Connection: close\r\n"
  5913. "\r\n";
  5914. std::string res;
  5915. ASSERT_TRUE(send_request(5, req, &res));
  5916. EXPECT_EQ(header_value, "");
  5917. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5918. }
  5919. // Sends a raw request and verifies that there isn't a crash or exception.
  5920. static void test_raw_request(const std::string &req,
  5921. std::string *out = nullptr) {
  5922. Server svr;
  5923. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5924. res.set_content("ok", "text/plain");
  5925. });
  5926. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5927. res.set_content("ok", "text/plain");
  5928. });
  5929. svr.Get("/header_field_value_check",
  5930. [&](const Request & /*req*/, Response &res) {
  5931. res.set_content("ok", "text/plain");
  5932. });
  5933. // Server read timeout must be longer than the client read timeout for the
  5934. // bug to reproduce, probably to force the server to process a request
  5935. // without a trailing blank line.
  5936. const time_t client_read_timeout_sec = 1;
  5937. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5938. bool listen_thread_ok = false;
  5939. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5940. auto se = detail::scope_exit([&] {
  5941. svr.stop();
  5942. t.join();
  5943. ASSERT_FALSE(svr.is_running());
  5944. EXPECT_TRUE(listen_thread_ok);
  5945. });
  5946. svr.wait_until_ready();
  5947. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5948. }
  5949. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5950. // A certain header line causes an exception if the header property is parsed
  5951. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5952. test_raw_request(
  5953. "GET /hi HTTP/1.1\r\n"
  5954. " : "
  5955. " "
  5956. " ");
  5957. }
  5958. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5959. // A certain header line causes an exception if the header property *name* is
  5960. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5961. // greedy matcher and requires backtracking when there are a lot of ":"
  5962. // characters.
  5963. // This occurs with libc++ but not libstdc++.
  5964. test_raw_request(
  5965. "GET /hi HTTP/1.1\r\n"
  5966. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5967. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5968. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5969. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5970. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5971. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5972. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5973. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5974. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5975. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5976. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5977. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5978. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5979. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5980. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5981. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5982. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5983. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5984. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5985. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5986. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5987. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5988. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5989. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5990. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5991. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5992. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5993. "&&&%%%");
  5994. }
  5995. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5996. // Make sure this doesn't crash the server.
  5997. // In a previous version of the header line regex, the "\r" rendered the line
  5998. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5999. // a new position where the leading white space ended and the field value
  6000. // began.
  6001. // The crash occurs with libc++ but not libstdc++.
  6002. test_raw_request("GET /hi HTTP/1.1\r\n"
  6003. "a:" +
  6004. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6005. "\r\n"
  6006. "\r\n");
  6007. }
  6008. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6009. std::string out;
  6010. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6011. "Content-Type: text/plain\r\n"
  6012. "Transfer-Encoding: chunked\r\n"
  6013. "\r\n"
  6014. "nothex\r\n",
  6015. &out);
  6016. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6017. }
  6018. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6019. std::string out;
  6020. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6021. "Content-Type: text/plain\r\n"
  6022. "Transfer-Encoding: chunked\r\n"
  6023. "\r\n"
  6024. "3\r\n"
  6025. "xyz\r\n"
  6026. "NaN\r\n",
  6027. &out);
  6028. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6029. }
  6030. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6031. std::string out;
  6032. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6033. "Content-Type: text/plain\r\n"
  6034. "Transfer-Encoding: chunked\r\n"
  6035. "\r\n"
  6036. // Length is too large for 64 bits.
  6037. "1ffffffffffffffff\r\n"
  6038. "xyz\r\n",
  6039. &out);
  6040. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6041. }
  6042. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6043. test_raw_request("GET /hi HTTP/1.1\r\n"
  6044. "Content-Type: text/plain\r\n\r");
  6045. }
  6046. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6047. std::string out;
  6048. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6049. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6050. }
  6051. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6052. Server svr;
  6053. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6054. EXPECT_TRUE(!req.remote_addr.empty());
  6055. });
  6056. thread t = thread([&] { svr.listen(HOST, PORT); });
  6057. auto se = detail::scope_exit([&] {
  6058. svr.stop();
  6059. t.join();
  6060. ASSERT_FALSE(svr.is_running());
  6061. });
  6062. svr.wait_until_ready();
  6063. // Send an invalid request line to trigger Bad Request
  6064. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6065. std::string out;
  6066. ASSERT_TRUE(send_request(5, bad_req, &out));
  6067. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6068. }
  6069. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6070. std::string out;
  6071. std::string request(
  6072. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6073. test_raw_request(request, &out);
  6074. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6075. }
  6076. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6077. std::string out;
  6078. std::string request(
  6079. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6080. test_raw_request(request, &out);
  6081. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6082. }
  6083. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6084. std::string out;
  6085. std::string request(
  6086. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6087. test_raw_request(request, &out);
  6088. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6089. }
  6090. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6091. std::string out;
  6092. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6093. "Test: \r\n\r\n",
  6094. &out);
  6095. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6096. }
  6097. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6098. Server svr;
  6099. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6100. res.set_header("Cache-Control", "no-cache");
  6101. res.set_chunked_content_provider(
  6102. "text/event-stream", [](size_t offset, DataSink &sink) {
  6103. std::string s = "data:";
  6104. s += std::to_string(offset);
  6105. s += "\n\n";
  6106. auto ret = sink.write(s.data(), s.size());
  6107. EXPECT_TRUE(ret);
  6108. std::this_thread::sleep_for(std::chrono::seconds(1));
  6109. return true;
  6110. });
  6111. });
  6112. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6113. svr.wait_until_ready();
  6114. Client client(HOST, PORT);
  6115. const Headers headers = {{"Accept", "text/event-stream"}};
  6116. auto get_thread = std::thread([&client, &headers]() {
  6117. auto res = client.Get(
  6118. "/events", headers,
  6119. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6120. });
  6121. auto se = detail::scope_exit([&] {
  6122. svr.stop();
  6123. get_thread.join();
  6124. listen_thread.join();
  6125. ASSERT_FALSE(svr.is_running());
  6126. });
  6127. // Give GET time to get a few messages.
  6128. std::this_thread::sleep_for(std::chrono::seconds(2));
  6129. }
  6130. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6131. httplib::Server svr;
  6132. svr.Post("/hi",
  6133. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6134. res.status = StatusCode::OK_200;
  6135. });
  6136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6137. svr.wait_until_ready();
  6138. Client cli(HOST, PORT);
  6139. auto res = cli.Post("/hi", "data", "text/plain");
  6140. ASSERT_TRUE(res);
  6141. EXPECT_EQ(StatusCode::OK_200, res->status);
  6142. svr.stop();
  6143. thread.join();
  6144. ASSERT_FALSE(svr.is_running());
  6145. res = cli.Post("/hi", "data", "text/plain");
  6146. ASSERT_FALSE(res);
  6147. }
  6148. TEST(ServerStopTest, ListenFailure) {
  6149. Server svr;
  6150. auto t = thread([&]() {
  6151. auto ret = svr.listen("????", PORT);
  6152. EXPECT_FALSE(ret);
  6153. });
  6154. svr.wait_until_ready();
  6155. svr.stop();
  6156. t.join();
  6157. }
  6158. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6159. TEST(ServerStopTest, Decommision) {
  6160. Server svr;
  6161. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6162. for (int i = 0; i < 4; i++) {
  6163. auto is_even = !(i % 2);
  6164. std::thread t{[&] {
  6165. try {
  6166. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6167. if (is_even) {
  6168. throw std::runtime_error("Some thing that happens to go wrong.");
  6169. }
  6170. svr.listen(HOST, PORT);
  6171. } catch (...) { svr.decommission(); }
  6172. }};
  6173. svr.wait_until_ready();
  6174. // Server is up
  6175. {
  6176. Client cli(HOST, PORT);
  6177. auto res = cli.Get("/hi");
  6178. if (is_even) {
  6179. EXPECT_FALSE(res);
  6180. } else {
  6181. EXPECT_TRUE(res);
  6182. EXPECT_EQ("hi...", res->body);
  6183. }
  6184. }
  6185. svr.stop();
  6186. t.join();
  6187. // Server is down...
  6188. {
  6189. Client cli(HOST, PORT);
  6190. auto res = cli.Get("/hi");
  6191. EXPECT_FALSE(res);
  6192. }
  6193. }
  6194. }
  6195. #endif
  6196. // Helper function for string body upload progress tests
  6197. template <typename SetupHandler, typename ClientCall>
  6198. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6199. ClientCall &&client_call,
  6200. const string &body) {
  6201. Server svr;
  6202. setup_handler(svr);
  6203. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6204. auto se = detail::scope_exit([&] {
  6205. svr.stop();
  6206. t.join();
  6207. });
  6208. svr.wait_until_ready();
  6209. Client cli(HOST, PORT);
  6210. vector<uint64_t> progress_values;
  6211. bool progress_called = false;
  6212. auto res =
  6213. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6214. progress_values.push_back(current);
  6215. progress_called = true;
  6216. return true;
  6217. });
  6218. ASSERT_TRUE(res);
  6219. EXPECT_EQ(200, res->status);
  6220. EXPECT_TRUE(progress_called);
  6221. }
  6222. TEST(UploadProgressTest, PostStringBodyBasic) {
  6223. TestStringBodyUploadProgress(
  6224. [](Server &svr) {
  6225. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6226. res.set_content("received", "text/plain");
  6227. });
  6228. },
  6229. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6230. return cli.Post("/test", body, "text/plain", progress_callback);
  6231. },
  6232. "test data for upload progress");
  6233. }
  6234. TEST(UploadProgressTest, PutStringBodyBasic) {
  6235. TestStringBodyUploadProgress(
  6236. [](Server &svr) {
  6237. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6238. res.set_content("put received", "text/plain");
  6239. });
  6240. },
  6241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6242. return cli.Put("/test", body, "text/plain", progress_callback);
  6243. },
  6244. "put test data for upload progress");
  6245. }
  6246. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6247. TestStringBodyUploadProgress(
  6248. [](Server &svr) {
  6249. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6250. res.set_content("patch received", "text/plain");
  6251. });
  6252. },
  6253. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6254. return cli.Patch("/test", body, "text/plain", progress_callback);
  6255. },
  6256. "patch test data for upload progress");
  6257. }
  6258. // Helper function for content provider upload progress tests
  6259. template <typename SetupHandler, typename ClientCall>
  6260. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6261. ClientCall &&client_call) {
  6262. Server svr;
  6263. setup_handler(svr);
  6264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6265. auto se = detail::scope_exit([&] {
  6266. svr.stop();
  6267. t.join();
  6268. });
  6269. svr.wait_until_ready();
  6270. Client cli(HOST, PORT);
  6271. vector<uint64_t> progress_values;
  6272. auto res =
  6273. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6274. progress_values.push_back(current);
  6275. return true;
  6276. });
  6277. ASSERT_TRUE(res);
  6278. EXPECT_EQ(200, res->status);
  6279. EXPECT_FALSE(progress_values.empty());
  6280. }
  6281. TEST(UploadProgressTest, PostContentProviderProgress) {
  6282. TestContentProviderUploadProgress(
  6283. [](Server &svr) {
  6284. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6285. res.set_content("provider received", "text/plain");
  6286. });
  6287. },
  6288. [](Client &cli, UploadProgress progress_callback) {
  6289. return cli.Post(
  6290. "/test", 10,
  6291. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6292. sink.os << "test data";
  6293. return true;
  6294. },
  6295. "text/plain", progress_callback);
  6296. });
  6297. }
  6298. // Helper function for multipart upload progress tests
  6299. template <typename SetupHandler, typename ClientCall>
  6300. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6301. ClientCall &&client_call,
  6302. const string &endpoint) {
  6303. Server svr;
  6304. setup_handler(svr);
  6305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6306. auto se = detail::scope_exit([&] {
  6307. svr.stop();
  6308. t.join();
  6309. });
  6310. svr.wait_until_ready();
  6311. Client cli(HOST, PORT);
  6312. vector<uint64_t> progress_values;
  6313. UploadFormDataItems items = {
  6314. {"field1", "value1", "", ""},
  6315. {"field2", "longer value for progress tracking test", "", ""},
  6316. {"file1", "file content data for upload progress", "test.txt",
  6317. "text/plain"}};
  6318. auto res = client_call(cli, endpoint, items,
  6319. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6320. progress_values.push_back(current);
  6321. return true;
  6322. });
  6323. ASSERT_TRUE(res);
  6324. EXPECT_EQ(200, res->status);
  6325. EXPECT_FALSE(progress_values.empty());
  6326. }
  6327. TEST(UploadProgressTest, PostMultipartProgress) {
  6328. TestMultipartUploadProgress(
  6329. [](Server &svr) {
  6330. svr.Post("/multipart", [](const Request &req, Response &res) {
  6331. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6332. res.set_content("multipart received", "text/plain");
  6333. });
  6334. },
  6335. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6336. UploadProgress progress_callback) {
  6337. return cli.Post(endpoint, items, progress_callback);
  6338. },
  6339. "/multipart");
  6340. }
  6341. // Helper function for basic download progress tests
  6342. template <typename SetupHandler, typename ClientCall>
  6343. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6344. ClientCall &&client_call, const string &endpoint,
  6345. size_t expected_content_size) {
  6346. Server svr;
  6347. setup_handler(svr);
  6348. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6349. auto se = detail::scope_exit([&] {
  6350. svr.stop();
  6351. t.join();
  6352. });
  6353. svr.wait_until_ready();
  6354. Client cli(HOST, PORT);
  6355. vector<uint64_t> progress_values;
  6356. auto res = client_call(cli, endpoint,
  6357. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6358. progress_values.push_back(current);
  6359. return true;
  6360. });
  6361. ASSERT_TRUE(res);
  6362. EXPECT_EQ(200, res->status);
  6363. EXPECT_FALSE(progress_values.empty());
  6364. EXPECT_EQ(expected_content_size, res->body.size());
  6365. }
  6366. TEST(DownloadProgressTest, GetBasic) {
  6367. TestBasicDownloadProgress(
  6368. [](Server &svr) {
  6369. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6370. string content(1000, 'D');
  6371. res.set_content(content, "text/plain");
  6372. });
  6373. },
  6374. [](Client &cli, const string &endpoint,
  6375. DownloadProgress progress_callback) {
  6376. return cli.Get(endpoint, progress_callback);
  6377. },
  6378. "/download", 1000u);
  6379. }
  6380. // Helper function for content receiver download progress tests
  6381. template <typename SetupHandler, typename ClientCall>
  6382. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6383. ClientCall &&client_call,
  6384. const string &endpoint,
  6385. size_t expected_content_size) {
  6386. Server svr;
  6387. setup_handler(svr);
  6388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6389. auto se = detail::scope_exit([&] {
  6390. svr.stop();
  6391. t.join();
  6392. });
  6393. svr.wait_until_ready();
  6394. Client cli(HOST, PORT);
  6395. vector<uint64_t> progress_values;
  6396. string received_body;
  6397. auto res = client_call(
  6398. cli, endpoint,
  6399. [&](const char *data, size_t data_length) -> bool {
  6400. received_body.append(data, data_length);
  6401. return true;
  6402. },
  6403. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6404. progress_values.push_back(current);
  6405. return true;
  6406. });
  6407. ASSERT_TRUE(res);
  6408. EXPECT_EQ(200, res->status);
  6409. EXPECT_FALSE(progress_values.empty());
  6410. EXPECT_EQ(expected_content_size, received_body.size());
  6411. EXPECT_TRUE(res->body.empty());
  6412. }
  6413. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6414. TestContentReceiverDownloadProgress(
  6415. [](Server &svr) {
  6416. svr.Get("/download-receiver",
  6417. [](const Request & /*req*/, Response &res) {
  6418. string content(2000, 'R');
  6419. res.set_content(content, "text/plain");
  6420. });
  6421. },
  6422. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6423. DownloadProgress progress_callback) {
  6424. return cli.Get(endpoint, content_receiver, progress_callback);
  6425. },
  6426. "/download-receiver", 2000u);
  6427. }
  6428. TEST(StreamingTest, NoContentLengthStreaming) {
  6429. Server svr;
  6430. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6431. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6432. if (offset < 6) {
  6433. sink.os << (offset < 3 ? "a" : "b");
  6434. } else {
  6435. sink.done();
  6436. }
  6437. return true;
  6438. });
  6439. });
  6440. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6441. auto listen_se = detail::scope_exit([&] {
  6442. svr.stop();
  6443. listen_thread.join();
  6444. ASSERT_FALSE(svr.is_running());
  6445. });
  6446. svr.wait_until_ready();
  6447. Client client(HOST, PORT);
  6448. auto get_thread = std::thread([&client]() {
  6449. std::string s;
  6450. auto res =
  6451. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6452. s += std::string(data, len);
  6453. return true;
  6454. });
  6455. ASSERT_TRUE(res);
  6456. EXPECT_EQ(StatusCode::OK_200, res->status);
  6457. EXPECT_EQ("aaabbb", s);
  6458. });
  6459. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6460. // Give GET time to get a few messages.
  6461. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6462. }
  6463. TEST(MountTest, Unmount) {
  6464. Server svr;
  6465. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6466. auto se = detail::scope_exit([&] {
  6467. svr.stop();
  6468. listen_thread.join();
  6469. ASSERT_FALSE(svr.is_running());
  6470. });
  6471. svr.wait_until_ready();
  6472. Client cli("localhost", PORT);
  6473. svr.set_mount_point("/mount2", "./www2");
  6474. auto res = cli.Get("/");
  6475. ASSERT_TRUE(res);
  6476. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6477. res = cli.Get("/mount2/dir/test.html");
  6478. ASSERT_TRUE(res);
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. svr.set_mount_point("/", "./www");
  6481. res = cli.Get("/dir/");
  6482. ASSERT_TRUE(res);
  6483. EXPECT_EQ(StatusCode::OK_200, res->status);
  6484. svr.remove_mount_point("/");
  6485. res = cli.Get("/dir/");
  6486. ASSERT_TRUE(res);
  6487. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6488. svr.remove_mount_point("/mount2");
  6489. res = cli.Get("/mount2/dir/test.html");
  6490. ASSERT_TRUE(res);
  6491. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6492. }
  6493. TEST(MountTest, Redicect) {
  6494. Server svr;
  6495. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6496. auto se = detail::scope_exit([&] {
  6497. svr.stop();
  6498. listen_thread.join();
  6499. ASSERT_FALSE(svr.is_running());
  6500. });
  6501. svr.set_mount_point("/", "./www");
  6502. svr.wait_until_ready();
  6503. Client cli("localhost", PORT);
  6504. auto res = cli.Get("/dir/");
  6505. ASSERT_TRUE(res);
  6506. EXPECT_EQ(StatusCode::OK_200, res->status);
  6507. res = cli.Get("/dir");
  6508. ASSERT_TRUE(res);
  6509. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6510. res = cli.Get("/file");
  6511. ASSERT_TRUE(res);
  6512. EXPECT_EQ(StatusCode::OK_200, res->status);
  6513. res = cli.Get("/file/");
  6514. ASSERT_TRUE(res);
  6515. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6516. cli.set_follow_location(true);
  6517. res = cli.Get("/dir");
  6518. ASSERT_TRUE(res);
  6519. EXPECT_EQ(StatusCode::OK_200, res->status);
  6520. }
  6521. TEST(MountTest, MultibytesPathName) {
  6522. Server svr;
  6523. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6524. auto se = detail::scope_exit([&] {
  6525. svr.stop();
  6526. listen_thread.join();
  6527. ASSERT_FALSE(svr.is_running());
  6528. });
  6529. svr.set_mount_point("/", "./www");
  6530. svr.wait_until_ready();
  6531. Client cli("localhost", PORT);
  6532. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6533. ASSERT_TRUE(res);
  6534. EXPECT_EQ(StatusCode::OK_200, res->status);
  6535. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6536. }
  6537. TEST(KeepAliveTest, ReadTimeout) {
  6538. Server svr;
  6539. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6540. std::this_thread::sleep_for(std::chrono::seconds(2));
  6541. res.set_content("a", "text/plain");
  6542. });
  6543. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6544. res.set_content("b", "text/plain");
  6545. });
  6546. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6547. auto se = detail::scope_exit([&] {
  6548. svr.stop();
  6549. listen_thread.join();
  6550. ASSERT_FALSE(svr.is_running());
  6551. });
  6552. svr.wait_until_ready();
  6553. Client cli("localhost", PORT);
  6554. cli.set_keep_alive(true);
  6555. cli.set_read_timeout(std::chrono::seconds(1));
  6556. auto resa = cli.Get("/a");
  6557. ASSERT_FALSE(resa);
  6558. EXPECT_EQ(Error::Read, resa.error());
  6559. auto resb = cli.Get("/b");
  6560. ASSERT_TRUE(resb);
  6561. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6562. EXPECT_EQ("b", resb->body);
  6563. }
  6564. TEST(KeepAliveTest, MaxCount) {
  6565. size_t keep_alive_max_count = 3;
  6566. Server svr;
  6567. svr.set_keep_alive_max_count(keep_alive_max_count);
  6568. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6569. res.set_content("Hello World!", "text/plain");
  6570. });
  6571. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6572. auto se = detail::scope_exit([&] {
  6573. svr.stop();
  6574. listen_thread.join();
  6575. ASSERT_FALSE(svr.is_running());
  6576. });
  6577. svr.wait_until_ready();
  6578. Client cli(HOST, PORT);
  6579. cli.set_keep_alive(true);
  6580. for (size_t i = 0; i < 5; i++) {
  6581. auto result = cli.Get("/hi");
  6582. ASSERT_TRUE(result);
  6583. EXPECT_EQ(StatusCode::OK_200, result->status);
  6584. if (i == keep_alive_max_count - 1) {
  6585. EXPECT_EQ("close", result->get_header_value("Connection"));
  6586. } else {
  6587. EXPECT_FALSE(result->has_header("Connection"));
  6588. }
  6589. }
  6590. }
  6591. TEST(KeepAliveTest, Issue1041) {
  6592. Server svr;
  6593. svr.set_keep_alive_timeout(3);
  6594. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6595. res.set_content("Hello World!", "text/plain");
  6596. });
  6597. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6598. auto se = detail::scope_exit([&] {
  6599. svr.stop();
  6600. listen_thread.join();
  6601. ASSERT_FALSE(svr.is_running());
  6602. });
  6603. svr.wait_until_ready();
  6604. Client cli(HOST, PORT);
  6605. cli.set_keep_alive(true);
  6606. auto result = cli.Get("/hi");
  6607. ASSERT_TRUE(result);
  6608. EXPECT_EQ(StatusCode::OK_200, result->status);
  6609. std::this_thread::sleep_for(std::chrono::seconds(5));
  6610. result = cli.Get("/hi");
  6611. ASSERT_TRUE(result);
  6612. EXPECT_EQ(StatusCode::OK_200, result->status);
  6613. }
  6614. TEST(KeepAliveTest, Issue1959) {
  6615. Server svr;
  6616. svr.set_keep_alive_timeout(5);
  6617. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6618. res.set_content("a", "text/plain");
  6619. });
  6620. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6621. auto se = detail::scope_exit([&] {
  6622. if (!svr.is_running()) return;
  6623. svr.stop();
  6624. listen_thread.join();
  6625. ASSERT_FALSE(svr.is_running());
  6626. });
  6627. svr.wait_until_ready();
  6628. Client cli("localhost", PORT);
  6629. cli.set_keep_alive(true);
  6630. using namespace std::chrono;
  6631. auto start = steady_clock::now();
  6632. cli.Get("/a");
  6633. svr.stop();
  6634. listen_thread.join();
  6635. auto end = steady_clock::now();
  6636. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6637. EXPECT_LT(elapsed, 5000);
  6638. }
  6639. #ifdef CPPHTTPLIB_SSL_ENABLED
  6640. TEST(KeepAliveTest, SSLClientReconnection) {
  6641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6642. ASSERT_TRUE(svr.is_valid());
  6643. svr.set_keep_alive_timeout(1);
  6644. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6645. res.set_content("Hello World!", "text/plain");
  6646. });
  6647. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6648. auto se = detail::scope_exit([&] {
  6649. svr.stop();
  6650. listen_thread.join();
  6651. ASSERT_FALSE(svr.is_running());
  6652. });
  6653. svr.wait_until_ready();
  6654. SSLClient cli(HOST, PORT);
  6655. cli.enable_server_certificate_verification(false);
  6656. cli.set_keep_alive(true);
  6657. auto result = cli.Get("/hi");
  6658. ASSERT_TRUE(result);
  6659. EXPECT_EQ(StatusCode::OK_200, result->status);
  6660. result = cli.Get("/hi");
  6661. ASSERT_TRUE(result);
  6662. EXPECT_EQ(StatusCode::OK_200, result->status);
  6663. std::this_thread::sleep_for(std::chrono::seconds(2));
  6664. // Recoonect
  6665. result = cli.Get("/hi");
  6666. ASSERT_TRUE(result);
  6667. EXPECT_EQ(StatusCode::OK_200, result->status);
  6668. result = cli.Get("/hi");
  6669. ASSERT_TRUE(result);
  6670. EXPECT_EQ(StatusCode::OK_200, result->status);
  6671. }
  6672. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6674. ASSERT_TRUE(svr.is_valid());
  6675. svr.set_keep_alive_timeout(1);
  6676. std::string content = "reconnect";
  6677. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6678. res.set_content("Hello World!", "text/plain");
  6679. });
  6680. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6681. auto se = detail::scope_exit([&] {
  6682. svr.stop();
  6683. listen_thread.join();
  6684. ASSERT_FALSE(svr.is_running());
  6685. });
  6686. svr.wait_until_ready();
  6687. SSLClient cli(HOST, PORT);
  6688. cli.enable_server_certificate_verification(false);
  6689. cli.set_keep_alive(true);
  6690. auto result = cli.Post(
  6691. "/hi", content.size(),
  6692. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6693. sink.write(content.c_str(), content.size());
  6694. return true;
  6695. },
  6696. "text/plain");
  6697. ASSERT_TRUE(result);
  6698. EXPECT_EQ(200, result->status);
  6699. std::this_thread::sleep_for(std::chrono::seconds(2));
  6700. // Recoonect
  6701. result = cli.Post(
  6702. "/hi", content.size(),
  6703. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6704. sink.write(content.c_str(), content.size());
  6705. return true;
  6706. },
  6707. "text/plain");
  6708. ASSERT_TRUE(result);
  6709. EXPECT_EQ(200, result->status);
  6710. result = cli.Post(
  6711. "/hi", content.size(),
  6712. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6713. sink.write(content.c_str(), content.size());
  6714. return true;
  6715. },
  6716. "text/plain");
  6717. ASSERT_TRUE(result);
  6718. EXPECT_EQ(200, result->status);
  6719. }
  6720. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6721. using namespace httplib::tls;
  6722. {
  6723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6724. ASSERT_TRUE(svr.is_valid());
  6725. svr.Get("/sni", [&](const Request &req, Response &res) {
  6726. std::string expected = req.sni();
  6727. EXPECT_EQ(expected, req.get_param_value("expected"));
  6728. res.set_content("ok", "text/plain");
  6729. });
  6730. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6731. auto se = detail::scope_exit([&] {
  6732. svr.stop();
  6733. listen_thread.join();
  6734. ASSERT_FALSE(svr.is_running());
  6735. });
  6736. svr.wait_until_ready();
  6737. {
  6738. SSLClient cli("localhost", PORT);
  6739. cli.enable_server_certificate_verification(false);
  6740. auto res = cli.Get("/sni?expected=localhost");
  6741. ASSERT_TRUE(res);
  6742. }
  6743. {
  6744. SSLClient cli("::1", PORT);
  6745. cli.enable_server_certificate_verification(false);
  6746. auto res = cli.Get("/sni?expected=");
  6747. // NOTE: This may fail if the server is listening on IPv4 only
  6748. // (e.g., when localhost resolves to 127.0.0.1 only)
  6749. if (res) {
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. } else {
  6752. EXPECT_EQ(Error::Connection, res.error());
  6753. }
  6754. }
  6755. }
  6756. }
  6757. #endif
  6758. TEST(ClientProblemDetectionTest, ContentProvider) {
  6759. Server svr;
  6760. size_t content_length = 1024 * 1024;
  6761. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6762. res.set_content_provider(
  6763. content_length, "text/plain",
  6764. [&](size_t offset, size_t length, DataSink &sink) {
  6765. auto out_len = std::min(length, static_cast<size_t>(1024));
  6766. std::string out(out_len, '@');
  6767. sink.write(out.data(), out_len);
  6768. return offset < 4096;
  6769. },
  6770. [](bool success) { ASSERT_FALSE(success); });
  6771. });
  6772. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6773. res.set_content_provider(
  6774. 0, "text/plain",
  6775. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6776. EXPECT_TRUE(false);
  6777. return true;
  6778. },
  6779. [](bool success) { ASSERT_FALSE(success); });
  6780. });
  6781. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6782. auto se = detail::scope_exit([&] {
  6783. svr.stop();
  6784. listen_thread.join();
  6785. ASSERT_FALSE(svr.is_running());
  6786. });
  6787. svr.wait_until_ready();
  6788. Client cli("localhost", PORT);
  6789. {
  6790. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6791. size_t /*data_length*/) { return false; });
  6792. ASSERT_FALSE(res);
  6793. }
  6794. {
  6795. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6796. size_t /*data_length*/) { return false; });
  6797. ASSERT_TRUE(res);
  6798. }
  6799. }
  6800. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6801. Server svr;
  6802. svr.set_error_handler([](Request const &, Response &res) -> void {
  6803. res.set_chunked_content_provider(
  6804. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6805. sink.os << "hello";
  6806. sink.os << "world";
  6807. sink.done();
  6808. return true;
  6809. });
  6810. });
  6811. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6812. auto se = detail::scope_exit([&] {
  6813. svr.stop();
  6814. listen_thread.join();
  6815. ASSERT_FALSE(svr.is_running());
  6816. });
  6817. svr.wait_until_ready();
  6818. Client cli("localhost", PORT);
  6819. auto res = cli.Get("/");
  6820. ASSERT_TRUE(res);
  6821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6822. EXPECT_EQ("helloworld", res->body);
  6823. }
  6824. TEST(LongPollingTest, ClientCloseDetection) {
  6825. Server svr;
  6826. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6827. res.set_chunked_content_provider(
  6828. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6829. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6830. sink.os << "hello";
  6831. auto count = 10;
  6832. while (count > 0 && sink.is_writable()) {
  6833. this_thread::sleep_for(chrono::milliseconds(10));
  6834. count--;
  6835. }
  6836. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6837. return true;
  6838. });
  6839. });
  6840. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6841. auto se = detail::scope_exit([&] {
  6842. svr.stop();
  6843. listen_thread.join();
  6844. ASSERT_FALSE(svr.is_running());
  6845. });
  6846. svr.wait_until_ready();
  6847. Client cli("localhost", PORT);
  6848. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6849. EXPECT_EQ("hello", string(data, data_length));
  6850. return false; // close the socket immediately.
  6851. });
  6852. ASSERT_FALSE(res);
  6853. }
  6854. TEST(GetWithParametersTest, GetWithParameters) {
  6855. Server svr;
  6856. svr.Get("/", [&](const Request &req, Response &) {
  6857. EXPECT_EQ("world", req.get_param_value("hello"));
  6858. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6859. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6860. });
  6861. svr.Get("/params", [&](const Request &req, Response &) {
  6862. EXPECT_EQ("world", req.get_param_value("hello"));
  6863. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6864. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6865. });
  6866. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6867. EXPECT_EQ("resource-id", req.matches[1]);
  6868. EXPECT_EQ("foo", req.get_param_value("param1"));
  6869. EXPECT_EQ("bar", req.get_param_value("param2"));
  6870. });
  6871. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6872. EXPECT_EQ("user-id", req.path_params.at("id"));
  6873. EXPECT_EQ("foo", req.get_param_value("param1"));
  6874. EXPECT_EQ("bar", req.get_param_value("param2"));
  6875. });
  6876. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6877. auto se = detail::scope_exit([&] {
  6878. svr.stop();
  6879. listen_thread.join();
  6880. ASSERT_FALSE(svr.is_running());
  6881. });
  6882. svr.wait_until_ready();
  6883. {
  6884. Client cli(HOST, PORT);
  6885. Params params;
  6886. params.emplace("hello", "world");
  6887. params.emplace("hello2", "world2");
  6888. params.emplace("hello3", "world3");
  6889. auto res = cli.Get("/", params, Headers{});
  6890. ASSERT_TRUE(res);
  6891. EXPECT_EQ(StatusCode::OK_200, res->status);
  6892. }
  6893. {
  6894. Client cli(HOST, PORT);
  6895. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6896. ASSERT_TRUE(res);
  6897. EXPECT_EQ(StatusCode::OK_200, res->status);
  6898. }
  6899. {
  6900. Client cli(HOST, PORT);
  6901. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6902. ASSERT_TRUE(res);
  6903. EXPECT_EQ(StatusCode::OK_200, res->status);
  6904. }
  6905. {
  6906. Client cli(HOST, PORT);
  6907. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6908. ASSERT_TRUE(res);
  6909. EXPECT_EQ(StatusCode::OK_200, res->status);
  6910. }
  6911. }
  6912. TEST(GetWithParametersTest, GetWithParameters2) {
  6913. Server svr;
  6914. svr.Get("/", [&](const Request &req, Response &res) {
  6915. auto text = req.get_param_value("hello");
  6916. res.set_content(text, "text/plain");
  6917. });
  6918. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6919. auto se = detail::scope_exit([&] {
  6920. svr.stop();
  6921. listen_thread.join();
  6922. ASSERT_FALSE(svr.is_running());
  6923. });
  6924. svr.wait_until_ready();
  6925. Client cli("localhost", PORT);
  6926. Params params;
  6927. params.emplace("hello", "world");
  6928. std::string body;
  6929. auto res = cli.Get("/", params, Headers{},
  6930. [&](const char *data, size_t data_length) {
  6931. body.append(data, data_length);
  6932. return true;
  6933. });
  6934. ASSERT_TRUE(res);
  6935. EXPECT_EQ(StatusCode::OK_200, res->status);
  6936. EXPECT_EQ("world", body);
  6937. }
  6938. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6939. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6940. auto host = "httpcan.org";
  6941. auto path = std::string{"/range/32"};
  6942. #else
  6943. auto host = "nghttp2.org";
  6944. auto path = std::string{"/httpbin/range/32"};
  6945. #endif
  6946. #ifdef CPPHTTPLIB_SSL_ENABLED
  6947. SSLClient cli(host);
  6948. #else
  6949. Client cli(host);
  6950. #endif
  6951. cli.set_default_headers({make_range_header({{1, 10}})});
  6952. cli.set_connection_timeout(5);
  6953. {
  6954. auto res = cli.Get(path);
  6955. ASSERT_TRUE(res);
  6956. EXPECT_EQ("bcdefghijk", res->body);
  6957. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6958. }
  6959. {
  6960. auto res = cli.Get(path);
  6961. ASSERT_TRUE(res);
  6962. EXPECT_EQ("bcdefghijk", res->body);
  6963. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6964. }
  6965. }
  6966. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6967. Server svr;
  6968. svr.set_default_headers({{"Hello", "World"}});
  6969. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6970. res.set_content("ok", "text/plain");
  6971. });
  6972. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6973. auto se = detail::scope_exit([&] {
  6974. svr.stop();
  6975. listen_thread.join();
  6976. ASSERT_FALSE(svr.is_running());
  6977. });
  6978. svr.wait_until_ready();
  6979. Client cli("localhost", PORT);
  6980. auto res = cli.Get("/");
  6981. ASSERT_TRUE(res);
  6982. EXPECT_EQ(StatusCode::OK_200, res->status);
  6983. EXPECT_EQ("ok", res->body);
  6984. EXPECT_EQ("World", res->get_header_value("Hello"));
  6985. }
  6986. #ifdef CPPHTTPLIB_SSL_ENABLED
  6987. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6988. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6989. ASSERT_TRUE(svr.is_valid());
  6990. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6991. std::this_thread::sleep_for(std::chrono::seconds(2));
  6992. res.set_content("a", "text/plain");
  6993. });
  6994. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6995. res.set_content("b", "text/plain");
  6996. });
  6997. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6998. auto se = detail::scope_exit([&] {
  6999. svr.stop();
  7000. listen_thread.join();
  7001. ASSERT_FALSE(svr.is_running());
  7002. });
  7003. svr.wait_until_ready();
  7004. SSLClient cli("localhost", PORT);
  7005. cli.enable_server_certificate_verification(false);
  7006. cli.set_keep_alive(true);
  7007. cli.set_read_timeout(std::chrono::seconds(1));
  7008. auto resa = cli.Get("/a");
  7009. ASSERT_TRUE(!resa);
  7010. EXPECT_EQ(Error::Read, resa.error());
  7011. auto resb = cli.Get("/b");
  7012. ASSERT_TRUE(resb);
  7013. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7014. EXPECT_EQ("b", resb->body);
  7015. }
  7016. #endif
  7017. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7018. protected:
  7019. ServerTestWithAI_PASSIVE()
  7020. : cli_(HOST, PORT)
  7021. #ifdef CPPHTTPLIB_SSL_ENABLED
  7022. ,
  7023. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7024. #endif
  7025. {
  7026. #ifdef CPPHTTPLIB_SSL_ENABLED
  7027. cli_.enable_server_certificate_verification(false);
  7028. #endif
  7029. }
  7030. virtual void SetUp() {
  7031. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7032. res.set_content("Hello World!", "text/plain");
  7033. });
  7034. t_ = thread(
  7035. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7036. svr_.wait_until_ready();
  7037. }
  7038. virtual void TearDown() {
  7039. svr_.stop();
  7040. t_.join();
  7041. }
  7042. #ifdef CPPHTTPLIB_SSL_ENABLED
  7043. SSLClient cli_;
  7044. SSLServer svr_;
  7045. #else
  7046. Client cli_;
  7047. Server svr_;
  7048. #endif
  7049. thread t_;
  7050. };
  7051. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7052. auto res = cli_.Get("/hi");
  7053. ASSERT_TRUE(res);
  7054. EXPECT_EQ(StatusCode::OK_200, res->status);
  7055. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7056. EXPECT_EQ("Hello World!", res->body);
  7057. }
  7058. class ServerUpDownTest : public ::testing::Test {
  7059. protected:
  7060. ServerUpDownTest() : cli_(HOST, PORT) {}
  7061. virtual void SetUp() {
  7062. t_ = thread([&]() {
  7063. svr_.bind_to_any_port(HOST);
  7064. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7065. ASSERT_TRUE(svr_.listen_after_bind());
  7066. });
  7067. svr_.wait_until_ready();
  7068. }
  7069. virtual void TearDown() {
  7070. svr_.stop();
  7071. t_.join();
  7072. }
  7073. Client cli_;
  7074. Server svr_;
  7075. thread t_;
  7076. };
  7077. TEST_F(ServerUpDownTest, QuickStartStop) {
  7078. // Should not crash, especially when run with
  7079. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7080. }
  7081. class PayloadMaxLengthTest : public ::testing::Test {
  7082. protected:
  7083. PayloadMaxLengthTest()
  7084. : cli_(HOST, PORT)
  7085. #ifdef CPPHTTPLIB_SSL_ENABLED
  7086. ,
  7087. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7088. #endif
  7089. {
  7090. #ifdef CPPHTTPLIB_SSL_ENABLED
  7091. cli_.enable_server_certificate_verification(false);
  7092. #endif
  7093. }
  7094. virtual void SetUp() {
  7095. svr_.set_payload_max_length(8);
  7096. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7097. res.set_content("test", "text/plain");
  7098. });
  7099. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7100. svr_.wait_until_ready();
  7101. }
  7102. virtual void TearDown() {
  7103. svr_.stop();
  7104. t_.join();
  7105. }
  7106. #ifdef CPPHTTPLIB_SSL_ENABLED
  7107. SSLClient cli_;
  7108. SSLServer svr_;
  7109. #else
  7110. Client cli_;
  7111. Server svr_;
  7112. #endif
  7113. thread t_;
  7114. };
  7115. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7116. auto res = cli_.Post("/test", "123456789", "text/plain");
  7117. ASSERT_TRUE(res);
  7118. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7119. res = cli_.Post("/test", "12345678", "text/plain");
  7120. ASSERT_TRUE(res);
  7121. EXPECT_EQ(StatusCode::OK_200, res->status);
  7122. }
  7123. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7124. // Test chunked encoding with payload exceeding the 8-byte limit
  7125. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7126. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7127. ASSERT_TRUE(res);
  7128. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7129. }
  7130. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7131. // Test chunked encoding with payload within the 8-byte limit
  7132. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7133. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7134. ASSERT_TRUE(res);
  7135. EXPECT_EQ(StatusCode::OK_200, res->status);
  7136. }
  7137. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7138. // Test using send_request to send chunked data exceeding payload limit
  7139. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7140. "Host: " +
  7141. std::string(HOST) + ":" + std::to_string(PORT) +
  7142. "\r\n"
  7143. "Transfer-Encoding: chunked\r\n"
  7144. "Connection: close\r\n"
  7145. "\r\n"
  7146. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7147. "0123456789\r\n"
  7148. "0\r\n" // End chunk
  7149. "\r\n";
  7150. std::string response;
  7151. bool result = send_request(1, chunked_request, &response);
  7152. if (!result) {
  7153. // If send_request fails, it might be because the server closed the
  7154. // connection due to payload limit enforcement, which is acceptable
  7155. SUCCEED()
  7156. << "Server rejected oversized chunked request (connection closed)";
  7157. } else {
  7158. // If we got a response, check if it's an error response or connection was
  7159. // closed early Short response length indicates connection was closed due to
  7160. // payload limit
  7161. if (response.length() <= 10) {
  7162. SUCCEED() << "Server closed connection for oversized chunked request";
  7163. } else {
  7164. // Check for error status codes
  7165. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7166. response.find("Payload Too Large") != std::string::npos ||
  7167. response.find("400") != std::string::npos);
  7168. }
  7169. }
  7170. }
  7171. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7172. // Test request without Content-Length header exceeding payload limit
  7173. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7174. "Host: " +
  7175. std::string(HOST) + ":" +
  7176. std::to_string(PORT) +
  7177. "\r\n"
  7178. "Connection: close\r\n"
  7179. "\r\n";
  7180. // Add payload exceeding the 8-byte limit
  7181. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7182. request_without_content_length += large_payload;
  7183. std::string response;
  7184. bool result = send_request(1, request_without_content_length, &response);
  7185. if (!result) {
  7186. // If send_request fails, server likely closed connection due to payload
  7187. // limit
  7188. SUCCEED() << "Server rejected oversized request without Content-Length "
  7189. "(connection closed)";
  7190. } else {
  7191. // Check if server responded with error or closed connection early
  7192. if (response.length() <= 10) {
  7193. SUCCEED() << "Server closed connection for oversized request without "
  7194. "Content-Length";
  7195. } else {
  7196. // Check for error status codes
  7197. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7198. response.find("Payload Too Large") != std::string::npos ||
  7199. response.find("400") != std::string::npos);
  7200. }
  7201. }
  7202. }
  7203. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7204. // Test request without Content-Length header within payload limit
  7205. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7206. "Host: " +
  7207. std::string(HOST) + ":" +
  7208. std::to_string(PORT) +
  7209. "\r\n"
  7210. "Connection: close\r\n"
  7211. "\r\n";
  7212. // Add payload within the 8-byte limit
  7213. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7214. request_without_content_length += small_payload;
  7215. std::string response;
  7216. bool result = send_request(1, request_without_content_length, &response);
  7217. // For requests without Content-Length, the server may have different behavior
  7218. // The key is that it should not reject due to payload limit for small
  7219. // payloads
  7220. if (result) {
  7221. // Check for any HTTP response (success or error, but not connection closed)
  7222. if (response.length() > 10) {
  7223. SUCCEED()
  7224. << "Server processed request without Content-Length within limit";
  7225. } else {
  7226. // Short response might indicate connection closed, which is acceptable
  7227. SUCCEED() << "Server closed connection for request without "
  7228. "Content-Length (acceptable behavior)";
  7229. }
  7230. } else {
  7231. // Connection failure might be due to protocol requirements
  7232. SUCCEED() << "Connection issue with request without Content-Length "
  7233. "(environment-specific)";
  7234. }
  7235. }
  7236. class LargePayloadMaxLengthTest : public ::testing::Test {
  7237. protected:
  7238. LargePayloadMaxLengthTest()
  7239. : cli_(HOST, PORT)
  7240. #ifdef CPPHTTPLIB_SSL_ENABLED
  7241. ,
  7242. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7243. #endif
  7244. {
  7245. #ifdef CPPHTTPLIB_SSL_ENABLED
  7246. cli_.enable_server_certificate_verification(false);
  7247. #endif
  7248. }
  7249. virtual void SetUp() {
  7250. // Set 10MB payload limit
  7251. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7252. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7253. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7254. res.set_content("Large payload test", "text/plain");
  7255. });
  7256. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7257. svr_.wait_until_ready();
  7258. }
  7259. virtual void TearDown() {
  7260. svr_.stop();
  7261. t_.join();
  7262. }
  7263. #ifdef CPPHTTPLIB_SSL_ENABLED
  7264. SSLClient cli_;
  7265. SSLServer svr_;
  7266. #else
  7267. Client cli_;
  7268. Server svr_;
  7269. #endif
  7270. thread t_;
  7271. };
  7272. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7273. // Test chunked encoding with payload within 10MB limit
  7274. std::string medium_payload(5 * 1024 * 1024,
  7275. 'A'); // 5MB payload, within 10MB limit
  7276. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7277. ASSERT_TRUE(res);
  7278. EXPECT_EQ(StatusCode::OK_200, res->status);
  7279. }
  7280. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7281. // Test chunked encoding with payload exceeding 10MB limit
  7282. std::string large_payload(12 * 1024 * 1024,
  7283. 'B'); // 12MB payload, exceeds 10MB limit
  7284. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7285. // Server may either return 413 or close the connection
  7286. if (res) {
  7287. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7288. } else {
  7289. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7290. }
  7291. }
  7292. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7293. // Test request without Content-Length header within 10MB limit
  7294. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7295. "Host: " +
  7296. std::string(HOST) + ":" +
  7297. std::to_string(PORT) +
  7298. "\r\n"
  7299. "Connection: close\r\n"
  7300. "\r\n";
  7301. // Add 1MB payload (within 10MB limit)
  7302. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7303. request_without_content_length += medium_payload;
  7304. std::string response;
  7305. bool result = send_request(5, request_without_content_length, &response);
  7306. if (result) {
  7307. // Should get a proper HTTP response for payloads within limit
  7308. if (response.length() > 10) {
  7309. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7310. "10MB limit";
  7311. } else {
  7312. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7313. "Content-Length)";
  7314. }
  7315. } else {
  7316. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7317. }
  7318. }
  7319. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7320. // Test request without Content-Length header exceeding 10MB limit
  7321. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7322. "Host: " +
  7323. std::string(HOST) + ":" +
  7324. std::to_string(PORT) +
  7325. "\r\n"
  7326. "Connection: close\r\n"
  7327. "\r\n";
  7328. // Add 12MB payload (exceeds 10MB limit)
  7329. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7330. request_without_content_length += large_payload;
  7331. std::string response;
  7332. bool result = send_request(10, request_without_content_length, &response);
  7333. if (!result) {
  7334. // Server should close connection due to payload limit
  7335. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7336. "(connection closed)";
  7337. } else {
  7338. // Check for error response
  7339. if (response.length() <= 10) {
  7340. SUCCEED()
  7341. << "Server closed connection for 12MB request exceeding 10MB limit";
  7342. } else {
  7343. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7344. response.find("Payload Too Large") != std::string::npos ||
  7345. response.find("400") != std::string::npos);
  7346. }
  7347. }
  7348. }
  7349. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7350. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7351. // path.
  7352. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7353. Server svr;
  7354. const size_t LIMIT = 64 * 1024; // 64KB
  7355. svr.set_payload_max_length(LIMIT);
  7356. size_t total = 0;
  7357. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7358. const ContentReader &content_reader) {
  7359. content_reader([&](const char * /*data*/, size_t len) {
  7360. total += len;
  7361. return true;
  7362. });
  7363. res.status = 200;
  7364. res.set_content("stream_ok", "text/plain");
  7365. });
  7366. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7367. auto se = detail::scope_exit([&] {
  7368. svr.stop();
  7369. thread.join();
  7370. ASSERT_FALSE(svr.is_running());
  7371. });
  7372. svr.wait_until_ready();
  7373. // Prepare 256KB raw data and gzip-compress it
  7374. std::string raw(256 * 1024, 'A');
  7375. std::string gz;
  7376. {
  7377. z_stream zs{};
  7378. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7379. Z_DEFAULT_STRATEGY);
  7380. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7381. zs.avail_in = static_cast<uInt>(raw.size());
  7382. char outbuf[4096];
  7383. int ret;
  7384. do {
  7385. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7386. zs.avail_out = sizeof(outbuf);
  7387. ret = deflate(&zs, Z_FINISH);
  7388. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7389. } while (ret != Z_STREAM_END);
  7390. deflateEnd(&zs);
  7391. }
  7392. Client cli(HOST, PORT);
  7393. cli.set_connection_timeout(std::chrono::seconds(5));
  7394. Headers headers = {{"Content-Encoding", "gzip"}};
  7395. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7396. "application/octet-stream");
  7397. ASSERT_TRUE(res);
  7398. // Server must reject oversized decompressed payloads with 413.
  7399. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7400. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7401. EXPECT_LE(total, LIMIT);
  7402. }
  7403. #endif
  7404. // Regression test for DoS vulnerability: a malicious server sending a response
  7405. // without Content-Length header must not cause unbounded memory consumption on
  7406. // the client side. The client should stop reading after a reasonable limit,
  7407. // similar to the server-side set_payload_max_length protection.
  7408. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7409. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7410. #ifndef _WIN32
  7411. signal(SIGPIPE, SIG_IGN);
  7412. #endif
  7413. auto server_thread = std::thread([] {
  7414. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7415. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7416. default_socket_options(srv);
  7417. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7418. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7419. sockaddr_in addr{};
  7420. addr.sin_family = AF_INET;
  7421. addr.sin_port = htons(PORT + 2);
  7422. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7423. int opt = 1;
  7424. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7425. #ifdef _WIN32
  7426. reinterpret_cast<const char *>(&opt),
  7427. #else
  7428. &opt,
  7429. #endif
  7430. sizeof(opt));
  7431. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7432. ::listen(srv, 1);
  7433. sockaddr_in cli_addr{};
  7434. socklen_t cli_len = sizeof(cli_addr);
  7435. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7436. if (cli != INVALID_SOCKET) {
  7437. char buf[4096];
  7438. ::recv(cli, buf, sizeof(buf), 0);
  7439. // Malicious response: no Content-Length, no chunked encoding
  7440. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7441. "Connection: close\r\n"
  7442. "\r\n";
  7443. ::send(cli,
  7444. #ifdef _WIN32
  7445. static_cast<const char *>(response_header.c_str()),
  7446. static_cast<int>(response_header.size()),
  7447. #else
  7448. response_header.c_str(), response_header.size(),
  7449. #endif
  7450. 0);
  7451. // Send 10MB of data
  7452. std::string chunk(64 * 1024, 'A');
  7453. size_t total_sent = 0;
  7454. while (total_sent < MALICIOUS_DATA_SIZE) {
  7455. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7456. auto sent = ::send(cli,
  7457. #ifdef _WIN32
  7458. static_cast<const char *>(chunk.c_str()),
  7459. static_cast<int>(to_send),
  7460. #else
  7461. chunk.c_str(), to_send,
  7462. #endif
  7463. 0);
  7464. if (sent <= 0) break;
  7465. total_sent += static_cast<size_t>(sent);
  7466. }
  7467. detail::close_socket(cli);
  7468. }
  7469. detail::close_socket(srv);
  7470. });
  7471. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7472. size_t total_read = 0;
  7473. {
  7474. Client cli("127.0.0.1", PORT + 2);
  7475. cli.set_read_timeout(5, 0);
  7476. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7477. auto stream = cli.open_stream("GET", "/malicious");
  7478. ASSERT_TRUE(stream.is_valid());
  7479. char buffer[64 * 1024];
  7480. ssize_t n;
  7481. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7482. total_read += static_cast<size_t>(n);
  7483. }
  7484. } // StreamHandle and Client destroyed here, closing the socket
  7485. server_thread.join();
  7486. // With set_payload_max_length, the client must stop reading before consuming
  7487. // all 10MB. The read loop should be cut off at or near the configured limit.
  7488. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7489. << "Client read " << total_read << " bytes, exceeding the configured "
  7490. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7491. }
  7492. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7493. // the entire response body without truncation.
  7494. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7495. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7496. #ifndef _WIN32
  7497. signal(SIGPIPE, SIG_IGN);
  7498. #endif
  7499. auto server_thread = std::thread([] {
  7500. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7501. default_socket_options(srv);
  7502. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7503. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7504. sockaddr_in addr{};
  7505. addr.sin_family = AF_INET;
  7506. addr.sin_port = htons(PORT + 2);
  7507. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7508. int opt = 1;
  7509. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7510. #ifdef _WIN32
  7511. reinterpret_cast<const char *>(&opt),
  7512. #else
  7513. &opt,
  7514. #endif
  7515. sizeof(opt));
  7516. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7517. ::listen(srv, 1);
  7518. sockaddr_in cli_addr{};
  7519. socklen_t cli_len = sizeof(cli_addr);
  7520. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7521. if (cli != INVALID_SOCKET) {
  7522. char buf[4096];
  7523. ::recv(cli, buf, sizeof(buf), 0);
  7524. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7525. "Connection: close\r\n"
  7526. "\r\n";
  7527. ::send(cli,
  7528. #ifdef _WIN32
  7529. static_cast<const char *>(response_header.c_str()),
  7530. static_cast<int>(response_header.size()),
  7531. #else
  7532. response_header.c_str(), response_header.size(),
  7533. #endif
  7534. 0);
  7535. std::string chunk(64 * 1024, 'A');
  7536. size_t total_sent = 0;
  7537. while (total_sent < DATA_SIZE) {
  7538. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7539. auto sent = ::send(cli,
  7540. #ifdef _WIN32
  7541. static_cast<const char *>(chunk.c_str()),
  7542. static_cast<int>(to_send),
  7543. #else
  7544. chunk.c_str(), to_send,
  7545. #endif
  7546. 0);
  7547. if (sent <= 0) break;
  7548. total_sent += static_cast<size_t>(sent);
  7549. }
  7550. #ifdef _WIN32
  7551. ::shutdown(cli, SD_SEND);
  7552. #else
  7553. ::shutdown(cli, SHUT_WR);
  7554. #endif
  7555. // Drain until the client closes its end, ensuring all data is delivered
  7556. char drain[1024];
  7557. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7558. detail::close_socket(cli);
  7559. }
  7560. detail::close_socket(srv);
  7561. });
  7562. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7563. size_t total_read = 0;
  7564. {
  7565. Client cli("127.0.0.1", PORT + 2);
  7566. cli.set_read_timeout(5, 0);
  7567. cli.set_payload_max_length(0); // 0 means no limit
  7568. auto stream = cli.open_stream("GET", "/data");
  7569. ASSERT_TRUE(stream.is_valid());
  7570. char buffer[64 * 1024];
  7571. ssize_t n;
  7572. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7573. total_read += static_cast<size_t>(n);
  7574. }
  7575. }
  7576. server_thread.join();
  7577. EXPECT_EQ(total_read, DATA_SIZE)
  7578. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7579. << " bytes without truncation, but only read " << total_read << " bytes.";
  7580. }
  7581. // Verify that content_receiver bypasses the default payload_max_length,
  7582. // allowing streaming downloads larger than 100MB without requiring an explicit
  7583. // set_payload_max_length call.
  7584. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7585. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7586. #ifndef _WIN32
  7587. signal(SIGPIPE, SIG_IGN);
  7588. #endif
  7589. auto server_thread = std::thread([] {
  7590. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7591. default_socket_options(srv);
  7592. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7593. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7594. sockaddr_in addr{};
  7595. addr.sin_family = AF_INET;
  7596. addr.sin_port = htons(PORT + 2);
  7597. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7598. int opt = 1;
  7599. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7600. #ifdef _WIN32
  7601. reinterpret_cast<const char *>(&opt),
  7602. #else
  7603. &opt,
  7604. #endif
  7605. sizeof(opt));
  7606. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7607. ::listen(srv, 1);
  7608. sockaddr_in cli_addr{};
  7609. socklen_t cli_len = sizeof(cli_addr);
  7610. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7611. if (cli != INVALID_SOCKET) {
  7612. char buf[4096];
  7613. ::recv(cli, buf, sizeof(buf), 0);
  7614. // Response with Content-Length larger than default 100MB limit
  7615. auto content_length = std::to_string(DATA_SIZE);
  7616. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7617. "Content-Length: " +
  7618. content_length +
  7619. "\r\n"
  7620. "Connection: close\r\n"
  7621. "\r\n";
  7622. ::send(cli,
  7623. #ifdef _WIN32
  7624. static_cast<const char *>(response_header.c_str()),
  7625. static_cast<int>(response_header.size()),
  7626. #else
  7627. response_header.c_str(), response_header.size(),
  7628. #endif
  7629. 0);
  7630. std::string chunk(64 * 1024, 'A');
  7631. size_t total_sent = 0;
  7632. while (total_sent < DATA_SIZE) {
  7633. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7634. auto sent = ::send(cli,
  7635. #ifdef _WIN32
  7636. static_cast<const char *>(chunk.c_str()),
  7637. static_cast<int>(to_send),
  7638. #else
  7639. chunk.c_str(), to_send,
  7640. #endif
  7641. 0);
  7642. if (sent <= 0) break;
  7643. total_sent += static_cast<size_t>(sent);
  7644. }
  7645. detail::close_socket(cli);
  7646. }
  7647. detail::close_socket(srv);
  7648. });
  7649. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7650. size_t total_received = 0;
  7651. {
  7652. Client cli("127.0.0.1", PORT + 2);
  7653. cli.set_read_timeout(10, 0);
  7654. // Do NOT call set_payload_max_length — use the default 100MB limit
  7655. auto res =
  7656. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7657. total_received += data_length;
  7658. return true;
  7659. });
  7660. ASSERT_TRUE(res);
  7661. EXPECT_EQ(StatusCode::OK_200, res->status);
  7662. }
  7663. server_thread.join();
  7664. EXPECT_EQ(total_received, DATA_SIZE)
  7665. << "With content_receiver, the client should read all " << DATA_SIZE
  7666. << " bytes despite the default 100MB payload_max_length, but only read "
  7667. << total_received << " bytes.";
  7668. }
  7669. // Verify that an explicit set_payload_max_length smaller than the response is
  7670. // enforced even when a content_receiver is used.
  7671. TEST(ClientVulnerabilityTest,
  7672. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7673. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7674. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7675. #ifndef _WIN32
  7676. signal(SIGPIPE, SIG_IGN);
  7677. #endif
  7678. auto server_thread = std::thread([] {
  7679. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7680. default_socket_options(srv);
  7681. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7682. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7683. sockaddr_in addr{};
  7684. addr.sin_family = AF_INET;
  7685. addr.sin_port = htons(PORT + 2);
  7686. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7687. int opt = 1;
  7688. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7689. #ifdef _WIN32
  7690. reinterpret_cast<const char *>(&opt),
  7691. #else
  7692. &opt,
  7693. #endif
  7694. sizeof(opt));
  7695. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7696. ::listen(srv, 1);
  7697. sockaddr_in cli_addr{};
  7698. socklen_t cli_len = sizeof(cli_addr);
  7699. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7700. if (cli != INVALID_SOCKET) {
  7701. char buf[4096];
  7702. ::recv(cli, buf, sizeof(buf), 0);
  7703. auto content_length = std::to_string(DATA_SIZE);
  7704. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7705. "Content-Length: " +
  7706. content_length +
  7707. "\r\n"
  7708. "Connection: close\r\n"
  7709. "\r\n";
  7710. ::send(cli,
  7711. #ifdef _WIN32
  7712. static_cast<const char *>(response_header.c_str()),
  7713. static_cast<int>(response_header.size()),
  7714. #else
  7715. response_header.c_str(), response_header.size(),
  7716. #endif
  7717. 0);
  7718. std::string chunk(64 * 1024, 'A');
  7719. size_t total_sent = 0;
  7720. while (total_sent < DATA_SIZE) {
  7721. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7722. auto sent = ::send(cli,
  7723. #ifdef _WIN32
  7724. static_cast<const char *>(chunk.c_str()),
  7725. static_cast<int>(to_send),
  7726. #else
  7727. chunk.c_str(), to_send,
  7728. #endif
  7729. 0);
  7730. if (sent <= 0) break;
  7731. total_sent += static_cast<size_t>(sent);
  7732. }
  7733. detail::close_socket(cli);
  7734. }
  7735. detail::close_socket(srv);
  7736. });
  7737. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7738. size_t total_received = 0;
  7739. {
  7740. Client cli("127.0.0.1", PORT + 2);
  7741. cli.set_read_timeout(10, 0);
  7742. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7743. auto res =
  7744. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7745. total_received += data_length;
  7746. return true;
  7747. });
  7748. // Should fail because 200MB exceeds the explicit 150MB limit
  7749. EXPECT_FALSE(res);
  7750. }
  7751. server_thread.join();
  7752. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7753. << "Client with content_receiver should respect the explicit "
  7754. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7755. << total_received << " bytes.";
  7756. }
  7757. // Verify that an explicit set_payload_max_length larger than the response
  7758. // allows the content_receiver to read all data successfully.
  7759. TEST(ClientVulnerabilityTest,
  7760. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7761. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7762. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7763. #ifndef _WIN32
  7764. signal(SIGPIPE, SIG_IGN);
  7765. #endif
  7766. auto server_thread = std::thread([] {
  7767. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7768. default_socket_options(srv);
  7769. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7770. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7771. sockaddr_in addr{};
  7772. addr.sin_family = AF_INET;
  7773. addr.sin_port = htons(PORT + 2);
  7774. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7775. int opt = 1;
  7776. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7777. #ifdef _WIN32
  7778. reinterpret_cast<const char *>(&opt),
  7779. #else
  7780. &opt,
  7781. #endif
  7782. sizeof(opt));
  7783. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7784. ::listen(srv, 1);
  7785. sockaddr_in cli_addr{};
  7786. socklen_t cli_len = sizeof(cli_addr);
  7787. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7788. if (cli != INVALID_SOCKET) {
  7789. char buf[4096];
  7790. ::recv(cli, buf, sizeof(buf), 0);
  7791. auto content_length = std::to_string(DATA_SIZE);
  7792. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7793. "Content-Length: " +
  7794. content_length +
  7795. "\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. std::string chunk(64 * 1024, 'A');
  7807. size_t total_sent = 0;
  7808. while (total_sent < DATA_SIZE) {
  7809. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7810. auto sent = ::send(cli,
  7811. #ifdef _WIN32
  7812. static_cast<const char *>(chunk.c_str()),
  7813. static_cast<int>(to_send),
  7814. #else
  7815. chunk.c_str(), to_send,
  7816. #endif
  7817. 0);
  7818. if (sent <= 0) break;
  7819. total_sent += static_cast<size_t>(sent);
  7820. }
  7821. #ifdef _WIN32
  7822. ::shutdown(cli, SD_SEND);
  7823. #else
  7824. ::shutdown(cli, SHUT_WR);
  7825. #endif
  7826. char drain[1024];
  7827. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7828. detail::close_socket(cli);
  7829. }
  7830. detail::close_socket(srv);
  7831. });
  7832. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7833. size_t total_received = 0;
  7834. {
  7835. Client cli("127.0.0.1", PORT + 2);
  7836. cli.set_read_timeout(10, 0);
  7837. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7838. auto res =
  7839. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7840. total_received += data_length;
  7841. return true;
  7842. });
  7843. ASSERT_TRUE(res);
  7844. EXPECT_EQ(StatusCode::OK_200, res->status);
  7845. }
  7846. server_thread.join();
  7847. EXPECT_EQ(total_received, DATA_SIZE)
  7848. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7849. << " bytes (larger than " << DATA_SIZE
  7850. << " bytes response), content_receiver should read all data, but only "
  7851. "read "
  7852. << total_received << " bytes.";
  7853. }
  7854. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7855. // Regression test for "zip bomb" attack on the client side: a malicious server
  7856. // sends a small gzip-compressed response that decompresses to a huge payload.
  7857. // The client must enforce payload_max_length on the decompressed size.
  7858. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7859. constexpr size_t DECOMPRESSED_SIZE =
  7860. 10 * 1024 * 1024; // 10MB after decompression
  7861. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7862. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7863. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7864. std::string compressed;
  7865. {
  7866. httplib::detail::gzip_compressor compressor;
  7867. bool ok =
  7868. compressor.compress(uncompressed.data(), uncompressed.size(),
  7869. /*last=*/true, [&](const char *buf, size_t len) {
  7870. compressed.append(buf, len);
  7871. return true;
  7872. });
  7873. ASSERT_TRUE(ok);
  7874. }
  7875. // Sanity: compressed data should be much smaller than the decompressed size
  7876. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7877. #ifndef _WIN32
  7878. signal(SIGPIPE, SIG_IGN);
  7879. #endif
  7880. // Set up the listening socket in the main thread so the server is guaranteed
  7881. // to be ready before the client connects (eliminates race condition).
  7882. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7883. default_socket_options(srv);
  7884. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7885. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7886. sockaddr_in addr{};
  7887. addr.sin_family = AF_INET;
  7888. addr.sin_port = htons(PORT + 3);
  7889. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7890. int opt = 1;
  7891. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7892. #ifdef _WIN32
  7893. reinterpret_cast<const char *>(&opt),
  7894. #else
  7895. &opt,
  7896. #endif
  7897. sizeof(opt));
  7898. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7899. ASSERT_EQ(0, ::listen(srv, 1));
  7900. auto server_thread = std::thread([&compressed, srv] {
  7901. sockaddr_in cli_addr{};
  7902. socklen_t cli_len = sizeof(cli_addr);
  7903. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7904. if (cli != INVALID_SOCKET) {
  7905. // Read the full HTTP request (until \r\n\r\n)
  7906. char buf[4096];
  7907. size_t total = 0;
  7908. while (total < sizeof(buf)) {
  7909. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7910. if (n <= 0) break;
  7911. total += static_cast<size_t>(n);
  7912. // Check for end of headers
  7913. if (total >= 4) {
  7914. std::string req(buf, total);
  7915. if (req.find("\r\n\r\n") != std::string::npos) break;
  7916. }
  7917. }
  7918. // Malicious response: gzip-compressed body, no Content-Length
  7919. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7920. "Content-Encoding: gzip\r\n"
  7921. "Connection: close\r\n"
  7922. "\r\n";
  7923. ::send(cli,
  7924. #ifdef _WIN32
  7925. static_cast<const char *>(response_header.c_str()),
  7926. static_cast<int>(response_header.size()),
  7927. #else
  7928. response_header.c_str(), response_header.size(),
  7929. #endif
  7930. 0);
  7931. // Send the compressed payload (small on the wire, huge when decompressed)
  7932. size_t total_sent = 0;
  7933. while (total_sent < compressed.size()) {
  7934. auto to_send = std::min(compressed.size() - total_sent,
  7935. static_cast<size_t>(64 * 1024));
  7936. auto sent =
  7937. ::send(cli,
  7938. #ifdef _WIN32
  7939. static_cast<const char *>(compressed.c_str() + total_sent),
  7940. static_cast<int>(to_send),
  7941. #else
  7942. compressed.c_str() + total_sent, to_send,
  7943. #endif
  7944. 0);
  7945. if (sent <= 0) break;
  7946. total_sent += static_cast<size_t>(sent);
  7947. }
  7948. detail::close_socket(cli);
  7949. }
  7950. });
  7951. auto se = detail::scope_exit([&] {
  7952. detail::close_socket(srv);
  7953. server_thread.join();
  7954. });
  7955. size_t total_decompressed = 0;
  7956. {
  7957. Client cli("127.0.0.1", PORT + 3);
  7958. cli.set_read_timeout(5, 0);
  7959. cli.set_decompress(true);
  7960. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7961. auto stream = cli.open_stream("GET", "/zipbomb");
  7962. ASSERT_TRUE(stream.is_valid());
  7963. char buffer[64 * 1024];
  7964. ssize_t n;
  7965. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7966. total_decompressed += static_cast<size_t>(n);
  7967. }
  7968. }
  7969. // The decompressed size must be capped by payload_max_length. Without
  7970. // protection, the client would decompress the full 10MB from a tiny
  7971. // compressed payload, enabling a zip bomb DoS attack.
  7972. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7973. << "Client decompressed " << total_decompressed
  7974. << " bytes from a gzip response. The decompressed size should be "
  7975. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7976. }
  7977. #endif
  7978. TEST(HostAndPortPropertiesTest, NoSSL) {
  7979. httplib::Client cli("www.google.com", 1234);
  7980. ASSERT_EQ("www.google.com", cli.host());
  7981. ASSERT_EQ(1234, cli.port());
  7982. }
  7983. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7984. httplib::Client cli("www.google.com:1234");
  7985. ASSERT_EQ("www.google.com", cli.host());
  7986. ASSERT_EQ(1234, cli.port());
  7987. }
  7988. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  7989. // Port number that overflows int — should not crash, client becomes invalid
  7990. httplib::Client cli("http://www.google.com:99999999999999999999");
  7991. ASSERT_FALSE(cli.is_valid());
  7992. }
  7993. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  7994. // Port 99999 exceeds valid range (1-65535) — should not crash
  7995. httplib::Client cli("http://www.google.com:99999");
  7996. ASSERT_FALSE(cli.is_valid());
  7997. }
  7998. #ifdef CPPHTTPLIB_SSL_ENABLED
  7999. TEST(HostAndPortPropertiesTest, SSL) {
  8000. httplib::SSLClient cli("www.google.com");
  8001. ASSERT_EQ("www.google.com", cli.host());
  8002. ASSERT_EQ(443, cli.port());
  8003. }
  8004. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8005. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8006. std::string cert;
  8007. read_file(CA_CERT_FILE, cert);
  8008. httplib::SSLClient httplib_client("www.google.com");
  8009. // Load CA store first time
  8010. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8011. // Load CA store second time (update)
  8012. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8013. // Verify client is still valid and can make connections
  8014. httplib_client.enable_server_certificate_verification(true);
  8015. auto res = httplib_client.Get("/");
  8016. ASSERT_TRUE(res);
  8017. // Google may return 200 or 301 depending on various factors
  8018. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8019. res->status == StatusCode::MovedPermanently_301);
  8020. }
  8021. TEST(SSLClientTest, ServerNameIndication_Online) {
  8022. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8023. auto host = "httpcan.org";
  8024. auto path = std::string{"/get"};
  8025. #else
  8026. auto host = "nghttp2.org";
  8027. auto path = std::string{"/httpbin/get"};
  8028. #endif
  8029. SSLClient cli(host, 443);
  8030. auto res = cli.Get(path);
  8031. ASSERT_TRUE(res);
  8032. ASSERT_EQ(StatusCode::OK_200, res->status);
  8033. }
  8034. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8035. // Use a site that will cause SSL verification failure due to self-signed cert
  8036. SSLClient cli("self-signed.badssl.com", 443);
  8037. cli.enable_server_certificate_verification(true);
  8038. auto res = cli.Get("/");
  8039. ASSERT_TRUE(!res);
  8040. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8041. // Verify backend error is captured for SSLServerVerification
  8042. // This occurs when certificate verification fails
  8043. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8044. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8045. EXPECT_NE(0UL, res.ssl_backend_error());
  8046. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8047. // For OpenSSL, ssl_error is 0 for verification errors
  8048. EXPECT_EQ(0, res.ssl_error());
  8049. #if !defined(_WIN32) || \
  8050. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8051. // On non-Windows or when Windows Schannel is disabled, the error comes
  8052. // from OpenSSL's verification
  8053. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8054. res.ssl_backend_error());
  8055. #endif
  8056. #endif
  8057. }
  8058. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8059. // Use a site where hostname doesn't match the certificate
  8060. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8061. SSLClient cli("wrong.host.badssl.com", 443);
  8062. cli.enable_server_certificate_verification(true);
  8063. cli.enable_server_hostname_verification(true);
  8064. auto res = cli.Get("/");
  8065. ASSERT_TRUE(!res);
  8066. // The error type depends on when hostname verification occurs:
  8067. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8068. // - Mbed TLS: SSLServerVerification (during handshake)
  8069. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8070. res.error() == Error::SSLServerVerification);
  8071. // Verify backend error is captured for hostname verification failure
  8072. EXPECT_NE(0UL, res.ssl_backend_error());
  8073. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8074. // For OpenSSL, ssl_error is 0 for verification errors
  8075. EXPECT_EQ(0, res.ssl_error());
  8076. #if !defined(_WIN32) || \
  8077. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8078. // On non-Windows or when Windows Schannel is disabled, the error comes
  8079. // from OpenSSL's hostname verification
  8080. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8081. res.ssl_backend_error());
  8082. #endif
  8083. #endif
  8084. }
  8085. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8086. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8087. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8088. SSLClient cli("www.google.com", 443);
  8089. cli.enable_server_certificate_verification(true);
  8090. auto res = cli.Get("/");
  8091. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8092. }
  8093. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8094. SSLClient cli("www.google.com", 443);
  8095. cli.enable_server_certificate_verification(true);
  8096. cli.enable_windows_certificate_verification(false);
  8097. auto res = cli.Get("/");
  8098. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8099. }
  8100. #endif
  8101. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8102. Client cli("https://google.com");
  8103. auto res = cli.Get("/");
  8104. ASSERT_TRUE(res);
  8105. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8106. }
  8107. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8108. SSLClient cli("google.com");
  8109. cli.set_ca_cert_path(CA_CERT_FILE);
  8110. auto res = cli.Get("/");
  8111. ASSERT_TRUE(res);
  8112. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8113. }
  8114. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8115. SSLClient cli("google.com");
  8116. cli.enable_server_certificate_verification(true);
  8117. cli.set_ca_cert_path("hello");
  8118. auto res = cli.Get("/");
  8119. ASSERT_TRUE(!res);
  8120. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8121. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8122. // should be set
  8123. EXPECT_EQ(0, res.ssl_error());
  8124. // Verify backend error is captured for SSLLoadingCerts
  8125. // This error occurs when loading CA certificates fails
  8126. EXPECT_NE(0UL, res.ssl_backend_error());
  8127. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8128. // OpenSSL specific error codes:
  8129. // > openssl errstr 0x80000002
  8130. // error:80000002:system library::No such file or directory
  8131. // > openssl errstr 0xA000126
  8132. // error:0A000126:SSL routines::unexpected eof while reading
  8133. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8134. res.ssl_backend_error() == 0xA000126);
  8135. #endif
  8136. }
  8137. TEST(SSLClientTest, ServerCertificateVerification4) {
  8138. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8139. ASSERT_TRUE(svr.is_valid());
  8140. svr.Get("/test", [&](const Request &, Response &res) {
  8141. res.set_content("test", "text/plain");
  8142. svr.stop();
  8143. ASSERT_TRUE(true);
  8144. });
  8145. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8146. auto se = detail::scope_exit([&] {
  8147. t.join();
  8148. ASSERT_FALSE(svr.is_running());
  8149. });
  8150. svr.wait_until_ready();
  8151. SSLClient cli("127.0.0.1", PORT);
  8152. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8153. cli.enable_server_certificate_verification(true);
  8154. cli.set_connection_timeout(30);
  8155. auto res = cli.Get("/test");
  8156. ASSERT_TRUE(res);
  8157. ASSERT_EQ(StatusCode::OK_200, res->status);
  8158. }
  8159. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8160. std::string cert;
  8161. read_file(CA_CERT_FILE, cert);
  8162. SSLClient cli("google.com");
  8163. cli.load_ca_cert_store(cert.data(), cert.size());
  8164. const auto res = cli.Get("/");
  8165. ASSERT_TRUE(res);
  8166. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8167. }
  8168. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8169. // clang-format off
  8170. static constexpr char cert[] =
  8171. "GlobalSign Root CA\n"
  8172. "==================\n"
  8173. "-----BEGIN CERTIFICATE-----\n"
  8174. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8175. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8176. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8177. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8178. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8179. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8180. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8181. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8182. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8183. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8184. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8185. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8186. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8187. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8188. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8189. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8190. "-----END CERTIFICATE-----\n";
  8191. // clang-format on
  8192. SSLClient cli("google.com");
  8193. cli.load_ca_cert_store(cert, sizeof(cert));
  8194. const auto res = cli.Get("/");
  8195. ASSERT_TRUE(res);
  8196. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8197. }
  8198. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8199. SSLClient cli("www.youtube.com");
  8200. cli.set_ca_cert_path(CA_CERT_FILE);
  8201. cli.enable_server_certificate_verification(true);
  8202. cli.set_follow_location(true);
  8203. auto res = cli.Get("/");
  8204. ASSERT_TRUE(res);
  8205. ASSERT_EQ(StatusCode::OK_200, res->status);
  8206. }
  8207. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8208. SSLClient cli("wWw.YouTube.Com");
  8209. cli.set_ca_cert_path(CA_CERT_FILE);
  8210. cli.enable_server_certificate_verification(true);
  8211. cli.enable_server_hostname_verification(true);
  8212. cli.set_follow_location(true);
  8213. auto res = cli.Get("/");
  8214. ASSERT_TRUE(res);
  8215. ASSERT_EQ(StatusCode::OK_200, res->status);
  8216. }
  8217. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8218. SSLClient cli("gOoGlE.COm");
  8219. cli.enable_server_certificate_verification(true);
  8220. cli.enable_server_hostname_verification(true);
  8221. cli.set_follow_location(true);
  8222. auto res = cli.Get("/");
  8223. ASSERT_TRUE(res);
  8224. ASSERT_EQ(StatusCode::OK_200, res->status);
  8225. }
  8226. TEST(SSLClientTest, Issue2004_Online) {
  8227. Client client("https://google.com");
  8228. client.set_follow_location(true);
  8229. auto res = client.Get("/");
  8230. ASSERT_TRUE(res);
  8231. ASSERT_EQ(StatusCode::OK_200, res->status);
  8232. auto body = res->body;
  8233. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8234. }
  8235. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8236. // Create SSLClient with invalid cert/key to make is_valid() return false
  8237. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8238. "nonexistent_key.pem");
  8239. // is_valid() should be false due to cert loading failure
  8240. ASSERT_FALSE(cli.is_valid());
  8241. auto res = cli.Get("/");
  8242. ASSERT_FALSE(res);
  8243. EXPECT_EQ(Error::SSLConnection, res.error());
  8244. }
  8245. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8246. // Test for Issue #2251: SSL error not properly reported when client cert
  8247. // and key paths are swapped or mismatched
  8248. // This simulates the scenario where user accidentally swaps the cert and key
  8249. // files
  8250. // Using client cert file as private key and vice versa (completely wrong)
  8251. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8252. // Should fail validation due to cert/key mismatch
  8253. ASSERT_FALSE(cli.is_valid());
  8254. // Attempt to make a request should fail with proper error
  8255. auto res = cli.Get("/");
  8256. ASSERT_FALSE(res);
  8257. EXPECT_EQ(Error::SSLConnection, res.error());
  8258. // SSL error should be recorded in the Result object (this is the key fix for
  8259. // Issue #2251)
  8260. auto backend_error = res.ssl_backend_error();
  8261. EXPECT_NE(0u, backend_error);
  8262. }
  8263. // Tests cert/key mismatch detection at the TLS context level
  8264. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8265. // Test that using mismatched cert/key causes connection failure.
  8266. // We verify this at the SSLClient level rather than through internal
  8267. // TLS API functions.
  8268. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8269. cli.enable_server_certificate_verification(false);
  8270. cli.set_connection_timeout(2);
  8271. // The mismatch should cause a connection or handshake error
  8272. auto res = cli.Get("/test");
  8273. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8274. // Either way, the request should fail
  8275. EXPECT_FALSE(res);
  8276. }
  8277. #endif
  8278. #if 0
  8279. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8280. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8281. ASSERT_TRUE(cli != nullptr);
  8282. cli->set_address_family(AF_INET6);
  8283. cli->set_interface("en0");
  8284. auto res = cli->Get("/get");
  8285. ASSERT_TRUE(res);
  8286. ASSERT_EQ(StatusCode::OK_200, res->status);
  8287. }
  8288. #endif
  8289. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8290. #ifdef CPPHTTPLIB_SSL_ENABLED
  8291. void ClientCertPresent(
  8292. const std::string &client_cert_file,
  8293. const std::string &client_private_key_file,
  8294. const std::string &client_encrypted_private_key_pass = std::string()) {
  8295. using namespace httplib::tls;
  8296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8297. CLIENT_CA_CERT_DIR);
  8298. ASSERT_TRUE(svr.is_valid());
  8299. svr.Get("/test", [&](const Request &req, Response &res) {
  8300. res.set_content("test", "text/plain");
  8301. auto cert = req.peer_cert();
  8302. ASSERT_TRUE(static_cast<bool>(cert));
  8303. std::string common_name = cert.subject_cn();
  8304. EXPECT_EQ("Common Name", common_name);
  8305. });
  8306. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8307. auto se = detail::scope_exit([&] {
  8308. svr.stop();
  8309. t.join();
  8310. ASSERT_FALSE(svr.is_running());
  8311. });
  8312. svr.wait_until_ready();
  8313. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8314. client_encrypted_private_key_pass);
  8315. cli.enable_server_certificate_verification(false);
  8316. cli.set_connection_timeout(30);
  8317. auto res = cli.Get("/test");
  8318. ASSERT_TRUE(res);
  8319. ASSERT_EQ(StatusCode::OK_200, res->status);
  8320. }
  8321. TEST(SSLClientServerTest, ClientCertPresent) {
  8322. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8323. }
  8324. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8325. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8326. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8327. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8328. }
  8329. // PEM memory-based constructor tests (works with all TLS backends)
  8330. void PemMemoryClientCertPresent(
  8331. const std::string &client_cert_file,
  8332. const std::string &client_private_key_file,
  8333. const std::string &client_encrypted_private_key_pass = std::string()) {
  8334. // Read PEM files into memory
  8335. std::string server_cert_pem, server_key_pem;
  8336. std::string client_ca_pem;
  8337. std::string client_cert_pem, client_key_pem;
  8338. read_file(SERVER_CERT_FILE, server_cert_pem);
  8339. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8340. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8341. read_file(client_cert_file, client_cert_pem);
  8342. read_file(client_private_key_file, client_key_pem);
  8343. // Create server with PEM memory
  8344. SSLServer::PemMemory server_pem = {
  8345. server_cert_pem.c_str(),
  8346. server_cert_pem.size(),
  8347. server_key_pem.c_str(),
  8348. server_key_pem.size(),
  8349. client_ca_pem.c_str(),
  8350. client_ca_pem.size(),
  8351. nullptr // no password for server key
  8352. };
  8353. SSLServer svr(server_pem);
  8354. ASSERT_TRUE(svr.is_valid());
  8355. svr.Get("/test", [&](const Request &, Response &res) {
  8356. res.set_content("test", "text/plain");
  8357. });
  8358. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8359. auto se = detail::scope_exit([&] {
  8360. svr.stop();
  8361. t.join();
  8362. ASSERT_FALSE(svr.is_running());
  8363. });
  8364. svr.wait_until_ready();
  8365. // Create client with PEM memory
  8366. const char *password = client_encrypted_private_key_pass.empty()
  8367. ? nullptr
  8368. : client_encrypted_private_key_pass.c_str();
  8369. SSLClient::PemMemory client_pem = {
  8370. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8371. client_key_pem.size(), password};
  8372. SSLClient cli(HOST, PORT, client_pem);
  8373. cli.enable_server_certificate_verification(false);
  8374. cli.set_connection_timeout(30);
  8375. auto res = cli.Get("/test");
  8376. ASSERT_TRUE(res);
  8377. ASSERT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8380. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8381. }
  8382. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8383. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8384. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8385. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8386. }
  8387. TEST(SSLClientServerTest, ClientCertMissing) {
  8388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8389. CLIENT_CA_CERT_DIR);
  8390. ASSERT_TRUE(svr.is_valid());
  8391. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8392. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8393. auto se = detail::scope_exit([&] {
  8394. svr.stop();
  8395. t.join();
  8396. ASSERT_FALSE(svr.is_running());
  8397. });
  8398. svr.wait_until_ready();
  8399. SSLClient cli(HOST, PORT);
  8400. cli.set_connection_timeout(30);
  8401. auto res = cli.Get("/test");
  8402. ASSERT_TRUE(!res);
  8403. // When client cert is missing and server requires it, connection fails
  8404. // Error type depends on backend implementation
  8405. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8406. res.error() == Error::SSLConnection);
  8407. // Verify backend error is captured
  8408. // Note: This test may have different error codes depending on the exact
  8409. // verification failure
  8410. EXPECT_NE(0UL, res.ssl_backend_error());
  8411. }
  8412. TEST(SSLClientServerTest, TrustDirOptional) {
  8413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8414. ASSERT_TRUE(svr.is_valid());
  8415. svr.Get("/test", [&](const Request &, Response &res) {
  8416. res.set_content("test", "text/plain");
  8417. });
  8418. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8419. auto se = detail::scope_exit([&] {
  8420. svr.stop();
  8421. t.join();
  8422. ASSERT_FALSE(svr.is_running());
  8423. });
  8424. svr.wait_until_ready();
  8425. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8426. cli.enable_server_certificate_verification(false);
  8427. cli.set_connection_timeout(30);
  8428. auto res = cli.Get("/test");
  8429. ASSERT_TRUE(res);
  8430. ASSERT_EQ(StatusCode::OK_200, res->status);
  8431. }
  8432. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8433. class NoListenSSLServer : public SSLServer {
  8434. public:
  8435. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8436. const char *client_ca_cert_file_path,
  8437. const char *client_ca_cert_dir_path = nullptr)
  8438. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8439. client_ca_cert_dir_path),
  8440. stop_(false) {}
  8441. std::atomic_bool stop_;
  8442. private:
  8443. bool process_and_close_socket(socket_t /*sock*/) override {
  8444. // Don't create SSL context
  8445. while (!stop_.load()) {
  8446. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8447. }
  8448. return true;
  8449. }
  8450. };
  8451. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8452. CLIENT_CA_CERT_FILE);
  8453. ASSERT_TRUE(svr.is_valid());
  8454. svr.Get("/test", [&](const Request &, Response &res) {
  8455. res.set_content("test", "text/plain");
  8456. });
  8457. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8458. auto se = detail::scope_exit([&] {
  8459. svr.stop_ = true;
  8460. svr.stop();
  8461. t.join();
  8462. ASSERT_FALSE(svr.is_running());
  8463. });
  8464. svr.wait_until_ready();
  8465. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8466. cli.enable_server_certificate_verification(false);
  8467. cli.set_connection_timeout(1);
  8468. auto res = cli.Get("/test");
  8469. ASSERT_TRUE(!res);
  8470. EXPECT_EQ(Error::SSLConnection, res.error());
  8471. // Timeout results in WantRead error code (maps to backend-specific value)
  8472. EXPECT_NE(0, res.ssl_error());
  8473. }
  8474. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8475. // Test SSLServer with client certificate verification using the standard
  8476. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8478. CLIENT_CA_CERT_DIR);
  8479. ASSERT_TRUE(svr.is_valid());
  8480. svr.Get("/test", [&](const Request &req, Response &res) {
  8481. res.set_content("test", "text/plain");
  8482. auto cert = req.peer_cert();
  8483. ASSERT_TRUE(static_cast<bool>(cert));
  8484. auto common_name = cert.subject_cn();
  8485. EXPECT_EQ("Common Name", common_name);
  8486. });
  8487. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8488. auto se = detail::scope_exit([&] {
  8489. svr.stop();
  8490. t.join();
  8491. ASSERT_FALSE(svr.is_running());
  8492. });
  8493. svr.wait_until_ready();
  8494. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8495. cli.enable_server_certificate_verification(false);
  8496. cli.set_connection_timeout(30);
  8497. auto res = cli.Get("/test");
  8498. ASSERT_TRUE(res);
  8499. ASSERT_EQ(StatusCode::OK_200, res->status);
  8500. }
  8501. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8502. // Verifies that wildcard matching and exact matching work consistently
  8503. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8504. using namespace httplib::tls;
  8505. // We need a running server to test against
  8506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8507. ASSERT_TRUE(svr.is_valid());
  8508. svr.Get("/test", [](const Request &, Response &res) {
  8509. res.set_content("ok", "text/plain");
  8510. });
  8511. thread t([&]() { svr.listen(HOST, PORT); });
  8512. auto se = detail::scope_exit([&] {
  8513. svr.stop();
  8514. t.join();
  8515. });
  8516. svr.wait_until_ready();
  8517. bool verify_callback_called = false;
  8518. bool verify_result_wrong = false;
  8519. SSLClient cli(HOST, PORT);
  8520. cli.enable_server_certificate_verification(true);
  8521. cli.set_ca_cert_path(CA_CERT_FILE);
  8522. cli.set_connection_timeout(5);
  8523. // Note: Test certificate has CN="Common Name", not "localhost"
  8524. bool verify_result_cn = false;
  8525. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8526. verify_callback_called = true;
  8527. if (!ctx.cert) return false;
  8528. // Test 1: "Common Name" should match (our test server cert CN)
  8529. verify_result_cn = ctx.check_hostname("Common Name");
  8530. // Test 2: wrong hostname should not match
  8531. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8532. return true; // Accept for the purpose of this test
  8533. });
  8534. auto res = cli.Get("/test");
  8535. // The request may succeed or fail depending on cert configuration
  8536. // but the callback should have been called
  8537. ASSERT_TRUE(verify_callback_called)
  8538. << "Verify callback should have been called";
  8539. // CN="Common Name" should match our test certificate
  8540. EXPECT_TRUE(verify_result_cn)
  8541. << "verify_hostname should match 'Common Name' (certificate CN)";
  8542. // Wrong hostname should not match
  8543. EXPECT_FALSE(verify_result_wrong)
  8544. << "verify_hostname should not match 'wronghost.example.com'";
  8545. }
  8546. #endif
  8547. // mbedTLS-specific callback constructor test
  8548. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8549. #ifdef CPPHTTPLIB_SSL_ENABLED
  8550. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8552. ASSERT_TRUE(svr.is_valid());
  8553. // Set up a handler to verify client certificate is present
  8554. bool client_cert_verified = false;
  8555. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8556. // Verify that client certificate was provided
  8557. client_cert_verified = true;
  8558. res.set_content("success", "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. ASSERT_FALSE(svr.is_running());
  8565. });
  8566. svr.wait_until_ready();
  8567. // Client with certificate
  8568. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8569. cli.enable_server_certificate_verification(false);
  8570. cli.set_connection_timeout(30);
  8571. auto res = cli.Get("/test");
  8572. ASSERT_TRUE(res);
  8573. ASSERT_EQ(StatusCode::OK_200, res->status);
  8574. ASSERT_TRUE(client_cert_verified);
  8575. EXPECT_EQ("success", res->body);
  8576. }
  8577. #endif
  8578. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8579. // backends
  8580. #ifdef CPPHTTPLIB_SSL_ENABLED
  8581. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8582. using namespace httplib::tls;
  8583. // Test that when client CA cert file is provided,
  8584. // the server properly requests and validates client certificates
  8585. // Create a server with client authentication
  8586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8587. ASSERT_TRUE(svr.is_valid());
  8588. bool handler_called = false;
  8589. svr.Get("/test", [&](const Request &req, Response &res) {
  8590. handler_called = true;
  8591. // Verify that a client certificate was provided
  8592. auto cert = req.peer_cert();
  8593. ASSERT_TRUE(static_cast<bool>(cert));
  8594. // Get the issuer name
  8595. std::string issuer_str = cert.issuer_name();
  8596. ASSERT_FALSE(issuer_str.empty());
  8597. // The client certificate should be issued by our test CA
  8598. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8599. res.set_content("authenticated", "text/plain");
  8600. });
  8601. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8602. auto se = detail::scope_exit([&] {
  8603. svr.stop();
  8604. t.join();
  8605. ASSERT_FALSE(svr.is_running());
  8606. });
  8607. svr.wait_until_ready();
  8608. // Connect with a client certificate issued by the CA
  8609. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8610. cli.enable_server_certificate_verification(false);
  8611. cli.set_connection_timeout(30);
  8612. auto res = cli.Get("/test");
  8613. ASSERT_TRUE(res);
  8614. ASSERT_EQ(StatusCode::OK_200, res->status);
  8615. ASSERT_TRUE(handler_called);
  8616. EXPECT_EQ("authenticated", res->body);
  8617. }
  8618. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8619. using namespace httplib::tls;
  8620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8621. ASSERT_TRUE(svr.is_valid());
  8622. svr.Get("/test", [](const Request &, Response &res) {
  8623. res.set_content("ok", "text/plain");
  8624. });
  8625. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8626. auto se = detail::scope_exit([&] {
  8627. svr.stop();
  8628. t.join();
  8629. });
  8630. svr.wait_until_ready();
  8631. SSLClient cli(HOST, PORT);
  8632. cli.enable_server_certificate_verification(false);
  8633. cli.set_connection_timeout(30);
  8634. bool cert_checked = false;
  8635. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8636. if (ctx.cert) {
  8637. auto sans = ctx.sans();
  8638. // Test certificate may or may not have SANs - just verify the API
  8639. // works If SANs exist, verify the types are valid
  8640. for (const auto &san : sans) {
  8641. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8642. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8643. san.type == SanType::OTHER);
  8644. EXPECT_FALSE(san.value.empty());
  8645. }
  8646. cert_checked = true;
  8647. }
  8648. return true;
  8649. });
  8650. auto res = cli.Get("/test");
  8651. ASSERT_TRUE(res);
  8652. EXPECT_TRUE(cert_checked);
  8653. }
  8654. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8655. using namespace httplib::tls;
  8656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8657. ASSERT_TRUE(svr.is_valid());
  8658. svr.Get("/test", [](const Request &, Response &res) {
  8659. res.set_content("ok", "text/plain");
  8660. });
  8661. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8662. auto se = detail::scope_exit([&] {
  8663. svr.stop();
  8664. t.join();
  8665. });
  8666. svr.wait_until_ready();
  8667. SSLClient cli(HOST, PORT);
  8668. cli.enable_server_certificate_verification(false);
  8669. cli.set_connection_timeout(30);
  8670. bool validity_checked = false;
  8671. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8672. if (ctx.cert) {
  8673. time_t not_before = 0, not_after = 0;
  8674. bool result = ctx.validity(not_before, not_after);
  8675. EXPECT_TRUE(result);
  8676. // Verify that not_before < now < not_after for a valid cert
  8677. time_t now = time(nullptr);
  8678. EXPECT_LT(not_before, now);
  8679. EXPECT_GT(not_after, now);
  8680. validity_checked = true;
  8681. }
  8682. return true;
  8683. });
  8684. auto res = cli.Get("/test");
  8685. ASSERT_TRUE(res);
  8686. EXPECT_TRUE(validity_checked);
  8687. }
  8688. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8689. using namespace httplib::tls;
  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 serial_checked = false;
  8705. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8706. if (ctx.cert) {
  8707. std::string serial = ctx.serial();
  8708. EXPECT_FALSE(serial.empty());
  8709. // Serial should be a hex string
  8710. for (char c : serial) {
  8711. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8712. (c >= 'a' && c <= 'f'));
  8713. }
  8714. serial_checked = true;
  8715. }
  8716. return true;
  8717. });
  8718. auto res = cli.Get("/test");
  8719. ASSERT_TRUE(res);
  8720. EXPECT_TRUE(serial_checked);
  8721. }
  8722. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8723. // Test 1: Valid CA file - no error should be recorded
  8724. {
  8725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8726. CLIENT_CA_CERT_FILE);
  8727. ASSERT_TRUE(svr.is_valid());
  8728. // With valid setup, last_ssl_error should be 0
  8729. EXPECT_EQ(0, svr.ssl_last_error());
  8730. }
  8731. // Test 2: Invalid CA file content
  8732. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8733. {
  8734. // Create a temporary file with completely invalid content
  8735. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8736. {
  8737. std::ofstream ofs(temp_invalid_ca);
  8738. ofs << "This is not a certificate file at all\n";
  8739. ofs << "Just plain text content\n";
  8740. }
  8741. // Create server with invalid CA file
  8742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8743. // Clean up temporary file
  8744. std::remove(temp_invalid_ca);
  8745. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8746. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8747. // Note: SSL_CTX_load_verify_locations typically fails first,
  8748. // but our error handling code path is still exercised
  8749. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8750. }
  8751. }
  8752. TEST(VerifyCallbackTest, VerifyContextFields) {
  8753. using namespace httplib::tls;
  8754. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8755. ASSERT_TRUE(svr.is_valid());
  8756. svr.Get("/test", [](const Request &, Response &res) {
  8757. res.set_content("ok", "text/plain");
  8758. });
  8759. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8760. auto se = detail::scope_exit([&] {
  8761. svr.stop();
  8762. t.join();
  8763. });
  8764. svr.wait_until_ready();
  8765. SSLClient cli(HOST, PORT);
  8766. cli.enable_server_certificate_verification(false);
  8767. cli.set_connection_timeout(30);
  8768. int callback_count = 0;
  8769. bool saw_leaf_cert = false;
  8770. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8771. if (ctx.cert) {
  8772. callback_count++;
  8773. // We should see at least one certificate (the leaf)
  8774. std::string cn = ctx.subject_cn();
  8775. if (!cn.empty()) { saw_leaf_cert = true; }
  8776. // Verify context fields are populated
  8777. EXPECT_NE(ctx.session, nullptr);
  8778. EXPECT_GE(ctx.depth, 0);
  8779. }
  8780. return true;
  8781. });
  8782. auto res = cli.Get("/test");
  8783. ASSERT_TRUE(res);
  8784. EXPECT_GT(callback_count, 0);
  8785. EXPECT_TRUE(saw_leaf_cert);
  8786. }
  8787. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8788. using httplib::tls::TlsError;
  8789. // Test that verify_error_to_string returns empty for success
  8790. std::string success_str = TlsError::verify_error_to_string(0);
  8791. EXPECT_TRUE(success_str.empty());
  8792. // Test that verify_error_to_string returns non-empty for error codes
  8793. // Using a common error code (certificate expired)
  8794. std::string error_str =
  8795. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8796. EXPECT_FALSE(error_str.empty());
  8797. }
  8798. TEST(SessionVerifierTest, CertificateAccepted) {
  8799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8800. ASSERT_TRUE(svr.is_valid());
  8801. svr.Get("/test", [](const Request &, Response &res) {
  8802. res.set_content("ok", "text/plain");
  8803. });
  8804. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8805. auto se = detail::scope_exit([&] {
  8806. svr.stop();
  8807. t.join();
  8808. });
  8809. svr.wait_until_ready();
  8810. SSLClient cli(HOST, PORT);
  8811. cli.enable_server_certificate_verification(false);
  8812. cli.set_connection_timeout(30);
  8813. bool callback_called = false;
  8814. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8815. EXPECT_NE(session, nullptr);
  8816. callback_called = true;
  8817. return SSLVerifierResponse::CertificateAccepted;
  8818. });
  8819. auto res = cli.Get("/test");
  8820. ASSERT_TRUE(res);
  8821. EXPECT_EQ(200, res->status);
  8822. EXPECT_TRUE(callback_called);
  8823. }
  8824. TEST(SessionVerifierTest, CertificateRejected) {
  8825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8826. ASSERT_TRUE(svr.is_valid());
  8827. svr.Get("/test", [](const Request &, Response &res) {
  8828. res.set_content("ok", "text/plain");
  8829. });
  8830. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8831. auto se = detail::scope_exit([&] {
  8832. svr.stop();
  8833. t.join();
  8834. });
  8835. svr.wait_until_ready();
  8836. SSLClient cli(HOST, PORT);
  8837. cli.enable_server_certificate_verification(false);
  8838. cli.set_connection_timeout(30);
  8839. bool callback_called = false;
  8840. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8841. EXPECT_NE(session, nullptr);
  8842. callback_called = true;
  8843. return SSLVerifierResponse::CertificateRejected;
  8844. });
  8845. auto res = cli.Get("/test");
  8846. EXPECT_FALSE(res);
  8847. EXPECT_TRUE(callback_called);
  8848. }
  8849. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8851. ASSERT_TRUE(svr.is_valid());
  8852. svr.Get("/test", [](const Request &, Response &res) {
  8853. res.set_content("ok", "text/plain");
  8854. });
  8855. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8856. auto se = detail::scope_exit([&] {
  8857. svr.stop();
  8858. t.join();
  8859. });
  8860. svr.wait_until_ready();
  8861. // NoDecisionMade with verification disabled should succeed (no default check)
  8862. SSLClient cli(HOST, PORT);
  8863. cli.enable_server_certificate_verification(false);
  8864. cli.set_connection_timeout(30);
  8865. bool callback_called = false;
  8866. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8867. EXPECT_NE(session, nullptr);
  8868. callback_called = true;
  8869. return SSLVerifierResponse::NoDecisionMade;
  8870. });
  8871. auto res = cli.Get("/test");
  8872. ASSERT_TRUE(res);
  8873. EXPECT_EQ(200, res->status);
  8874. EXPECT_TRUE(callback_called);
  8875. }
  8876. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8878. ASSERT_TRUE(svr.is_valid());
  8879. svr.Get("/test", [](const Request &, Response &res) {
  8880. res.set_content("ok", "text/plain");
  8881. });
  8882. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8883. auto se = detail::scope_exit([&] {
  8884. svr.stop();
  8885. t.join();
  8886. });
  8887. svr.wait_until_ready();
  8888. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8889. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8890. // so we only check that the request fails, not whether the callback was
  8891. // called.
  8892. SSLClient cli(HOST, PORT);
  8893. cli.enable_server_certificate_verification(true);
  8894. cli.set_connection_timeout(30);
  8895. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8896. EXPECT_NE(session, nullptr);
  8897. return SSLVerifierResponse::NoDecisionMade;
  8898. });
  8899. auto res = cli.Get("/test");
  8900. EXPECT_FALSE(res);
  8901. }
  8902. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8903. // Test SSL server using PemMemory constructor with client CA certificates
  8904. // Read PEM files
  8905. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8906. read_file(SERVER_CERT_FILE, server_cert_pem);
  8907. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8908. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8909. // Create SSLServer with PemMemory constructor including client CA
  8910. SSLServer::PemMemory server_pem = {
  8911. server_cert_pem.c_str(),
  8912. server_cert_pem.size(),
  8913. server_key_pem.c_str(),
  8914. server_key_pem.size(),
  8915. client_ca_pem.c_str(),
  8916. client_ca_pem.size(),
  8917. nullptr // no password for server key
  8918. };
  8919. SSLServer svr(server_pem);
  8920. ASSERT_TRUE(svr.is_valid());
  8921. // No SSL error should be recorded for valid setup
  8922. EXPECT_EQ(0, svr.ssl_last_error());
  8923. // Set up server endpoints
  8924. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8925. res.set_content("ok", "text/plain");
  8926. });
  8927. // Start server in a thread
  8928. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8929. svr.wait_until_ready();
  8930. // Connect with client certificate (using constructor with paths)
  8931. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8932. cli.enable_server_certificate_verification(false);
  8933. auto res = cli.Get("/test-pem-ca");
  8934. ASSERT_TRUE(res);
  8935. EXPECT_EQ(200, res->status);
  8936. EXPECT_EQ("ok", res->body);
  8937. svr.stop();
  8938. server_thread.join();
  8939. }
  8940. #endif
  8941. #ifdef _WIN32
  8942. TEST(CleanupTest, WSACleanup) {
  8943. int ret = WSACleanup();
  8944. ASSERT_EQ(0, ret);
  8945. }
  8946. #endif
  8947. #ifndef CPPHTTPLIB_SSL_ENABLED
  8948. TEST(NoSSLSupport, SimpleInterface) {
  8949. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8950. }
  8951. #endif
  8952. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8953. TEST(InvalidScheme, SimpleInterface) {
  8954. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8955. }
  8956. #endif
  8957. TEST(NoScheme, SimpleInterface) {
  8958. Client cli("yahoo.com:80");
  8959. ASSERT_TRUE(cli.is_valid());
  8960. }
  8961. TEST(SendAPI, SimpleInterface_Online) {
  8962. Client cli("http://yahoo.com");
  8963. Request req;
  8964. req.method = "GET";
  8965. req.path = "/";
  8966. auto res = cli.send(req);
  8967. ASSERT_TRUE(res);
  8968. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8969. }
  8970. TEST(SendAPI, WithParamsInRequest) {
  8971. Server svr;
  8972. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8973. EXPECT_TRUE(req.has_param("test"));
  8974. EXPECT_EQ("test_value", req.get_param_value("test"));
  8975. });
  8976. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8977. auto se = detail::scope_exit([&] {
  8978. svr.stop();
  8979. t.join();
  8980. ASSERT_FALSE(svr.is_running());
  8981. });
  8982. svr.wait_until_ready();
  8983. Client cli(HOST, PORT);
  8984. {
  8985. Request req;
  8986. req.method = "GET";
  8987. req.path = "/";
  8988. req.params.emplace("test", "test_value");
  8989. auto res = cli.send(req);
  8990. ASSERT_TRUE(res);
  8991. }
  8992. {
  8993. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8994. ASSERT_TRUE(res);
  8995. }
  8996. }
  8997. TEST(ClientImplMethods, GetSocketTest) {
  8998. httplib::Server svr;
  8999. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9000. res.status = StatusCode::OK_200;
  9001. });
  9002. auto port = svr.bind_to_any_port("127.0.0.1");
  9003. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9004. auto se = detail::scope_exit([&] {
  9005. svr.stop();
  9006. thread.join();
  9007. ASSERT_FALSE(svr.is_running());
  9008. });
  9009. svr.wait_until_ready();
  9010. {
  9011. httplib::Client cli("127.0.0.1", port);
  9012. cli.set_keep_alive(true);
  9013. // Use the behavior of cpp-httplib of opening the connection
  9014. // only when the first request happens. If that changes,
  9015. // this test would be obsolete.
  9016. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9017. // This also implicitly tests the server. But other tests would fail much
  9018. // earlier than this one to be considered.
  9019. auto res = cli.Get("/");
  9020. ASSERT_TRUE(res);
  9021. EXPECT_EQ(StatusCode::OK_200, res->status);
  9022. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9023. }
  9024. }
  9025. // Disabled due to out-of-memory problem on GitHub Actions
  9026. #ifdef _WIN64
  9027. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  9028. // allocate content size larger than 2GB in memory
  9029. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  9030. char *content = (char *)malloc(content_size);
  9031. ASSERT_TRUE(content);
  9032. Server svr;
  9033. svr.Get("/foo",
  9034. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  9035. res.set_content(content, content_size, "application/octet-stream");
  9036. });
  9037. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9038. auto se = detail::scope_exit([&] {
  9039. svr.stop();
  9040. listen_thread.join();
  9041. if (content) free(content);
  9042. ASSERT_FALSE(svr.is_running());
  9043. });
  9044. svr.wait_until_ready();
  9045. Client cli(HOST, PORT);
  9046. auto res = cli.Get("/foo");
  9047. ASSERT_TRUE(res);
  9048. EXPECT_EQ(StatusCode::OK_200, res->status);
  9049. EXPECT_EQ(content_size, res->body.length());
  9050. }
  9051. #endif
  9052. #ifdef CPPHTTPLIB_SSL_ENABLED
  9053. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9054. Client cli("http://yahoo.com");
  9055. auto res = cli.Get("/");
  9056. ASSERT_TRUE(res);
  9057. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9058. cli.set_follow_location(true);
  9059. res = cli.Get("/");
  9060. ASSERT_TRUE(res);
  9061. EXPECT_EQ(StatusCode::OK_200, res->status);
  9062. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9063. }
  9064. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9065. Client cli("https://yahoo.com");
  9066. auto res = cli.Get("/");
  9067. ASSERT_TRUE(res);
  9068. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9069. cli.set_follow_location(true);
  9070. res = cli.Get("/");
  9071. ASSERT_TRUE(res);
  9072. EXPECT_EQ(StatusCode::OK_200, res->status);
  9073. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9074. }
  9075. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9076. Client cli("https://yahoo.com");
  9077. auto res = cli.Get("/");
  9078. ASSERT_TRUE(res);
  9079. ASSERT_FALSE(!res);
  9080. ASSERT_TRUE(res);
  9081. ASSERT_FALSE(res == nullptr);
  9082. ASSERT_TRUE(res != nullptr);
  9083. EXPECT_EQ(Error::Success, res.error());
  9084. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9085. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9086. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9087. cli.set_follow_location(true);
  9088. res = cli.Get("/");
  9089. ASSERT_TRUE(res);
  9090. EXPECT_EQ(Error::Success, res.error());
  9091. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9092. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9095. }
  9096. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9097. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9098. Client cli("https://cdnjs.cloudflare.com");
  9099. auto res =
  9100. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9101. ASSERT_TRUE(res);
  9102. EXPECT_EQ(StatusCode::OK_200, res->status);
  9103. EXPECT_EQ(287630U, res->body.size());
  9104. EXPECT_EQ("application/javascript; charset=utf-8",
  9105. res->get_header_value("Content-Type"));
  9106. }
  9107. #endif
  9108. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9109. #undef REDIR_HOST // Silence compiler warning
  9110. #define REDIR_HOST "https://httpbingo.org"
  9111. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9112. Client cli(REDIR_HOST);
  9113. cli.set_follow_location(true);
  9114. auto res =
  9115. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9116. ASSERT_TRUE(res);
  9117. EXPECT_EQ(StatusCode::OK_200, res->status);
  9118. }
  9119. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9120. Client cli(REDIR_HOST);
  9121. cli.set_follow_location(true);
  9122. Params params;
  9123. params.emplace("url", "http://example.com");
  9124. params.emplace("status_code", "302");
  9125. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9126. ASSERT_TRUE(res);
  9127. EXPECT_EQ(StatusCode::OK_200, res->status);
  9128. }
  9129. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9130. Client cli(REDIR_HOST);
  9131. cli.set_follow_location(true);
  9132. Params params;
  9133. params.emplace("url", "http://example.com");
  9134. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9135. ASSERT_TRUE(res);
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. }
  9138. TEST(HttpToHttpsRedirectTest, CertFile) {
  9139. auto ssl_port = PORT + 1;
  9140. Server svr;
  9141. ASSERT_TRUE(svr.is_valid());
  9142. svr.Get("/index", [&](const Request &, Response &res) {
  9143. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9144. "/index");
  9145. svr.stop();
  9146. });
  9147. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9148. ASSERT_TRUE(ssl_svr.is_valid());
  9149. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9150. res.set_content("test", "text/plain");
  9151. ssl_svr.stop();
  9152. });
  9153. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9154. thread t2 =
  9155. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9156. auto se = detail::scope_exit([&] {
  9157. t2.join();
  9158. t.join();
  9159. ASSERT_FALSE(svr.is_running());
  9160. });
  9161. svr.wait_until_ready();
  9162. ssl_svr.wait_until_ready();
  9163. Client cli("127.0.0.1", PORT);
  9164. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9165. cli.enable_server_certificate_verification(true);
  9166. cli.set_follow_location(true);
  9167. cli.set_connection_timeout(30);
  9168. auto res = cli.Get("/index");
  9169. ASSERT_TRUE(res);
  9170. ASSERT_EQ(StatusCode::OK_200, res->status);
  9171. }
  9172. TEST(SSLClientRedirectTest, CertFile) {
  9173. auto ssl_port = PORT + 1;
  9174. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9175. ASSERT_TRUE(ssl_svr1.is_valid());
  9176. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9177. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9178. "/index");
  9179. ssl_svr1.stop();
  9180. });
  9181. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9182. ASSERT_TRUE(ssl_svr2.is_valid());
  9183. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9184. res.set_content("test", "text/plain");
  9185. ssl_svr2.stop();
  9186. });
  9187. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9188. thread t2 =
  9189. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9190. auto se = detail::scope_exit([&] {
  9191. t2.join();
  9192. t.join();
  9193. ASSERT_FALSE(ssl_svr1.is_running());
  9194. });
  9195. ssl_svr1.wait_until_ready();
  9196. ssl_svr2.wait_until_ready();
  9197. SSLClient cli("127.0.0.1", PORT);
  9198. std::string cert;
  9199. read_file(SERVER_CERT2_FILE, cert);
  9200. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9201. cli.enable_server_certificate_verification(true);
  9202. cli.set_follow_location(true);
  9203. cli.set_connection_timeout(30);
  9204. auto res = cli.Get("/index");
  9205. ASSERT_TRUE(res);
  9206. ASSERT_EQ(StatusCode::OK_200, res->status);
  9207. }
  9208. #endif
  9209. #ifdef CPPHTTPLIB_SSL_ENABLED
  9210. // Test that set_ca_cert_store() skips system certs (consistent with
  9211. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9212. // should be trusted - system certs should NOT be loaded.
  9213. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9214. // Load a specific cert that is NOT a system CA cert
  9215. std::string cert;
  9216. read_file(SERVER_CERT2_FILE, cert);
  9217. SSLClient cli("google.com");
  9218. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9219. cli.enable_server_certificate_verification(true);
  9220. // This should FAIL because:
  9221. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9222. // 2. System certs should NOT be loaded when custom store is set
  9223. // If system certs WERE loaded, this would succeed
  9224. auto res = cli.Get("/");
  9225. ASSERT_FALSE(res);
  9226. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9227. }
  9228. TEST(MultipartFormDataTest, LargeData) {
  9229. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9230. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9231. const ContentReader &content_reader) {
  9232. if (req.is_multipart_form_data()) {
  9233. std::vector<FormData> items;
  9234. content_reader(
  9235. [&](const FormData &file) {
  9236. items.push_back(file);
  9237. return true;
  9238. },
  9239. [&](const char *data, size_t data_length) {
  9240. items.back().content.append(data, data_length);
  9241. return true;
  9242. });
  9243. EXPECT_TRUE(std::string(items[0].name) == "document");
  9244. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9245. EXPECT_TRUE(items[0].filename == "2MB_data");
  9246. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9247. EXPECT_TRUE(items[1].name == "hello");
  9248. EXPECT_TRUE(items[1].content == "world");
  9249. EXPECT_TRUE(items[1].filename == "");
  9250. EXPECT_TRUE(items[1].content_type == "");
  9251. } else {
  9252. std::string body;
  9253. content_reader([&](const char *data, size_t data_length) {
  9254. body.append(data, data_length);
  9255. return true;
  9256. });
  9257. }
  9258. });
  9259. auto port = svr.bind_to_any_port(HOST);
  9260. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9261. auto se = detail::scope_exit([&] {
  9262. svr.stop();
  9263. t.join();
  9264. ASSERT_FALSE(svr.is_running());
  9265. });
  9266. svr.wait_until_ready();
  9267. {
  9268. std::string data(1024 * 1024 * 2, '.');
  9269. std::stringstream buffer;
  9270. buffer << data;
  9271. SSLClient cli(HOST, port);
  9272. cli.enable_server_certificate_verification(false);
  9273. UploadFormDataItems items{
  9274. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9275. {"hello", "world", "", ""},
  9276. };
  9277. auto res = cli.Post("/post", items);
  9278. ASSERT_TRUE(res);
  9279. ASSERT_EQ(StatusCode::OK_200, res->status);
  9280. }
  9281. }
  9282. TEST(MultipartFormDataTest, DataProviderItems) {
  9283. std::random_device seed_gen;
  9284. std::mt19937 random(seed_gen());
  9285. std::string rand1;
  9286. rand1.resize(1000);
  9287. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9288. std::string rand2;
  9289. rand2.resize(3000);
  9290. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9292. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9293. const ContentReader &content_reader) {
  9294. ASSERT_FALSE(req.is_multipart_form_data());
  9295. std::string body;
  9296. content_reader([&](const char *data, size_t data_length) {
  9297. body.append(data, data_length);
  9298. return true;
  9299. });
  9300. EXPECT_EQ(body, "");
  9301. });
  9302. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9303. const ContentReader &content_reader) {
  9304. ASSERT_TRUE(req.is_multipart_form_data());
  9305. std::vector<FormData> items;
  9306. content_reader(
  9307. [&](const FormData &file) {
  9308. items.push_back(file);
  9309. return true;
  9310. },
  9311. [&](const char *data, size_t data_length) {
  9312. items.back().content.append(data, data_length);
  9313. return true;
  9314. });
  9315. ASSERT_TRUE(items.size() == 2);
  9316. EXPECT_EQ(std::string(items[0].name), "name1");
  9317. EXPECT_EQ(items[0].content, "Testing123");
  9318. EXPECT_EQ(items[0].filename, "filename1");
  9319. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9320. EXPECT_EQ(items[1].name, "name2");
  9321. EXPECT_EQ(items[1].content, "Testing456");
  9322. EXPECT_EQ(items[1].filename, "");
  9323. EXPECT_EQ(items[1].content_type, "");
  9324. });
  9325. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9326. const ContentReader &content_reader) {
  9327. ASSERT_TRUE(req.is_multipart_form_data());
  9328. std::vector<FormData> items;
  9329. content_reader(
  9330. [&](const FormData &file) {
  9331. items.push_back(file);
  9332. return true;
  9333. },
  9334. [&](const char *data, size_t data_length) {
  9335. items.back().content.append(data, data_length);
  9336. return true;
  9337. });
  9338. ASSERT_TRUE(items.size() == 2);
  9339. EXPECT_EQ(items[0].name, "name3");
  9340. EXPECT_EQ(items[0].content, rand1);
  9341. EXPECT_EQ(items[0].filename, "filename3");
  9342. EXPECT_EQ(items[0].content_type, "");
  9343. EXPECT_EQ(items[1].name, "name4");
  9344. EXPECT_EQ(items[1].content, rand2);
  9345. EXPECT_EQ(items[1].filename, "filename4");
  9346. EXPECT_EQ(items[1].content_type, "");
  9347. });
  9348. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9349. const ContentReader &content_reader) {
  9350. ASSERT_TRUE(req.is_multipart_form_data());
  9351. std::vector<FormData> items;
  9352. content_reader(
  9353. [&](const FormData &file) {
  9354. items.push_back(file);
  9355. return true;
  9356. },
  9357. [&](const char *data, size_t data_length) {
  9358. items.back().content.append(data, data_length);
  9359. return true;
  9360. });
  9361. ASSERT_TRUE(items.size() == 4);
  9362. EXPECT_EQ(std::string(items[0].name), "name1");
  9363. EXPECT_EQ(items[0].content, "Testing123");
  9364. EXPECT_EQ(items[0].filename, "filename1");
  9365. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9366. EXPECT_EQ(items[1].name, "name2");
  9367. EXPECT_EQ(items[1].content, "Testing456");
  9368. EXPECT_EQ(items[1].filename, "");
  9369. EXPECT_EQ(items[1].content_type, "");
  9370. EXPECT_EQ(items[2].name, "name3");
  9371. EXPECT_EQ(items[2].content, rand1);
  9372. EXPECT_EQ(items[2].filename, "filename3");
  9373. EXPECT_EQ(items[2].content_type, "");
  9374. EXPECT_EQ(items[3].name, "name4");
  9375. EXPECT_EQ(items[3].content, rand2);
  9376. EXPECT_EQ(items[3].filename, "filename4");
  9377. EXPECT_EQ(items[3].content_type, "");
  9378. });
  9379. auto port = svr.bind_to_any_port("localhost");
  9380. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9381. auto se = detail::scope_exit([&] {
  9382. svr.stop();
  9383. t.join();
  9384. ASSERT_FALSE(svr.is_running());
  9385. });
  9386. svr.wait_until_ready();
  9387. {
  9388. SSLClient cli("localhost", port);
  9389. cli.enable_server_certificate_verification(false);
  9390. UploadFormDataItems items{
  9391. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9392. {"name2", "Testing456", "", ""}, // not a file
  9393. };
  9394. {
  9395. auto res = cli.Post("/post-none", {}, {}, {});
  9396. ASSERT_TRUE(res);
  9397. ASSERT_EQ(StatusCode::OK_200, res->status);
  9398. }
  9399. FormDataProviderItems providers;
  9400. {
  9401. auto res =
  9402. cli.Post("/post-items", {}, items, providers); // empty providers
  9403. ASSERT_TRUE(res);
  9404. ASSERT_EQ(StatusCode::OK_200, res->status);
  9405. }
  9406. providers.push_back({"name3",
  9407. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9408. // test the offset is given correctly at each step
  9409. if (!offset)
  9410. sink.os.write(rand1.data(), 30);
  9411. else if (offset == 30)
  9412. sink.os.write(rand1.data() + 30, 300);
  9413. else if (offset == 330)
  9414. sink.os.write(rand1.data() + 330, 670);
  9415. else if (offset == rand1.size())
  9416. sink.done();
  9417. return true;
  9418. },
  9419. "filename3",
  9420. {}});
  9421. providers.push_back({"name4",
  9422. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9423. // test the offset is given correctly at each step
  9424. if (!offset)
  9425. sink.os.write(rand2.data(), 2000);
  9426. else if (offset == 2000)
  9427. sink.os.write(rand2.data() + 2000, 1);
  9428. else if (offset == 2001)
  9429. sink.os.write(rand2.data() + 2001, 999);
  9430. else if (offset == rand2.size())
  9431. sink.done();
  9432. return true;
  9433. },
  9434. "filename4",
  9435. {}});
  9436. {
  9437. auto res = cli.Post("/post-providers", {}, {}, providers);
  9438. ASSERT_TRUE(res);
  9439. ASSERT_EQ(StatusCode::OK_200, res->status);
  9440. }
  9441. {
  9442. auto res = cli.Post("/post-both", {}, items, providers);
  9443. ASSERT_TRUE(res);
  9444. ASSERT_EQ(StatusCode::OK_200, res->status);
  9445. }
  9446. }
  9447. }
  9448. TEST(MultipartFormDataTest, BadHeader) {
  9449. Server svr;
  9450. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9451. res.set_content("ok", "text/plain");
  9452. });
  9453. thread t = thread([&] { svr.listen(HOST, PORT); });
  9454. auto se = detail::scope_exit([&] {
  9455. svr.stop();
  9456. t.join();
  9457. ASSERT_FALSE(svr.is_running());
  9458. });
  9459. svr.wait_until_ready();
  9460. const std::string body =
  9461. "This is the preamble. It is to be ignored, though it\r\n"
  9462. "is a handy place for composition agents to include an\r\n"
  9463. "explanatory note to non-MIME conformant readers.\r\n"
  9464. "\r\n"
  9465. "\r\n"
  9466. "--simple boundary\r\n"
  9467. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9468. ": BAD...\r\n"
  9469. "\r\n"
  9470. "value1\r\n"
  9471. "--simple boundary\r\n"
  9472. "Content-Disposition: form-data; name=\"field2\"; "
  9473. "filename=\"example.txt\"\r\n"
  9474. "\r\n"
  9475. "value2\r\n"
  9476. "--simple boundary--\r\n"
  9477. "This is the epilogue. It is also to be ignored.\r\n";
  9478. std::string content_type =
  9479. R"(multipart/form-data; boundary="simple boundary")";
  9480. Client cli(HOST, PORT);
  9481. auto res = cli.Post("/post", body, content_type.c_str());
  9482. ASSERT_TRUE(res);
  9483. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9484. }
  9485. TEST(MultipartFormDataTest, WithPreamble) {
  9486. Server svr;
  9487. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9488. res.set_content("ok", "text/plain");
  9489. });
  9490. thread t = thread([&] { svr.listen(HOST, PORT); });
  9491. auto se = detail::scope_exit([&] {
  9492. svr.stop();
  9493. t.join();
  9494. ASSERT_FALSE(svr.is_running());
  9495. });
  9496. svr.wait_until_ready();
  9497. const std::string body =
  9498. "This is the preamble. It is to be ignored, though it\r\n"
  9499. "is a handy place for composition agents to include an\r\n"
  9500. "explanatory note to non-MIME conformant readers.\r\n"
  9501. "\r\n"
  9502. "\r\n"
  9503. "--simple boundary\r\n"
  9504. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9505. "\r\n"
  9506. "value1\r\n"
  9507. "--simple boundary\r\n"
  9508. "Content-Disposition: form-data; name=\"field2\"; "
  9509. "filename=\"example.txt\"\r\n"
  9510. "\r\n"
  9511. "value2\r\n"
  9512. "--simple boundary--\r\n"
  9513. "This is the epilogue. It is also to be ignored.\r\n";
  9514. std::string content_type =
  9515. R"(multipart/form-data; boundary="simple boundary")";
  9516. Client cli(HOST, PORT);
  9517. auto res = cli.Post("/post", body, content_type.c_str());
  9518. ASSERT_TRUE(res);
  9519. EXPECT_EQ(StatusCode::OK_200, res->status);
  9520. }
  9521. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9523. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9524. const ContentReader &content_reader) {
  9525. if (req.is_multipart_form_data()) {
  9526. std::vector<FormData> items;
  9527. content_reader(
  9528. [&](const FormData &file) {
  9529. items.push_back(file);
  9530. return true;
  9531. },
  9532. [&](const char *data, size_t data_length) {
  9533. items.back().content.append(data, data_length);
  9534. return true;
  9535. });
  9536. EXPECT_TRUE(std::string(items[0].name) == "document");
  9537. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9538. EXPECT_TRUE(items[0].filename == "2MB_data");
  9539. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9540. EXPECT_TRUE(items[1].name == "hello");
  9541. EXPECT_TRUE(items[1].content == "world");
  9542. EXPECT_TRUE(items[1].filename == "");
  9543. EXPECT_TRUE(items[1].content_type == "");
  9544. } else {
  9545. std::string body;
  9546. content_reader([&](const char *data, size_t data_length) {
  9547. body.append(data, data_length);
  9548. return true;
  9549. });
  9550. }
  9551. });
  9552. auto port = svr.bind_to_any_port("localhost");
  9553. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9554. auto se = detail::scope_exit([&] {
  9555. svr.stop();
  9556. t.join();
  9557. ASSERT_FALSE(svr.is_running());
  9558. });
  9559. svr.wait_until_ready();
  9560. {
  9561. std::string data(1024 * 1024 * 2, '.');
  9562. std::stringstream buffer;
  9563. buffer << data;
  9564. SSLClient cli("localhost", port);
  9565. cli.enable_server_certificate_verification(false);
  9566. UploadFormDataItems items{
  9567. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9568. {"hello", "world", "", ""},
  9569. };
  9570. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9571. ASSERT_TRUE(res);
  9572. ASSERT_EQ(StatusCode::OK_200, res->status);
  9573. }
  9574. }
  9575. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9576. std::string data(1024 * 1024 * 2, '&');
  9577. std::stringstream buffer;
  9578. buffer << data;
  9579. Client cli("https://localhost:8080");
  9580. UploadFormDataItems items{
  9581. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9582. {"hello", "world", "", ""},
  9583. };
  9584. for (const char &c : " \t\r\n") {
  9585. auto res =
  9586. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9587. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9588. ASSERT_FALSE(res);
  9589. }
  9590. }
  9591. TEST(MultipartFormDataTest, PutFormData) {
  9592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9593. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9594. const ContentReader &content_reader) {
  9595. if (req.is_multipart_form_data()) {
  9596. std::vector<FormData> items;
  9597. content_reader(
  9598. [&](const FormData &file) {
  9599. items.push_back(file);
  9600. return true;
  9601. },
  9602. [&](const char *data, size_t data_length) {
  9603. items.back().content.append(data, data_length);
  9604. return true;
  9605. });
  9606. EXPECT_TRUE(std::string(items[0].name) == "document");
  9607. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9608. EXPECT_TRUE(items[0].filename == "2MB_data");
  9609. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9610. EXPECT_TRUE(items[1].name == "hello");
  9611. EXPECT_TRUE(items[1].content == "world");
  9612. EXPECT_TRUE(items[1].filename == "");
  9613. EXPECT_TRUE(items[1].content_type == "");
  9614. } else {
  9615. std::string body;
  9616. content_reader([&](const char *data, size_t data_length) {
  9617. body.append(data, data_length);
  9618. return true;
  9619. });
  9620. }
  9621. });
  9622. auto port = svr.bind_to_any_port("localhost");
  9623. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9624. auto se = detail::scope_exit([&] {
  9625. svr.stop();
  9626. t.join();
  9627. ASSERT_FALSE(svr.is_running());
  9628. });
  9629. svr.wait_until_ready();
  9630. {
  9631. std::string data(1024 * 1024 * 2, '&');
  9632. std::stringstream buffer;
  9633. buffer << data;
  9634. SSLClient cli("localhost", port);
  9635. cli.enable_server_certificate_verification(false);
  9636. UploadFormDataItems items{
  9637. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9638. {"hello", "world", "", ""},
  9639. };
  9640. auto res = cli.Put("/put", items);
  9641. ASSERT_TRUE(res);
  9642. ASSERT_EQ(StatusCode::OK_200, res->status);
  9643. }
  9644. }
  9645. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9646. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9647. svr.Put("/put_customboundary",
  9648. [&](const Request &req, const Response & /*res*/,
  9649. const ContentReader &content_reader) {
  9650. if (req.is_multipart_form_data()) {
  9651. std::vector<FormData> items;
  9652. content_reader(
  9653. [&](const FormData &file) {
  9654. items.push_back(file);
  9655. return true;
  9656. },
  9657. [&](const char *data, size_t data_length) {
  9658. items.back().content.append(data, data_length);
  9659. return true;
  9660. });
  9661. EXPECT_TRUE(std::string(items[0].name) == "document");
  9662. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9663. EXPECT_TRUE(items[0].filename == "2MB_data");
  9664. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9665. EXPECT_TRUE(items[1].name == "hello");
  9666. EXPECT_TRUE(items[1].content == "world");
  9667. EXPECT_TRUE(items[1].filename == "");
  9668. EXPECT_TRUE(items[1].content_type == "");
  9669. } else {
  9670. std::string body;
  9671. content_reader([&](const char *data, size_t data_length) {
  9672. body.append(data, data_length);
  9673. return true;
  9674. });
  9675. }
  9676. });
  9677. auto port = svr.bind_to_any_port("localhost");
  9678. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9679. auto se = detail::scope_exit([&] {
  9680. svr.stop();
  9681. t.join();
  9682. ASSERT_FALSE(svr.is_running());
  9683. });
  9684. svr.wait_until_ready();
  9685. {
  9686. std::string data(1024 * 1024 * 2, '&');
  9687. std::stringstream buffer;
  9688. buffer << data;
  9689. SSLClient cli("localhost", port);
  9690. cli.enable_server_certificate_verification(false);
  9691. UploadFormDataItems items{
  9692. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9693. {"hello", "world", "", ""},
  9694. };
  9695. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9696. ASSERT_TRUE(res);
  9697. ASSERT_EQ(StatusCode::OK_200, res->status);
  9698. }
  9699. }
  9700. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9701. std::string data(1024 * 1024 * 2, '&');
  9702. std::stringstream buffer;
  9703. buffer << data;
  9704. Client cli("https://localhost:8080");
  9705. cli.enable_server_certificate_verification(false);
  9706. UploadFormDataItems items{
  9707. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9708. {"hello", "world", "", ""},
  9709. };
  9710. for (const char &c : " \t\r\n") {
  9711. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9712. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9713. ASSERT_FALSE(res);
  9714. }
  9715. }
  9716. TEST(MultipartFormDataTest, AlternateFilename) {
  9717. auto handled = false;
  9718. Server svr;
  9719. svr.Post("/test", [&](const Request &req, Response &res) {
  9720. ASSERT_EQ(2u, req.form.files.size());
  9721. ASSERT_EQ(1u, req.form.fields.size());
  9722. // Test files
  9723. const auto &file1 = req.form.get_file("file1");
  9724. ASSERT_EQ("file1", file1.name);
  9725. ASSERT_EQ("A.txt", file1.filename);
  9726. ASSERT_EQ("text/plain", file1.content_type);
  9727. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9728. const auto &file2 = req.form.get_file("file2");
  9729. ASSERT_EQ("file2", file2.name);
  9730. ASSERT_EQ("a.html", file2.filename);
  9731. ASSERT_EQ("text/html", file2.content_type);
  9732. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9733. file2.content);
  9734. // Test text field
  9735. const auto &text = req.form.get_field("text");
  9736. ASSERT_EQ("text default", text);
  9737. res.set_content("ok", "text/plain");
  9738. handled = true;
  9739. });
  9740. thread t = thread([&] { svr.listen(HOST, PORT); });
  9741. auto se = detail::scope_exit([&] {
  9742. svr.stop();
  9743. t.join();
  9744. ASSERT_FALSE(svr.is_running());
  9745. ASSERT_TRUE(handled);
  9746. });
  9747. svr.wait_until_ready();
  9748. auto req = "POST /test HTTP/1.1\r\n"
  9749. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9750. "Content-Length: 399\r\n"
  9751. "\r\n"
  9752. "----------\r\n"
  9753. "Content-Disposition: form-data; name=\"text\"\r\n"
  9754. "\r\n"
  9755. "text default\r\n"
  9756. "----------\r\n"
  9757. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9758. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9759. "Content-Type: text/plain\r\n"
  9760. "\r\n"
  9761. "Content of a.txt.\r\n"
  9762. "\r\n"
  9763. "----------\r\n"
  9764. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9765. "\"a.html\"\r\n"
  9766. "Content-Type: text/html\r\n"
  9767. "\r\n"
  9768. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9769. "\r\n"
  9770. "------------\r\n";
  9771. ASSERT_TRUE(send_request(1, req));
  9772. }
  9773. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9774. auto handled = false;
  9775. Server svr;
  9776. svr.Post("/test", [&](const Request &req, Response &res) {
  9777. // Case-insensitive "utf-8''" prefix with a long value
  9778. const auto &file = req.form.get_file("file1");
  9779. ASSERT_EQ("file1", file.name);
  9780. // 8000 chars exercises both the Content-Disposition parser and the
  9781. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9782. // Prior to the fix, std::regex_match on this header would cause O(N)
  9783. // stack recursion in libstdc++, leading to SIGSEGV.
  9784. std::string expected_filename(8000, 'A');
  9785. ASSERT_EQ(expected_filename, file.filename);
  9786. res.set_content("ok", "text/plain");
  9787. handled = true;
  9788. });
  9789. thread t = thread([&] { svr.listen(HOST, PORT); });
  9790. auto se = detail::scope_exit([&] {
  9791. svr.stop();
  9792. t.join();
  9793. ASSERT_FALSE(svr.is_running());
  9794. ASSERT_TRUE(handled);
  9795. });
  9796. svr.wait_until_ready();
  9797. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9798. // Regression test for GHSA-qq6v-r583-3h69
  9799. std::string long_filename(8000, 'A');
  9800. std::string body = "----------\r\n"
  9801. "Content-Disposition: form-data; name=\"file1\"; "
  9802. "filename*=\"Utf-8''" +
  9803. long_filename +
  9804. "\"\r\n"
  9805. "\r\n"
  9806. "hello\r\n"
  9807. "------------\r\n";
  9808. auto req = "POST /test HTTP/1.1\r\n"
  9809. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9810. "Content-Length: " +
  9811. std::to_string(body.size()) + "\r\n\r\n" + body;
  9812. ASSERT_TRUE(send_request(1, req));
  9813. }
  9814. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9815. auto handled = false;
  9816. Server svr;
  9817. svr.Post("/test", [&](const Request &req, Response &) {
  9818. ASSERT_EQ(2u, req.form.fields.size());
  9819. const auto &text1 = req.form.get_field("text1");
  9820. ASSERT_EQ("text1", text1);
  9821. const auto &text2 = req.form.get_field("text2");
  9822. ASSERT_EQ("text2", text2);
  9823. handled = true;
  9824. });
  9825. thread t = thread([&] { svr.listen(HOST, PORT); });
  9826. auto se = detail::scope_exit([&] {
  9827. svr.stop();
  9828. t.join();
  9829. ASSERT_FALSE(svr.is_running());
  9830. ASSERT_TRUE(handled);
  9831. });
  9832. svr.wait_until_ready();
  9833. auto req = "POST /test HTTP/1.1\r\n"
  9834. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9835. "Content-Length: 146\r\n"
  9836. "\r\n----------\r\n"
  9837. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9838. "\r\n"
  9839. "text1"
  9840. "\r\n----------\r\n"
  9841. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9842. "\r\n"
  9843. "text2"
  9844. "\r\n------------";
  9845. std::string response;
  9846. ASSERT_TRUE(send_request(1, req, &response));
  9847. ASSERT_EQ("200", response.substr(9, 3));
  9848. }
  9849. TEST(MultipartFormDataTest, ContentLength) {
  9850. auto handled = false;
  9851. Server svr;
  9852. svr.Post("/test", [&](const Request &req, Response &) {
  9853. ASSERT_EQ(2u, req.form.fields.size());
  9854. const auto &text1 = req.form.get_field("text1");
  9855. ASSERT_EQ("text1", text1);
  9856. const auto &text2 = req.form.get_field("text2");
  9857. ASSERT_EQ("text2", text2);
  9858. handled = true;
  9859. });
  9860. thread t = thread([&] { svr.listen(HOST, PORT); });
  9861. auto se = detail::scope_exit([&] {
  9862. svr.stop();
  9863. t.join();
  9864. ASSERT_FALSE(svr.is_running());
  9865. ASSERT_TRUE(handled);
  9866. });
  9867. svr.wait_until_ready();
  9868. auto req = "POST /test HTTP/1.1\r\n"
  9869. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9870. "Content-Length: 167\r\n"
  9871. "\r\n----------\r\n"
  9872. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9873. "Content-Length: 5\r\n"
  9874. "\r\n"
  9875. "text1"
  9876. "\r\n----------\r\n"
  9877. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9878. "\r\n"
  9879. "text2"
  9880. "\r\n------------\r\n";
  9881. std::string response;
  9882. ASSERT_TRUE(send_request(1, req, &response));
  9883. ASSERT_EQ("200", response.substr(9, 3));
  9884. }
  9885. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9886. auto handled = false;
  9887. Server svr;
  9888. svr.Post("/test", [&](const Request &req, Response &) {
  9889. ASSERT_EQ(2u, req.form.fields.size());
  9890. const auto &text1 = req.form.get_field("text1");
  9891. ASSERT_EQ("text1", text1);
  9892. // TODO: Add header access for text fields if needed
  9893. const auto &text2 = req.form.get_field("text2");
  9894. ASSERT_EQ("text2", text2);
  9895. // TODO: Header access for text fields needs to be implemented
  9896. // auto &headers = it->second.headers;
  9897. // ASSERT_EQ(3U, headers.size());
  9898. // auto custom_header = headers.find("x-whatever");
  9899. // ASSERT_TRUE(custom_header != headers.end());
  9900. // ASSERT_NE("customvalue", custom_header->second);
  9901. // ASSERT_EQ("CustomValue", custom_header->second);
  9902. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9903. handled = true;
  9904. });
  9905. thread t = thread([&] { svr.listen(HOST, PORT); });
  9906. auto se = detail::scope_exit([&] {
  9907. svr.stop();
  9908. t.join();
  9909. ASSERT_FALSE(svr.is_running());
  9910. ASSERT_TRUE(handled);
  9911. });
  9912. svr.wait_until_ready();
  9913. auto req = "POST /test HTTP/1.1\r\n"
  9914. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9915. "Content-Length: 232\r\n"
  9916. "\r\n----------\r\n"
  9917. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9918. "Content-Length: 5\r\n"
  9919. "X-Test: 1\r\n"
  9920. "\r\n"
  9921. "text1"
  9922. "\r\n----------\r\n"
  9923. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9924. "Content-Type: text/plain\r\n"
  9925. "X-Whatever: CustomValue\r\n"
  9926. "\r\n"
  9927. "text2"
  9928. "\r\n------------\r\n"
  9929. "That should be disregarded. Not even read";
  9930. std::string response;
  9931. ASSERT_TRUE(send_request(1, req, &response));
  9932. ASSERT_EQ("200", response.substr(9, 3));
  9933. }
  9934. TEST(MultipartFormDataTest, LargeHeader) {
  9935. auto handled = false;
  9936. Server svr;
  9937. svr.Post("/test", [&](const Request &req, Response &) {
  9938. ASSERT_EQ(1u, req.form.fields.size());
  9939. const auto &text = req.form.get_field("name1");
  9940. ASSERT_EQ("text1", text);
  9941. handled = true;
  9942. });
  9943. thread t = thread([&] { svr.listen(HOST, PORT); });
  9944. auto se = detail::scope_exit([&] {
  9945. svr.stop();
  9946. t.join();
  9947. ASSERT_FALSE(svr.is_running());
  9948. ASSERT_TRUE(handled);
  9949. });
  9950. svr.wait_until_ready();
  9951. auto boundary = std::string("cpp-httplib-multipart-data");
  9952. std::string content = "--" + boundary +
  9953. "\r\n"
  9954. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9955. "\r\n"
  9956. "text1\r\n"
  9957. "--" +
  9958. boundary + "--\r\n";
  9959. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9960. "Content-Type: multipart/form-data;boundary=" +
  9961. boundary +
  9962. "\r\n"
  9963. "Content-Length: " +
  9964. std::to_string(content.size()) +
  9965. "\r\n"
  9966. "Dummy-Header: ";
  9967. std::string header_suffix = "\r\n"
  9968. "\r\n";
  9969. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9970. size_t header_dummy_size =
  9971. read_buff_size -
  9972. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9973. auto header_dummy = std::string(header_dummy_size, '@');
  9974. auto req = header_prefix + header_dummy + header_suffix + content;
  9975. std::string response;
  9976. ASSERT_TRUE(send_request(1, req, &response));
  9977. ASSERT_EQ("200", response.substr(9, 3));
  9978. }
  9979. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  9980. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  9981. // (not chunked Transfer-Encoding) after the streaming refactor.
  9982. auto handled = false;
  9983. Server svr;
  9984. svr.Post("/upload", [&](const Request &req, Response &res) {
  9985. auto cl_it = req.headers.find("Content-Length");
  9986. EXPECT_TRUE(cl_it != req.headers.end());
  9987. auto te_it = req.headers.find("Transfer-Encoding");
  9988. EXPECT_TRUE(te_it == req.headers.end());
  9989. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  9990. res.set_content("ok", "text/plain");
  9991. handled = true;
  9992. });
  9993. auto port = svr.bind_to_any_port(HOST);
  9994. auto t = thread([&] { svr.listen_after_bind(); });
  9995. auto se = detail::scope_exit([&] {
  9996. svr.stop();
  9997. t.join();
  9998. ASSERT_FALSE(svr.is_running());
  9999. ASSERT_TRUE(handled);
  10000. });
  10001. svr.wait_until_ready();
  10002. UploadFormDataItems items = {
  10003. {"field1", "hello", "", "text/plain"},
  10004. {"file1", "world", "test.txt", "application/octet-stream"},
  10005. };
  10006. Client cli(HOST, port);
  10007. auto res = cli.Post("/upload", {}, items);
  10008. ASSERT_TRUE(res);
  10009. EXPECT_EQ(StatusCode::OK_200, res->status);
  10010. }
  10011. TEST(MultipartFormDataTest, MakeFileProvider) {
  10012. // Verify make_file_provider sends a file's contents correctly.
  10013. const std::string file_content(4096, 'Z');
  10014. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10015. {
  10016. std::ofstream ofs(tmp_path, std::ios::binary);
  10017. ofs.write(file_content.data(),
  10018. static_cast<std::streamsize>(file_content.size()));
  10019. }
  10020. auto handled = false;
  10021. Server svr;
  10022. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10023. const ContentReader &content_reader) {
  10024. ASSERT_TRUE(req.is_multipart_form_data());
  10025. std::vector<FormData> items;
  10026. content_reader(
  10027. [&](const FormData &file) {
  10028. items.push_back(file);
  10029. return true;
  10030. },
  10031. [&](const char *data, size_t data_length) {
  10032. items.back().content.append(data, data_length);
  10033. return true;
  10034. });
  10035. ASSERT_EQ(1u, items.size());
  10036. EXPECT_EQ("myfile", items[0].name);
  10037. EXPECT_EQ("data.bin", items[0].filename);
  10038. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10039. EXPECT_EQ(file_content, items[0].content);
  10040. handled = true;
  10041. });
  10042. auto port = svr.bind_to_any_port(HOST);
  10043. auto t = thread([&] { svr.listen_after_bind(); });
  10044. auto se = detail::scope_exit([&] {
  10045. svr.stop();
  10046. t.join();
  10047. ASSERT_FALSE(svr.is_running());
  10048. ASSERT_TRUE(handled);
  10049. std::remove(tmp_path.c_str());
  10050. });
  10051. svr.wait_until_ready();
  10052. FormDataProviderItems providers;
  10053. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10054. "application/octet-stream"));
  10055. Client cli(HOST, port);
  10056. auto res = cli.Post("/upload", {}, {}, providers);
  10057. ASSERT_TRUE(res);
  10058. EXPECT_EQ(StatusCode::OK_200, res->status);
  10059. }
  10060. TEST(MakeFileBodyTest, Basic) {
  10061. const std::string file_content(4096, 'Z');
  10062. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10063. {
  10064. std::ofstream ofs(tmp_path, std::ios::binary);
  10065. ofs.write(file_content.data(),
  10066. static_cast<std::streamsize>(file_content.size()));
  10067. }
  10068. auto handled = false;
  10069. Server svr;
  10070. svr.Post("/upload", [&](const Request &req, Response &res) {
  10071. EXPECT_EQ(file_content, req.body);
  10072. handled = true;
  10073. res.status = StatusCode::OK_200;
  10074. });
  10075. auto port = svr.bind_to_any_port(HOST);
  10076. auto t = thread([&] { svr.listen_after_bind(); });
  10077. auto se = detail::scope_exit([&] {
  10078. svr.stop();
  10079. t.join();
  10080. ASSERT_FALSE(svr.is_running());
  10081. ASSERT_TRUE(handled);
  10082. std::remove(tmp_path.c_str());
  10083. });
  10084. svr.wait_until_ready();
  10085. auto fb = make_file_body(tmp_path);
  10086. ASSERT_GT(fb.first, 0u);
  10087. Client cli(HOST, port);
  10088. auto res =
  10089. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10090. ASSERT_TRUE(res);
  10091. EXPECT_EQ(StatusCode::OK_200, res->status);
  10092. }
  10093. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10094. static constexpr unsigned int number_of_tasks{1000000};
  10095. std::atomic_uint count{0};
  10096. std::unique_ptr<TaskQueue> task_queue{
  10097. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10098. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10099. auto queued = task_queue->enqueue(
  10100. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10101. EXPECT_TRUE(queued);
  10102. }
  10103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10104. task_queue->shutdown();
  10105. #else
  10106. EXPECT_NO_THROW(task_queue->shutdown());
  10107. #endif
  10108. EXPECT_EQ(number_of_tasks, count.load());
  10109. }
  10110. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10111. static constexpr unsigned int number_of_tasks{1000000};
  10112. static constexpr unsigned int qlimit{2};
  10113. unsigned int queued_count{0};
  10114. std::atomic_uint count{0};
  10115. std::unique_ptr<TaskQueue> task_queue{
  10116. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10117. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10118. if (task_queue->enqueue(
  10119. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10120. queued_count++;
  10121. }
  10122. }
  10123. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10124. task_queue->shutdown();
  10125. #else
  10126. EXPECT_NO_THROW(task_queue->shutdown());
  10127. #endif
  10128. EXPECT_EQ(queued_count, count.load());
  10129. EXPECT_TRUE(queued_count <= number_of_tasks);
  10130. EXPECT_TRUE(queued_count >= qlimit);
  10131. }
  10132. TEST(TaskQueueTest, MaxQueuedRequests) {
  10133. static constexpr unsigned int qlimit{3};
  10134. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10135. std::condition_variable sem_cv;
  10136. std::mutex sem_mtx;
  10137. int credits = 0;
  10138. bool queued;
  10139. /* Fill up the queue with tasks that will block until we give them credits to
  10140. * complete. */
  10141. for (unsigned int n = 0; n <= qlimit;) {
  10142. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10143. std::unique_lock<std::mutex> lock(sem_mtx);
  10144. while (credits <= 0) {
  10145. sem_cv.wait(lock);
  10146. }
  10147. /* Consume the credit and signal the test code if they are all gone. */
  10148. if (--credits == 0) { sem_cv.notify_one(); }
  10149. });
  10150. if (n < qlimit) {
  10151. /* The first qlimit enqueues must succeed. */
  10152. EXPECT_TRUE(queued);
  10153. } else {
  10154. /* The last one will succeed only when the worker thread
  10155. * starts and dequeues the first blocking task. Although
  10156. * not necessary for the correctness of this test, we sleep for
  10157. * a short while to avoid busy waiting. */
  10158. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10159. }
  10160. if (queued) { n++; }
  10161. }
  10162. /* Further enqueues must fail since the queue is full. */
  10163. for (auto i = 0; i < 4; i++) {
  10164. queued = task_queue->enqueue([] {});
  10165. EXPECT_FALSE(queued);
  10166. }
  10167. /* Give the credits to allow the previous tasks to complete. */
  10168. {
  10169. std::unique_lock<std::mutex> lock(sem_mtx);
  10170. credits += qlimit + 1;
  10171. }
  10172. sem_cv.notify_all();
  10173. /* Wait for all the credits to be consumed. */
  10174. {
  10175. std::unique_lock<std::mutex> lock(sem_mtx);
  10176. while (credits > 0) {
  10177. sem_cv.wait(lock);
  10178. }
  10179. }
  10180. /* Check that we are able again to enqueue at least qlimit tasks. */
  10181. for (unsigned int i = 0; i < qlimit; i++) {
  10182. queued = task_queue->enqueue([] {});
  10183. EXPECT_TRUE(queued);
  10184. }
  10185. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10186. task_queue->shutdown();
  10187. #else
  10188. EXPECT_NO_THROW(task_queue->shutdown());
  10189. #endif
  10190. }
  10191. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10192. Server svr;
  10193. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10194. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10195. });
  10196. svr.Get("/hello", [](const Request &req, Response &res) {
  10197. res.set_content(req.get_param_value("key"), "text/plain");
  10198. });
  10199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10200. auto se = detail::scope_exit([&] {
  10201. svr.stop();
  10202. thread.join();
  10203. ASSERT_FALSE(svr.is_running());
  10204. });
  10205. svr.wait_until_ready();
  10206. {
  10207. Client cli(HOST, PORT);
  10208. cli.set_follow_location(true);
  10209. auto res = cli.Get("/");
  10210. ASSERT_TRUE(res);
  10211. EXPECT_EQ(StatusCode::OK_200, res->status);
  10212. EXPECT_EQ("val&key2=val2", res->body);
  10213. }
  10214. }
  10215. #endif
  10216. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10217. Server svr;
  10218. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10219. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10220. });
  10221. svr.Get("/hello", [](const Request &req, Response &res) {
  10222. res.set_content(req.get_param_value("key"), "text/plain");
  10223. });
  10224. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10225. auto se = detail::scope_exit([&] {
  10226. svr.stop();
  10227. thread.join();
  10228. ASSERT_FALSE(svr.is_running());
  10229. });
  10230. svr.wait_until_ready();
  10231. {
  10232. Client cli(HOST, PORT);
  10233. cli.set_follow_location(true);
  10234. auto res = cli.Get("/");
  10235. ASSERT_TRUE(res);
  10236. EXPECT_EQ(StatusCode::OK_200, res->status);
  10237. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10238. }
  10239. }
  10240. #ifdef CPPHTTPLIB_SSL_ENABLED
  10241. TEST(RedirectTest, Issue2185_Online) {
  10242. SSLClient client("github.com");
  10243. client.set_follow_location(true);
  10244. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10245. "Coollab-Windows.zip");
  10246. ASSERT_TRUE(res);
  10247. EXPECT_EQ(StatusCode::OK_200, res->status);
  10248. EXPECT_EQ(9920427U, res->body.size());
  10249. }
  10250. #endif
  10251. TEST(VulnerabilityTest, CRLFInjection) {
  10252. Server svr;
  10253. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10254. res.set_content("Hello 1", "text/plain");
  10255. });
  10256. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10257. res.set_content("Hello 2", "text/plain");
  10258. });
  10259. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10260. res.set_content("Hello 3", "text/plain");
  10261. });
  10262. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10263. res.set_content("Hello 4", "text/plain");
  10264. });
  10265. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10266. for (const auto &x : req.headers) {
  10267. auto key = x.first;
  10268. EXPECT_STRNE("evil", key.c_str());
  10269. }
  10270. });
  10271. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10272. auto se = detail::scope_exit([&] {
  10273. svr.stop();
  10274. thread.join();
  10275. ASSERT_FALSE(svr.is_running());
  10276. });
  10277. svr.wait_until_ready();
  10278. {
  10279. Client cli(HOST, PORT);
  10280. cli.Post("/test1", "A=B",
  10281. "application/x-www-form-urlencoded\r\nevil: hello1");
  10282. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10283. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10284. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10285. }
  10286. }
  10287. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10288. auto server_thread = std::thread([] {
  10289. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10290. default_socket_options(srv);
  10291. sockaddr_in addr{};
  10292. addr.sin_family = AF_INET;
  10293. addr.sin_port = htons(PORT + 1);
  10294. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10295. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10296. ::listen(srv, 1);
  10297. sockaddr_in cli_addr{};
  10298. socklen_t cli_len = sizeof(cli_addr);
  10299. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10300. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10301. std::string buf_all;
  10302. char buf[2048];
  10303. ssize_t n;
  10304. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10305. buf_all.append(buf, static_cast<size_t>(n));
  10306. size_t pos;
  10307. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10308. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10309. auto e = request_block.find("\r\n");
  10310. if (e != std::string::npos) {
  10311. auto request_line = request_block.substr(0, e);
  10312. std::string msg =
  10313. "CRLF injection detected in request line: '" + request_line + "'";
  10314. EXPECT_FALSE(true) << msg;
  10315. }
  10316. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10317. ::send(cli,
  10318. #ifdef _WIN32
  10319. static_cast<const char *>(resp.c_str()),
  10320. static_cast<int>(resp.size()),
  10321. #else
  10322. resp.c_str(), resp.size(),
  10323. #endif
  10324. 0);
  10325. buf_all.erase(0, pos + 4);
  10326. }
  10327. }
  10328. detail::close_socket(cli);
  10329. detail::close_socket(srv);
  10330. });
  10331. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10332. auto cli = Client("127.0.0.1", PORT + 1);
  10333. auto headers = Headers{
  10334. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10335. {"Connection", "keep-alive"}};
  10336. auto res = cli.Get("/hi", headers);
  10337. EXPECT_FALSE(res);
  10338. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10339. server_thread.join();
  10340. }
  10341. TEST(PathParamsTest, StaticMatch) {
  10342. const auto pattern = "/users/all";
  10343. detail::PathParamsMatcher matcher(pattern);
  10344. Request request;
  10345. request.path = "/users/all";
  10346. ASSERT_TRUE(matcher.match(request));
  10347. std::unordered_map<std::string, std::string> expected_params = {};
  10348. EXPECT_EQ(request.path_params, expected_params);
  10349. }
  10350. TEST(PathParamsTest, StaticMismatch) {
  10351. const auto pattern = "/users/all";
  10352. detail::PathParamsMatcher matcher(pattern);
  10353. Request request;
  10354. request.path = "/users/1";
  10355. ASSERT_FALSE(matcher.match(request));
  10356. }
  10357. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10358. const auto pattern = "/users/:id/subscriptions";
  10359. detail::PathParamsMatcher matcher(pattern);
  10360. Request request;
  10361. request.path = "/users/42/subscriptions";
  10362. ASSERT_TRUE(matcher.match(request));
  10363. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10364. EXPECT_EQ(request.path_params, expected_params);
  10365. }
  10366. TEST(PathParamsTest, SingleParamInTheEnd) {
  10367. const auto pattern = "/users/:id";
  10368. detail::PathParamsMatcher matcher(pattern);
  10369. Request request;
  10370. request.path = "/users/24";
  10371. ASSERT_TRUE(matcher.match(request));
  10372. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10373. EXPECT_EQ(request.path_params, expected_params);
  10374. }
  10375. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10376. const auto pattern = "/users/:id/";
  10377. detail::PathParamsMatcher matcher(pattern);
  10378. Request request;
  10379. request.path = "/users/42/";
  10380. ASSERT_TRUE(matcher.match(request));
  10381. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10382. EXPECT_EQ(request.path_params, expected_params);
  10383. }
  10384. TEST(PathParamsTest, EmptyParam) {
  10385. const auto pattern = "/users/:id/";
  10386. detail::PathParamsMatcher matcher(pattern);
  10387. Request request;
  10388. request.path = "/users//";
  10389. ASSERT_TRUE(matcher.match(request));
  10390. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10391. EXPECT_EQ(request.path_params, expected_params);
  10392. }
  10393. TEST(PathParamsTest, FragmentMismatch) {
  10394. const auto pattern = "/users/:id/";
  10395. detail::PathParamsMatcher matcher(pattern);
  10396. Request request;
  10397. request.path = "/admins/24/";
  10398. ASSERT_FALSE(matcher.match(request));
  10399. }
  10400. TEST(PathParamsTest, ExtraFragments) {
  10401. const auto pattern = "/users/:id";
  10402. detail::PathParamsMatcher matcher(pattern);
  10403. Request request;
  10404. request.path = "/users/42/subscriptions";
  10405. ASSERT_FALSE(matcher.match(request));
  10406. }
  10407. TEST(PathParamsTest, MissingTrailingParam) {
  10408. const auto pattern = "/users/:id";
  10409. detail::PathParamsMatcher matcher(pattern);
  10410. Request request;
  10411. request.path = "/users";
  10412. ASSERT_FALSE(matcher.match(request));
  10413. }
  10414. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10415. const auto pattern = "/users/:id/subscriptions";
  10416. detail::PathParamsMatcher matcher(pattern);
  10417. Request request;
  10418. request.path = "/users/subscriptions";
  10419. ASSERT_FALSE(matcher.match(request));
  10420. }
  10421. TEST(PathParamsTest, MultipleParams) {
  10422. const auto pattern = "/users/:userid/subscriptions/:subid";
  10423. detail::PathParamsMatcher matcher(pattern);
  10424. Request request;
  10425. request.path = "/users/42/subscriptions/2";
  10426. ASSERT_TRUE(matcher.match(request));
  10427. std::unordered_map<std::string, std::string> expected_params = {
  10428. {"userid", "42"}, {"subid", "2"}};
  10429. EXPECT_EQ(request.path_params, expected_params);
  10430. }
  10431. TEST(PathParamsTest, SequenceOfParams) {
  10432. const auto pattern = "/values/:x/:y/:z";
  10433. detail::PathParamsMatcher matcher(pattern);
  10434. Request request;
  10435. request.path = "/values/1/2/3";
  10436. ASSERT_TRUE(matcher.match(request));
  10437. std::unordered_map<std::string, std::string> expected_params = {
  10438. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10439. EXPECT_EQ(request.path_params, expected_params);
  10440. }
  10441. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10442. const auto pattern = "/prefix:suffix";
  10443. detail::PathParamsMatcher matcher(pattern);
  10444. Request request;
  10445. request.path = "/prefix:suffix";
  10446. ASSERT_TRUE(matcher.match(request));
  10447. const std::unordered_map<std::string, std::string> expected_params = {};
  10448. EXPECT_EQ(request.path_params, expected_params);
  10449. }
  10450. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10451. // If ipv6 regex working, regex match codepath is taken.
  10452. // else port will default to 80 in Client impl
  10453. int clientImplMagicPort = 80;
  10454. int port = 4321;
  10455. // above ports must be different to avoid false negative
  10456. EXPECT_NE(clientImplMagicPort, port);
  10457. std::string ipV6TestURL = "http://[ff06::c3]";
  10458. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10459. CLIENT_PRIVATE_KEY_FILE);
  10460. EXPECT_EQ(cli.port(), port);
  10461. }
  10462. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10463. auto file_path = "./www/dir/index.html";
  10464. auto dir_path = "./www/dir";
  10465. detail::FileStat stat_file(file_path);
  10466. EXPECT_TRUE(stat_file.is_file());
  10467. EXPECT_FALSE(stat_file.is_dir());
  10468. detail::FileStat stat_dir(dir_path);
  10469. EXPECT_FALSE(stat_dir.is_file());
  10470. EXPECT_TRUE(stat_dir.is_dir());
  10471. }
  10472. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10473. // IPv4 with default HTTP port (80)
  10474. EXPECT_EQ("example.com",
  10475. detail::make_host_and_port_string("example.com", 80, false));
  10476. // IPv4 with default HTTPS port (443)
  10477. EXPECT_EQ("example.com",
  10478. detail::make_host_and_port_string("example.com", 443, true));
  10479. // IPv4 with non-default HTTP port
  10480. EXPECT_EQ("example.com:8080",
  10481. detail::make_host_and_port_string("example.com", 8080, false));
  10482. // IPv4 with non-default HTTPS port
  10483. EXPECT_EQ("example.com:8443",
  10484. detail::make_host_and_port_string("example.com", 8443, true));
  10485. // IPv6 with default HTTP port (80)
  10486. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10487. // IPv6 with default HTTPS port (443)
  10488. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10489. // IPv6 with non-default HTTP port
  10490. EXPECT_EQ("[::1]:8080",
  10491. detail::make_host_and_port_string("::1", 8080, false));
  10492. // IPv6 with non-default HTTPS port
  10493. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10494. // IPv6 full address with default port
  10495. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10496. detail::make_host_and_port_string(
  10497. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10498. // IPv6 full address with non-default port
  10499. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10500. detail::make_host_and_port_string(
  10501. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10502. // IPv6 localhost with non-default port
  10503. EXPECT_EQ("[::1]:3000",
  10504. detail::make_host_and_port_string("::1", 3000, false));
  10505. // IPv6 with zone ID (link-local address) with default port
  10506. EXPECT_EQ("[fe80::1%eth0]",
  10507. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10508. // IPv6 with zone ID (link-local address) with non-default port
  10509. EXPECT_EQ("[fe80::1%eth0]:8080",
  10510. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10511. // Edge case: Port 443 with is_ssl=false (should add port)
  10512. EXPECT_EQ("example.com:443",
  10513. detail::make_host_and_port_string("example.com", 443, false));
  10514. // Edge case: Port 80 with is_ssl=true (should add port)
  10515. EXPECT_EQ("example.com:80",
  10516. detail::make_host_and_port_string("example.com", 80, true));
  10517. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10518. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10519. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10520. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10521. // Security fix: Already bracketed IPv6 should not get double brackets
  10522. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10523. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10524. EXPECT_EQ("[::1]:8080",
  10525. detail::make_host_and_port_string("[::1]", 8080, false));
  10526. EXPECT_EQ("[2001:db8::1]:8080",
  10527. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10528. EXPECT_EQ("[fe80::1%eth0]",
  10529. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10530. EXPECT_EQ("[fe80::1%eth0]:8080",
  10531. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10532. // Edge case: Empty host (should return as-is)
  10533. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10534. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10535. // This is a known limitation but shouldn't crash
  10536. EXPECT_EQ("[host:name]",
  10537. detail::make_host_and_port_string("host:name", 80, false));
  10538. // Port number edge cases (no validation, but should not crash)
  10539. EXPECT_EQ("example.com:0",
  10540. detail::make_host_and_port_string("example.com", 0, false));
  10541. EXPECT_EQ("example.com:-1",
  10542. detail::make_host_and_port_string("example.com", -1, false));
  10543. EXPECT_EQ("example.com:65535",
  10544. detail::make_host_and_port_string("example.com", 65535, false));
  10545. EXPECT_EQ("example.com:65536",
  10546. detail::make_host_and_port_string("example.com", 65536, false));
  10547. }
  10548. #ifdef CPPHTTPLIB_SSL_ENABLED
  10549. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10550. httplib::SSLClient cli("roblox.com", 443);
  10551. cli.set_follow_location(true);
  10552. auto res = cli.Get("/");
  10553. ASSERT_TRUE(res);
  10554. EXPECT_EQ(StatusCode::OK_200, res->status);
  10555. }
  10556. #endif
  10557. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10558. Server svr;
  10559. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10560. EXPECT_EQ(res.status, 400);
  10561. });
  10562. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10563. auto se = detail::scope_exit([&] {
  10564. svr.stop();
  10565. thread.join();
  10566. ASSERT_FALSE(svr.is_running());
  10567. });
  10568. svr.wait_until_ready();
  10569. Client cli(HOST, PORT);
  10570. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10571. }
  10572. TEST(InvalidHeaderCharsTest, is_field_name) {
  10573. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10574. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10575. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10576. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10577. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10578. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10579. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10580. EXPECT_FALSE(detail::fields::is_field_name(""));
  10581. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10582. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10583. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10584. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10585. }
  10586. TEST(InvalidHeaderCharsTest, is_field_value) {
  10587. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10588. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10589. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10590. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10591. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10592. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10593. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10594. EXPECT_TRUE(detail::fields::is_field_value(""));
  10595. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10596. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10597. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10598. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10599. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10600. }
  10601. TEST(InvalidHeaderCharsTest, OnServer) {
  10602. Server svr;
  10603. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10604. std::string header = "Not Set";
  10605. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10606. res.set_header(header, "value");
  10607. res.set_content("Page Content Page Content", "text/plain");
  10608. });
  10609. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10610. std::string header = "Not Set";
  10611. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10612. res.set_header("X-Test", header);
  10613. res.set_content("Page Content Page Content", "text/plain");
  10614. });
  10615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10616. auto se = detail::scope_exit([&] {
  10617. svr.stop();
  10618. thread.join();
  10619. ASSERT_FALSE(svr.is_running());
  10620. });
  10621. svr.wait_until_ready();
  10622. Client cli(HOST, PORT);
  10623. {
  10624. auto res = cli.Get(
  10625. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10626. ASSERT_TRUE(res);
  10627. EXPECT_EQ("Page Content Page Content", res->body);
  10628. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10629. }
  10630. {
  10631. auto res = cli.Get(
  10632. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10633. ASSERT_TRUE(res);
  10634. EXPECT_EQ("Page Content Page Content", res->body);
  10635. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10636. }
  10637. }
  10638. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10639. auto handled = false;
  10640. Server svr;
  10641. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10642. thread t = thread([&] { svr.listen(HOST, PORT); });
  10643. auto se = detail::scope_exit([&] {
  10644. svr.stop();
  10645. t.join();
  10646. ASSERT_FALSE(svr.is_running());
  10647. ASSERT_FALSE(handled);
  10648. });
  10649. svr.wait_until_ready();
  10650. auto req = "POST /test HTTP/1.1\r\n"
  10651. "Content-Length: x\r\n"
  10652. "\r\n";
  10653. std::string response;
  10654. ASSERT_TRUE(send_request(1, req, &response));
  10655. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10656. response.substr(0, response.find("\r\n")));
  10657. }
  10658. #ifndef _WIN32
  10659. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10660. static constexpr char reject[] = "Unauthorized";
  10661. static constexpr char accept[] = "Upload accepted";
  10662. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10663. Server svr;
  10664. svr.set_expect_100_continue_handler(
  10665. [](const Request & /*req*/, Response &res) {
  10666. res.status = StatusCode::Unauthorized_401;
  10667. res.set_content(reject, "text/plain");
  10668. return res.status;
  10669. });
  10670. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10671. res.set_content(accept, "text/plain");
  10672. });
  10673. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10674. auto se = detail::scope_exit([&] {
  10675. svr.stop();
  10676. thread.join();
  10677. ASSERT_FALSE(svr.is_running());
  10678. });
  10679. svr.wait_until_ready();
  10680. {
  10681. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10682. curl_easy_init(), &curl_easy_cleanup};
  10683. ASSERT_NE(curl, nullptr);
  10684. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10685. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10686. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10687. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10688. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10689. &curl_slist_free_all};
  10690. ASSERT_NE(list, nullptr);
  10691. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10692. struct read_data {
  10693. size_t read_size;
  10694. size_t total_size;
  10695. } data = {0, total_size};
  10696. using read_callback_t =
  10697. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10698. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10699. void *userdata) -> size_t {
  10700. read_data *data = (read_data *)userdata;
  10701. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10702. std::fill_n(ptr, size * nmemb, 'A');
  10703. data->read_size += size * nmemb;
  10704. return size * nmemb;
  10705. };
  10706. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10707. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10708. std::vector<char> buffer;
  10709. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10710. using write_callback_t =
  10711. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10712. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10713. void *userdata) -> size_t {
  10714. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10715. buffer->reserve(buffer->size() + size * nmemb + 1);
  10716. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10717. return size * nmemb;
  10718. };
  10719. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10720. {
  10721. const auto res = curl_easy_perform(curl.get());
  10722. ASSERT_EQ(res, CURLE_OK);
  10723. }
  10724. {
  10725. auto response_code = long{};
  10726. const auto res =
  10727. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10728. ASSERT_EQ(res, CURLE_OK);
  10729. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10730. }
  10731. {
  10732. auto dl = curl_off_t{};
  10733. const auto res =
  10734. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10735. ASSERT_EQ(res, CURLE_OK);
  10736. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10737. }
  10738. {
  10739. buffer.push_back('\0');
  10740. ASSERT_STRCASEEQ(buffer.data(), reject);
  10741. }
  10742. }
  10743. }
  10744. #endif
  10745. template <typename S, typename C>
  10746. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10747. svr.Get("/stream", [&](const Request &, Response &res) {
  10748. auto data = new std::string("01234567890123456789");
  10749. res.set_content_provider(
  10750. data->size(), "text/plain",
  10751. [&, data](size_t offset, size_t length, DataSink &sink) {
  10752. const size_t DATA_CHUNK_SIZE = 4;
  10753. const auto &d = *data;
  10754. std::this_thread::sleep_for(std::chrono::seconds(1));
  10755. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10756. return true;
  10757. },
  10758. [data](bool success) {
  10759. EXPECT_FALSE(success);
  10760. delete data;
  10761. });
  10762. });
  10763. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10764. auto i = new size_t(0);
  10765. res.set_content_provider(
  10766. "text/plain",
  10767. [i](size_t, DataSink &sink) {
  10768. if (*i < 5) {
  10769. std::this_thread::sleep_for(std::chrono::seconds(1));
  10770. sink.write("abcd", 4);
  10771. (*i)++;
  10772. } else {
  10773. sink.done();
  10774. }
  10775. return true;
  10776. },
  10777. [i](bool success) {
  10778. EXPECT_FALSE(success);
  10779. delete i;
  10780. });
  10781. });
  10782. svr.Get("/chunked", [&](const Request &, Response &res) {
  10783. auto i = new size_t(0);
  10784. res.set_chunked_content_provider(
  10785. "text/plain",
  10786. [i](size_t, DataSink &sink) {
  10787. if (*i < 5) {
  10788. std::this_thread::sleep_for(std::chrono::seconds(1));
  10789. sink.os << "abcd";
  10790. (*i)++;
  10791. } else {
  10792. sink.done();
  10793. }
  10794. return true;
  10795. },
  10796. [i](bool success) {
  10797. EXPECT_FALSE(success);
  10798. delete i;
  10799. });
  10800. });
  10801. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10802. auto se = detail::scope_exit([&] {
  10803. svr.stop();
  10804. listen_thread.join();
  10805. ASSERT_FALSE(svr.is_running());
  10806. });
  10807. svr.wait_until_ready();
  10808. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10809. {
  10810. auto start = std::chrono::steady_clock::now();
  10811. auto res = cli.Get("/stream");
  10812. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10813. std::chrono::steady_clock::now() - start)
  10814. .count();
  10815. ASSERT_FALSE(res);
  10816. EXPECT_EQ(Error::Read, res.error());
  10817. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10818. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10819. }
  10820. {
  10821. auto start = std::chrono::steady_clock::now();
  10822. auto res = cli.Get("/stream_without_length");
  10823. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10824. std::chrono::steady_clock::now() - start)
  10825. .count();
  10826. ASSERT_FALSE(res);
  10827. EXPECT_EQ(Error::Read, res.error());
  10828. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10829. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10830. }
  10831. {
  10832. auto start = std::chrono::steady_clock::now();
  10833. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10834. EXPECT_EQ("abcd", string(data, data_length));
  10835. return true;
  10836. });
  10837. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10838. std::chrono::steady_clock::now() - start)
  10839. .count();
  10840. ASSERT_FALSE(res);
  10841. EXPECT_EQ(Error::Read, res.error());
  10842. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10843. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10844. }
  10845. }
  10846. TEST(MaxTimeoutTest, ContentStream) {
  10847. time_t timeout = 2000;
  10848. time_t threshold = 200;
  10849. Server svr;
  10850. Client cli("localhost", PORT);
  10851. max_timeout_test(svr, cli, timeout, threshold);
  10852. }
  10853. #ifdef CPPHTTPLIB_SSL_ENABLED
  10854. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10855. time_t timeout = 2000;
  10856. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10858. SSLClient cli("localhost", PORT);
  10859. cli.enable_server_certificate_verification(false);
  10860. max_timeout_test(svr, cli, timeout, threshold);
  10861. }
  10862. #endif
  10863. class EventDispatcher {
  10864. public:
  10865. EventDispatcher() {}
  10866. bool wait_event(DataSink *sink) {
  10867. unique_lock<mutex> lk(m_);
  10868. int id = id_;
  10869. // Wait with timeout to prevent hanging if client disconnects
  10870. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10871. [&] { return cid_ == id; })) {
  10872. return false; // Timeout occurred
  10873. }
  10874. sink->write(message_.data(), message_.size());
  10875. return true;
  10876. }
  10877. void send_event(const string &message) {
  10878. lock_guard<mutex> lk(m_);
  10879. cid_ = id_++;
  10880. message_ = message;
  10881. cv_.notify_all();
  10882. }
  10883. private:
  10884. mutex m_;
  10885. condition_variable cv_;
  10886. atomic_int id_{0};
  10887. atomic_int cid_{-1};
  10888. string message_;
  10889. };
  10890. TEST(ClientInThreadTest, Issue2068) {
  10891. EventDispatcher ed;
  10892. Server svr;
  10893. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10894. res.set_chunked_content_provider("text/event-stream",
  10895. [&](size_t /*offset*/, DataSink &sink) {
  10896. return ed.wait_event(&sink);
  10897. });
  10898. });
  10899. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10900. svr.wait_until_ready();
  10901. thread event_thread([&] {
  10902. int id = 0;
  10903. while (svr.is_running()) {
  10904. this_thread::sleep_for(chrono::milliseconds(500));
  10905. std::stringstream ss;
  10906. ss << "data: " << id << "\n\n";
  10907. ed.send_event(ss.str());
  10908. id++;
  10909. }
  10910. });
  10911. auto se = detail::scope_exit([&] {
  10912. svr.stop();
  10913. listen_thread.join();
  10914. event_thread.join();
  10915. ASSERT_FALSE(svr.is_running());
  10916. });
  10917. {
  10918. auto client = detail::make_unique<Client>(HOST, PORT);
  10919. client->set_read_timeout(std::chrono::minutes(10));
  10920. std::atomic<bool> stop{false};
  10921. std::thread t([&] {
  10922. client->Get("/event1",
  10923. [&](const char *, size_t) -> bool { return !stop; });
  10924. });
  10925. std::this_thread::sleep_for(std::chrono::seconds(2));
  10926. stop = true;
  10927. client->stop();
  10928. t.join();
  10929. // Reset client after thread has finished
  10930. client.reset();
  10931. }
  10932. }
  10933. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10934. auto handled = false;
  10935. Server svr;
  10936. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10937. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. t.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. ASSERT_FALSE(handled);
  10943. });
  10944. svr.wait_until_ready();
  10945. // Two Content-Length headers with different values — must be rejected
  10946. auto req = "POST /test HTTP/1.1\r\n"
  10947. "Content-Length: 5\r\n"
  10948. "Content-Length: 10\r\n"
  10949. "\r\n"
  10950. "hello";
  10951. std::string response;
  10952. ASSERT_TRUE(send_request(1, req, &response));
  10953. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10954. response.substr(0, response.find("\r\n")));
  10955. }
  10956. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10957. auto handled = false;
  10958. Server svr;
  10959. svr.Post("/test", [&](const Request &, Response &res) {
  10960. handled = true;
  10961. res.set_content("ok", "text/plain");
  10962. });
  10963. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10964. auto se = detail::scope_exit([&] {
  10965. svr.stop();
  10966. t.join();
  10967. ASSERT_FALSE(svr.is_running());
  10968. ASSERT_TRUE(handled);
  10969. });
  10970. svr.wait_until_ready();
  10971. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  10972. auto req = "POST /test HTTP/1.1\r\n"
  10973. "Content-Length: 5\r\n"
  10974. "Content-Length: 5\r\n"
  10975. "\r\n"
  10976. "hello";
  10977. std::string response;
  10978. ASSERT_TRUE(send_request(1, req, &response));
  10979. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  10980. }
  10981. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10982. Server svr;
  10983. svr.Get("/", [](const Request &req, Response &res) {
  10984. EXPECT_EQ(2U, req.trailers.size());
  10985. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10986. // Denied
  10987. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10988. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10989. // Accepted
  10990. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10991. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10992. EXPECT_TRUE(req.has_trailer("X-World"));
  10993. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10994. res.set_content("ok", "text/plain");
  10995. });
  10996. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10997. auto se = detail::scope_exit([&] {
  10998. svr.stop();
  10999. t.join();
  11000. ASSERT_FALSE(svr.is_running());
  11001. });
  11002. svr.wait_until_ready();
  11003. const std::string req = "GET / HTTP/1.1\r\n"
  11004. "Transfer-Encoding: chunked\r\n"
  11005. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11006. "\r\n"
  11007. "0\r\n"
  11008. "Content-Length: 10\r\n"
  11009. "Host: internal.local\r\n"
  11010. "Content-Type: malicious/content\r\n"
  11011. "Cookie: any\r\n"
  11012. "Set-Cookie: any\r\n"
  11013. "X-Forwarded-For: attacker.com\r\n"
  11014. "X-Real-Ip: 1.1.1.1\r\n"
  11015. "X-Hello: hello\r\n"
  11016. "X-World: world\r\n"
  11017. "\r\n";
  11018. std::string res;
  11019. ASSERT_TRUE(send_request(1, req, &res));
  11020. }
  11021. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11022. Server svr;
  11023. std::string observed_remote_addr;
  11024. std::string observed_xff;
  11025. svr.Get("/ip", [&](const Request &req, Response &res) {
  11026. observed_remote_addr = req.remote_addr;
  11027. observed_xff = req.get_header_value("X-Forwarded-For");
  11028. res.set_content("ok", "text/plain");
  11029. });
  11030. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11031. auto se = detail::scope_exit([&] {
  11032. svr.stop();
  11033. t.join();
  11034. ASSERT_FALSE(svr.is_running());
  11035. });
  11036. svr.wait_until_ready();
  11037. Client cli(HOST, PORT);
  11038. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11039. ASSERT_TRUE(res);
  11040. EXPECT_EQ(StatusCode::OK_200, res->status);
  11041. EXPECT_EQ(observed_xff, "203.0.113.66");
  11042. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11043. observed_remote_addr == "127.0.0.1");
  11044. }
  11045. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11046. Server svr;
  11047. svr.set_trusted_proxies({"203.0.113.66"});
  11048. std::string observed_remote_addr;
  11049. std::string observed_xff;
  11050. svr.Get("/ip", [&](const Request &req, Response &res) {
  11051. observed_remote_addr = req.remote_addr;
  11052. observed_xff = req.get_header_value("X-Forwarded-For");
  11053. res.set_content("ok", "text/plain");
  11054. });
  11055. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11056. auto se = detail::scope_exit([&] {
  11057. svr.stop();
  11058. t.join();
  11059. ASSERT_FALSE(svr.is_running());
  11060. });
  11061. svr.wait_until_ready();
  11062. Client cli(HOST, PORT);
  11063. auto res = cli.Get("/ip");
  11064. ASSERT_TRUE(res);
  11065. EXPECT_EQ(StatusCode::OK_200, res->status);
  11066. EXPECT_EQ(observed_xff, "");
  11067. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11068. observed_remote_addr == "127.0.0.1");
  11069. }
  11070. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11071. Server svr;
  11072. svr.set_trusted_proxies({"203.0.113.66"});
  11073. std::string observed_remote_addr;
  11074. std::string observed_xff;
  11075. svr.Get("/ip", [&](const Request &req, Response &res) {
  11076. observed_remote_addr = req.remote_addr;
  11077. observed_xff = req.get_header_value("X-Forwarded-For");
  11078. res.set_content("ok", "text/plain");
  11079. });
  11080. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11081. auto se = detail::scope_exit([&] {
  11082. svr.stop();
  11083. t.join();
  11084. ASSERT_FALSE(svr.is_running());
  11085. });
  11086. svr.wait_until_ready();
  11087. Client cli(HOST, PORT);
  11088. auto res =
  11089. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11090. ASSERT_TRUE(res);
  11091. EXPECT_EQ(StatusCode::OK_200, res->status);
  11092. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11093. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11094. }
  11095. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11096. Server svr;
  11097. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11098. std::string observed_remote_addr;
  11099. std::string observed_xff;
  11100. svr.Get("/ip", [&](const Request &req, Response &res) {
  11101. observed_remote_addr = req.remote_addr;
  11102. observed_xff = req.get_header_value("X-Forwarded-For");
  11103. res.set_content("ok", "text/plain");
  11104. });
  11105. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11106. auto se = detail::scope_exit([&] {
  11107. svr.stop();
  11108. t.join();
  11109. ASSERT_FALSE(svr.is_running());
  11110. });
  11111. svr.wait_until_ready();
  11112. Client cli(HOST, PORT);
  11113. auto res = cli.Get(
  11114. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11115. ASSERT_TRUE(res);
  11116. EXPECT_EQ(StatusCode::OK_200, res->status);
  11117. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11118. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11119. }
  11120. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11121. Server svr;
  11122. svr.set_trusted_proxies({"192.0.2.45"});
  11123. std::string observed_remote_addr;
  11124. std::string observed_xff;
  11125. svr.Get("/ip", [&](const Request &req, Response &res) {
  11126. observed_remote_addr = req.remote_addr;
  11127. observed_xff = req.get_header_value("X-Forwarded-For");
  11128. res.set_content("ok", "text/plain");
  11129. });
  11130. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11131. auto se = detail::scope_exit([&] {
  11132. svr.stop();
  11133. t.join();
  11134. ASSERT_FALSE(svr.is_running());
  11135. });
  11136. svr.wait_until_ready();
  11137. Client cli(HOST, PORT);
  11138. auto res =
  11139. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11140. ASSERT_TRUE(res);
  11141. EXPECT_EQ(StatusCode::OK_200, res->status);
  11142. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11143. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11144. }
  11145. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11146. Server svr;
  11147. svr.set_trusted_proxies({"192.0.2.45"});
  11148. std::string observed_remote_addr;
  11149. std::string observed_xff;
  11150. svr.Get("/ip", [&](const Request &req, Response &res) {
  11151. observed_remote_addr = req.remote_addr;
  11152. observed_xff = req.get_header_value("X-Forwarded-For");
  11153. res.set_content("ok", "text/plain");
  11154. });
  11155. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11156. auto se = detail::scope_exit([&] {
  11157. svr.stop();
  11158. t.join();
  11159. ASSERT_FALSE(svr.is_running());
  11160. });
  11161. svr.wait_until_ready();
  11162. Client cli(HOST, PORT);
  11163. auto res = cli.Get(
  11164. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11165. ASSERT_TRUE(res);
  11166. EXPECT_EQ(StatusCode::OK_200, res->status);
  11167. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11168. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11169. }
  11170. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11171. Server svr;
  11172. svr.set_trusted_proxies({"192.0.2.45"});
  11173. std::string observed_remote_addr;
  11174. std::string observed_xff;
  11175. svr.Get("/ip", [&](const Request &req, Response &res) {
  11176. observed_remote_addr = req.remote_addr;
  11177. observed_xff = req.get_header_value("X-Forwarded-For");
  11178. res.set_content("ok", "text/plain");
  11179. });
  11180. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11181. auto se = detail::scope_exit([&] {
  11182. svr.stop();
  11183. t.join();
  11184. ASSERT_FALSE(svr.is_running());
  11185. });
  11186. svr.wait_until_ready();
  11187. std::string raw_req =
  11188. "GET /ip HTTP/1.1\r\n"
  11189. "Host: localhost\r\n"
  11190. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11191. "Connection: close\r\n"
  11192. "\r\n";
  11193. std::string out;
  11194. ASSERT_TRUE(send_request(5, raw_req, &out));
  11195. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11196. // Header parser trims surrounding whitespace of the header value
  11197. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11198. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11199. }
  11200. #ifndef _WIN32
  11201. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11202. Server svr;
  11203. svr.Post("/post", [&](const Request &req, Response &res) {
  11204. res.set_content(req.body, "text/plain");
  11205. });
  11206. svr.Put("/put", [&](const Request &req, Response &res) {
  11207. res.set_content(req.body, "text/plain");
  11208. });
  11209. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11210. res.set_content(req.body, "text/plain");
  11211. });
  11212. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11213. res.set_content(req.body, "text/plain");
  11214. });
  11215. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11216. auto se = detail::scope_exit([&] {
  11217. svr.stop();
  11218. t.join();
  11219. ASSERT_FALSE(svr.is_running());
  11220. });
  11221. svr.wait_until_ready();
  11222. std::string resp;
  11223. // POST without Content-Length
  11224. ASSERT_TRUE(send_request(5,
  11225. "POST /post HTTP/1.1\r\n"
  11226. "Host: localhost\r\n"
  11227. "Connection: close\r\n"
  11228. "\r\n",
  11229. &resp));
  11230. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11231. // PUT without Content-Length
  11232. resp.clear();
  11233. ASSERT_TRUE(send_request(5,
  11234. "PUT /put HTTP/1.1\r\n"
  11235. "Host: localhost\r\n"
  11236. "Connection: close\r\n"
  11237. "\r\n",
  11238. &resp));
  11239. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11240. // PATCH without Content-Length
  11241. resp.clear();
  11242. ASSERT_TRUE(send_request(5,
  11243. "PATCH /patch HTTP/1.1\r\n"
  11244. "Host: localhost\r\n"
  11245. "Connection: close\r\n"
  11246. "\r\n",
  11247. &resp));
  11248. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11249. // DELETE without Content-Length
  11250. resp.clear();
  11251. ASSERT_TRUE(send_request(5,
  11252. "DELETE /delete HTTP/1.1\r\n"
  11253. "Host: localhost\r\n"
  11254. "Connection: close\r\n"
  11255. "\r\n",
  11256. &resp));
  11257. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11258. }
  11259. #endif
  11260. //==============================================================================
  11261. // open_stream() Tests
  11262. //==============================================================================
  11263. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11264. std::string result;
  11265. char buf[8192];
  11266. ssize_t n;
  11267. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11268. result.append(buf, static_cast<size_t>(n));
  11269. }
  11270. return result;
  11271. }
  11272. // Mock stream for unit tests
  11273. class MockStream : public Stream {
  11274. public:
  11275. std::string data;
  11276. size_t pos = 0;
  11277. ssize_t error_after = -1; // -1 = no error
  11278. explicit MockStream(const std::string &d, ssize_t err = -1)
  11279. : data(d), error_after(err) {}
  11280. bool is_readable() const override { return true; }
  11281. bool wait_readable() const override { return true; }
  11282. bool wait_writable() const override { return true; }
  11283. ssize_t read(char *ptr, size_t size) override {
  11284. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11285. if (pos >= data.size()) return 0;
  11286. size_t limit =
  11287. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11288. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11289. std::memcpy(ptr, data.data() + pos, to_read);
  11290. pos += to_read;
  11291. return static_cast<ssize_t>(to_read);
  11292. }
  11293. ssize_t write(const char *, size_t) override { return -1; }
  11294. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11295. ip = "127.0.0.1";
  11296. port = 0;
  11297. }
  11298. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11299. ip = "127.0.0.1";
  11300. port = 0;
  11301. }
  11302. socket_t socket() const override { return INVALID_SOCKET; }
  11303. time_t duration() const override { return 0; }
  11304. };
  11305. TEST(StreamHandleTest, Basic) {
  11306. ClientImpl::StreamHandle handle;
  11307. EXPECT_FALSE(handle.is_valid());
  11308. handle.response = detail::make_unique<Response>();
  11309. handle.error = Error::Connection;
  11310. EXPECT_FALSE(handle.is_valid());
  11311. handle.error = Error::Success;
  11312. EXPECT_TRUE(handle.is_valid());
  11313. }
  11314. TEST(BodyReaderTest, Basic) {
  11315. MockStream stream("Hello, World!");
  11316. detail::BodyReader reader;
  11317. reader.stream = &stream;
  11318. reader.content_length = 13;
  11319. char buf[32];
  11320. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11321. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11322. EXPECT_TRUE(reader.eof);
  11323. }
  11324. TEST(BodyReaderTest, NoStream) {
  11325. detail::BodyReader reader;
  11326. char buf[32];
  11327. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11328. EXPECT_EQ(Error::Connection, reader.last_error);
  11329. }
  11330. TEST(BodyReaderTest, Error) {
  11331. MockStream stream("Hello, World!", 5);
  11332. detail::BodyReader reader;
  11333. reader.stream = &stream;
  11334. reader.content_length = 13;
  11335. char buf[32];
  11336. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11337. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11338. EXPECT_EQ(Error::Read, reader.last_error);
  11339. }
  11340. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11341. // Mock-based StreamHandle tests relying on private internals are removed.
  11342. class OpenStreamTest : public ::testing::Test {
  11343. protected:
  11344. void SetUp() override {
  11345. svr_.Get("/hello", [](const Request &, Response &res) {
  11346. res.set_content("Hello World!", "text/plain");
  11347. });
  11348. svr_.Get("/large", [](const Request &, Response &res) {
  11349. res.set_content(std::string(10000, 'X'), "text/plain");
  11350. });
  11351. svr_.Get("/chunked", [](const Request &, Response &res) {
  11352. res.set_chunked_content_provider("text/plain",
  11353. [](size_t offset, DataSink &sink) {
  11354. if (offset < 15) {
  11355. sink.write("chunk", 5);
  11356. return true;
  11357. }
  11358. sink.done();
  11359. return true;
  11360. });
  11361. });
  11362. svr_.Get("/compressible", [](const Request &, Response &res) {
  11363. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11364. DataSink &sink) {
  11365. if (offset < 100 * 1024) {
  11366. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11367. sink.write(chunk.data(), chunk.size());
  11368. return true;
  11369. }
  11370. sink.done();
  11371. return true;
  11372. });
  11373. });
  11374. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11375. [](const Request & /*req*/, Response &res) {
  11376. auto i = new int(0);
  11377. res.set_header("Trailer", "Content-Length, X-Allowed");
  11378. res.set_chunked_content_provider(
  11379. "text/plain",
  11380. [i](size_t /*offset*/, DataSink &sink) {
  11381. switch (*i) {
  11382. case 0: sink.os << "123"; break;
  11383. case 1: sink.os << "456"; break;
  11384. case 2: sink.os << "789"; break;
  11385. case 3: {
  11386. sink.done_with_trailer(
  11387. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11388. } break;
  11389. }
  11390. (*i)++;
  11391. return true;
  11392. },
  11393. [i](bool success) {
  11394. EXPECT_TRUE(success);
  11395. delete i;
  11396. });
  11397. });
  11398. // Echo headers endpoint for header-related tests
  11399. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11400. std::string body;
  11401. for (const auto &h : req.headers) {
  11402. body.append(h.first);
  11403. body.push_back(':');
  11404. body.append(h.second);
  11405. body.push_back('\n');
  11406. }
  11407. res.set_content(body, "text/plain");
  11408. });
  11409. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11410. std::string body;
  11411. for (const auto &h : req.headers) {
  11412. body.append(h.first);
  11413. body.push_back(':');
  11414. body.append(h.second);
  11415. body.push_back('\n');
  11416. }
  11417. res.set_content(body, "text/plain");
  11418. });
  11419. port_ = svr_.bind_to_any_port("127.0.0.1");
  11420. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11421. svr_.wait_until_ready();
  11422. }
  11423. void TearDown() override {
  11424. svr_.stop();
  11425. if (thread_.joinable()) thread_.join();
  11426. }
  11427. Server svr_;
  11428. std::thread thread_;
  11429. int port_ = 0;
  11430. };
  11431. TEST_F(OpenStreamTest, Basic) {
  11432. Client cli("127.0.0.1", port_);
  11433. auto handle = cli.open_stream("GET", "/hello");
  11434. EXPECT_TRUE(handle.is_valid());
  11435. EXPECT_EQ("Hello World!", read_all(handle));
  11436. }
  11437. TEST_F(OpenStreamTest, SmallBuffer) {
  11438. Client cli("127.0.0.1", port_);
  11439. auto handle = cli.open_stream("GET", "/hello");
  11440. std::string result;
  11441. char buf[4];
  11442. ssize_t n;
  11443. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11444. result.append(buf, static_cast<size_t>(n));
  11445. EXPECT_EQ("Hello World!", result);
  11446. }
  11447. TEST_F(OpenStreamTest, DefaultHeaders) {
  11448. Client cli("127.0.0.1", port_);
  11449. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11450. {
  11451. auto handle = cli.open_stream("GET", "/echo-headers");
  11452. ASSERT_TRUE(handle.is_valid());
  11453. auto body = read_all(handle);
  11454. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11455. std::string::npos);
  11456. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11457. std::string::npos);
  11458. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11459. }
  11460. // open_stream POST with body and no explicit content_type should NOT add
  11461. // text/plain Content-Type (behavior differs from non-streaming path), but
  11462. // should include Content-Length
  11463. {
  11464. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11465. ASSERT_TRUE(handle.is_valid());
  11466. auto body = read_all(handle);
  11467. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11468. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11469. }
  11470. // open_stream POST with explicit Content-Type should preserve it
  11471. {
  11472. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11473. {{"Content-Type", "application/custom"}},
  11474. "{}", "application/custom");
  11475. ASSERT_TRUE(handle.is_valid());
  11476. auto body = read_all(handle);
  11477. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11478. }
  11479. // User-specified User-Agent must not be overwritten for stream API
  11480. {
  11481. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11482. {{"User-Agent", "MyAgent/1.2"}});
  11483. ASSERT_TRUE(handle.is_valid());
  11484. auto body = read_all(handle);
  11485. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11486. }
  11487. }
  11488. TEST_F(OpenStreamTest, Large) {
  11489. Client cli("127.0.0.1", port_);
  11490. auto handle = cli.open_stream("GET", "/large");
  11491. EXPECT_EQ(10000u, read_all(handle).size());
  11492. }
  11493. TEST_F(OpenStreamTest, ConnectionError) {
  11494. Client cli("127.0.0.1", 9999);
  11495. auto handle = cli.open_stream("GET", "/hello");
  11496. EXPECT_FALSE(handle.is_valid());
  11497. }
  11498. TEST_F(OpenStreamTest, Chunked) {
  11499. Client cli("127.0.0.1", port_);
  11500. auto handle = cli.open_stream("GET", "/chunked");
  11501. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11502. "Transfer-Encoding") == "chunked");
  11503. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11504. }
  11505. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11506. Client cli("127.0.0.1", port_);
  11507. auto handle =
  11508. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11509. ASSERT_TRUE(handle.is_valid());
  11510. // Consume body to allow trailers to be received/parsed
  11511. auto body = read_all(handle);
  11512. // Explicitly parse trailers (ensure trailers are available for assertion)
  11513. handle.parse_trailers_if_needed();
  11514. EXPECT_EQ(std::string("123456789"), body);
  11515. // The response should include a Trailer header declaring both names
  11516. ASSERT_TRUE(handle.response);
  11517. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11518. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11519. handle.response->get_header_value("Trailer"));
  11520. // Prohibited trailer must not be present
  11521. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11522. // Allowed trailer should be present
  11523. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11524. EXPECT_EQ(std::string("yes"),
  11525. handle.response->get_trailer_value("X-Allowed"));
  11526. // Verify trailers are NOT present as regular headers
  11527. EXPECT_EQ(std::string(""),
  11528. handle.response->get_header_value("Content-Length"));
  11529. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11530. }
  11531. static std::thread serve_single_response(int port,
  11532. const std::string &response) {
  11533. return std::thread([port, response] {
  11534. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11535. default_socket_options(srv);
  11536. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11537. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11538. sockaddr_in addr{};
  11539. addr.sin_family = AF_INET;
  11540. addr.sin_port = htons(static_cast<uint16_t>(port));
  11541. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11542. int opt = 1;
  11543. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11544. #ifdef _WIN32
  11545. reinterpret_cast<const char *>(&opt),
  11546. #else
  11547. &opt,
  11548. #endif
  11549. sizeof(opt));
  11550. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11551. ::listen(srv, 1);
  11552. sockaddr_in cli_addr{};
  11553. socklen_t cli_len = sizeof(cli_addr);
  11554. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11555. if (cli != INVALID_SOCKET) {
  11556. char buf[4096];
  11557. ::recv(cli, buf, sizeof(buf), 0);
  11558. ::send(cli,
  11559. #ifdef _WIN32
  11560. static_cast<const char *>(response.c_str()),
  11561. static_cast<int>(response.size()),
  11562. #else
  11563. response.c_str(), response.size(),
  11564. #endif
  11565. 0);
  11566. detail::close_socket(cli);
  11567. }
  11568. detail::close_socket(srv);
  11569. });
  11570. }
  11571. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11572. #ifndef _WIN32
  11573. signal(SIGPIPE, SIG_IGN);
  11574. #endif
  11575. auto server_thread =
  11576. serve_single_response(PORT + 2, "HTTP/1.1 200 OK\r\n"
  11577. "Content-Type: text/plain\r\n"
  11578. "Content-Length: not-a-number\r\n"
  11579. "Connection: close\r\n"
  11580. "\r\n"
  11581. "hello");
  11582. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11583. Client cli("127.0.0.1", PORT + 2);
  11584. auto handle = cli.open_stream("GET", "/");
  11585. EXPECT_FALSE(handle.is_valid());
  11586. server_thread.join();
  11587. }
  11588. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11589. #ifndef _WIN32
  11590. signal(SIGPIPE, SIG_IGN);
  11591. #endif
  11592. auto server_thread = serve_single_response(
  11593. PORT + 2, "HTTP/1.1 200 OK\r\n"
  11594. "Content-Type: text/plain\r\n"
  11595. "Content-Length: 99999999999999999999999999\r\n"
  11596. "Connection: close\r\n"
  11597. "\r\n"
  11598. "hello");
  11599. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11600. // Before the fix, std::stoull would throw std::out_of_range here and
  11601. // crash the process. After the fix, strtoull silently clamps to
  11602. // ULLONG_MAX so the stream opens without crashing. The important thing
  11603. // is that the process does NOT terminate.
  11604. Client cli("127.0.0.1", PORT + 2);
  11605. auto handle = cli.open_stream("GET", "/");
  11606. EXPECT_TRUE(handle.is_valid());
  11607. server_thread.join();
  11608. }
  11609. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11610. TEST_F(OpenStreamTest, Gzip) {
  11611. Client cli("127.0.0.1", port_);
  11612. auto handle = cli.open_stream("GET", "/compressible", {},
  11613. {{"Accept-Encoding", "gzip"}});
  11614. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11615. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11616. }
  11617. #endif
  11618. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11619. TEST_F(OpenStreamTest, Brotli) {
  11620. Client cli("127.0.0.1", port_);
  11621. auto handle =
  11622. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11623. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11624. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11625. }
  11626. #endif
  11627. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11628. TEST_F(OpenStreamTest, Zstd) {
  11629. Client cli("127.0.0.1", port_);
  11630. auto handle = cli.open_stream("GET", "/compressible", {},
  11631. {{"Accept-Encoding", "zstd"}});
  11632. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11633. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11634. }
  11635. #endif
  11636. #ifdef CPPHTTPLIB_SSL_ENABLED
  11637. class SSLOpenStreamTest : public ::testing::Test {
  11638. protected:
  11639. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11640. void SetUp() override {
  11641. svr_.Get("/hello", [](const Request &, Response &res) {
  11642. res.set_content("Hello SSL World!", "text/plain");
  11643. });
  11644. svr_.Get("/chunked", [](const Request &, Response &res) {
  11645. res.set_chunked_content_provider("text/plain",
  11646. [](size_t offset, DataSink &sink) {
  11647. if (offset < 15) {
  11648. sink.write("chunk", 5);
  11649. return true;
  11650. }
  11651. sink.done();
  11652. return true;
  11653. });
  11654. });
  11655. svr_.Post("/echo", [](const Request &req, Response &res) {
  11656. res.set_content(req.body, req.get_header_value("Content-Type"));
  11657. });
  11658. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11659. std::string body = req.body;
  11660. res.set_chunked_content_provider(
  11661. "text/plain", [body](size_t offset, DataSink &sink) {
  11662. if (offset < body.size()) {
  11663. sink.write(body.data() + offset, body.size() - offset);
  11664. }
  11665. sink.done();
  11666. return true;
  11667. });
  11668. });
  11669. port_ = svr_.bind_to_any_port("127.0.0.1");
  11670. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11671. svr_.wait_until_ready();
  11672. }
  11673. void TearDown() override {
  11674. svr_.stop();
  11675. if (thread_.joinable()) thread_.join();
  11676. }
  11677. SSLServer svr_;
  11678. std::thread thread_;
  11679. int port_ = 0;
  11680. };
  11681. TEST_F(SSLOpenStreamTest, Basic) {
  11682. SSLClient cli("127.0.0.1", port_);
  11683. cli.enable_server_certificate_verification(false);
  11684. auto handle = cli.open_stream("GET", "/hello");
  11685. ASSERT_TRUE(handle.is_valid());
  11686. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11687. }
  11688. TEST_F(SSLOpenStreamTest, Chunked) {
  11689. SSLClient cli("127.0.0.1", port_);
  11690. cli.enable_server_certificate_verification(false);
  11691. auto handle = cli.open_stream("GET", "/chunked");
  11692. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11693. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11694. "Transfer-Encoding") == "chunked");
  11695. auto body = read_all(handle);
  11696. EXPECT_EQ("chunkchunkchunk", body);
  11697. }
  11698. TEST_F(SSLOpenStreamTest, Post) {
  11699. SSLClient cli("127.0.0.1", port_);
  11700. cli.enable_server_certificate_verification(false);
  11701. auto handle =
  11702. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11703. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11704. EXPECT_EQ(200, handle.response->status);
  11705. auto body = read_all(handle);
  11706. EXPECT_EQ("Hello SSL POST", body);
  11707. }
  11708. TEST_F(SSLOpenStreamTest, PostChunked) {
  11709. SSLClient cli("127.0.0.1", port_);
  11710. cli.enable_server_certificate_verification(false);
  11711. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11712. "Chunked SSL Data", "text/plain");
  11713. ASSERT_TRUE(handle.is_valid());
  11714. EXPECT_EQ(200, handle.response->status);
  11715. auto body = read_all(handle);
  11716. EXPECT_EQ("Chunked SSL Data", body);
  11717. }
  11718. #endif // CPPHTTPLIB_SSL_ENABLED
  11719. //==============================================================================
  11720. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11721. // results for various scenarios.
  11722. //==============================================================================
  11723. TEST(ParityTest, GetVsOpenStream) {
  11724. Server svr;
  11725. const std::string path = "/parity";
  11726. const std::string content = "Parity test content: hello world";
  11727. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11728. res.set_content(content, "text/plain");
  11729. });
  11730. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11731. auto se = detail::scope_exit([&] {
  11732. svr.stop();
  11733. t.join();
  11734. ASSERT_FALSE(svr.is_running());
  11735. });
  11736. svr.wait_until_ready();
  11737. Client cli(HOST, PORT);
  11738. // Non-stream path
  11739. auto r1 = cli.Get(path);
  11740. ASSERT_TRUE(r1);
  11741. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11742. // Stream path
  11743. auto h = cli.open_stream("GET", path);
  11744. ASSERT_TRUE(h.is_valid());
  11745. EXPECT_EQ(r1->body, read_all(h));
  11746. }
  11747. // Helper to compress data with provided compressor type T
  11748. template <typename Compressor>
  11749. static std::string compress_payload_for_parity(const std::string &in) {
  11750. std::string out;
  11751. Compressor compressor;
  11752. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11753. [&](const char *data, size_t n) {
  11754. out.append(data, n);
  11755. return true;
  11756. });
  11757. EXPECT_TRUE(ok);
  11758. return out;
  11759. }
  11760. // Helper function for compression parity tests
  11761. template <typename Compressor>
  11762. static void test_compression_parity(const std::string &original,
  11763. const std::string &path,
  11764. const std::string &encoding) {
  11765. const std::string compressed =
  11766. compress_payload_for_parity<Compressor>(original);
  11767. Server svr;
  11768. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11769. res.set_content(compressed, "application/octet-stream");
  11770. res.set_header("Content-Encoding", encoding);
  11771. });
  11772. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11773. auto se = detail::scope_exit([&] {
  11774. svr.stop();
  11775. t.join();
  11776. ASSERT_FALSE(svr.is_running());
  11777. });
  11778. svr.wait_until_ready();
  11779. Client cli(HOST, PORT);
  11780. // Non-streaming
  11781. {
  11782. auto res = cli.Get(path);
  11783. ASSERT_TRUE(res);
  11784. EXPECT_EQ(StatusCode::OK_200, res->status);
  11785. EXPECT_EQ(original, res->body);
  11786. }
  11787. // Streaming
  11788. {
  11789. auto h = cli.open_stream("GET", path);
  11790. ASSERT_TRUE(h.is_valid());
  11791. EXPECT_EQ(original, read_all(h));
  11792. }
  11793. }
  11794. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11795. TEST(ParityTest, Gzip) {
  11796. test_compression_parity<detail::gzip_compressor>(
  11797. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11798. }
  11799. #endif
  11800. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11801. TEST(ParityTest, Brotli) {
  11802. test_compression_parity<detail::brotli_compressor>(
  11803. "Hello, brotli parity test payload", "/parity-br", "br");
  11804. }
  11805. #endif
  11806. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11807. TEST(ParityTest, Zstd) {
  11808. test_compression_parity<detail::zstd_compressor>(
  11809. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11810. }
  11811. #endif
  11812. //==============================================================================
  11813. // New Stream API Tests
  11814. //==============================================================================
  11815. inline std::string read_body(httplib::stream::Result &result) {
  11816. std::string body;
  11817. while (result.next()) {
  11818. body.append(result.data(), result.size());
  11819. }
  11820. return body;
  11821. }
  11822. TEST(ClientConnectionTest, Basic) {
  11823. httplib::ClientConnection conn;
  11824. EXPECT_FALSE(conn.is_open());
  11825. conn.sock = 1;
  11826. EXPECT_TRUE(conn.is_open());
  11827. httplib::ClientConnection conn2(std::move(conn));
  11828. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11829. conn2.sock = INVALID_SOCKET;
  11830. }
  11831. // Unified test server for all stream::* tests
  11832. class StreamApiTest : public ::testing::Test {
  11833. protected:
  11834. void SetUp() override {
  11835. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11836. res.set_content("Hello World!", "text/plain");
  11837. });
  11838. svr_.Get("/echo-params",
  11839. [](const httplib::Request &req, httplib::Response &res) {
  11840. std::string r;
  11841. for (const auto &p : req.params) {
  11842. if (!r.empty()) r += "&";
  11843. r += p.first + "=" + p.second;
  11844. }
  11845. res.set_content(r, "text/plain");
  11846. });
  11847. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11848. res.set_content(req.body, req.get_header_value("Content-Type"));
  11849. });
  11850. svr_.Post("/echo-headers",
  11851. [](const httplib::Request &req, httplib::Response &res) {
  11852. std::string r;
  11853. for (const auto &h : req.headers)
  11854. r += h.first + ": " + h.second + "\n";
  11855. res.set_content(r, "text/plain");
  11856. });
  11857. svr_.Post("/echo-params",
  11858. [](const httplib::Request &req, httplib::Response &res) {
  11859. std::string r = "params:";
  11860. for (const auto &p : req.params)
  11861. r += p.first + "=" + p.second + ";";
  11862. res.set_content(r + " body:" + req.body, "text/plain");
  11863. });
  11864. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11865. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11866. });
  11867. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11868. res.set_content("PUT:" + req.body, "text/plain");
  11869. });
  11870. svr_.Patch("/echo",
  11871. [](const httplib::Request &req, httplib::Response &res) {
  11872. res.set_content("PATCH:" + req.body, "text/plain");
  11873. });
  11874. svr_.Delete(
  11875. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11876. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11877. "text/plain");
  11878. });
  11879. svr_.Get("/head-test",
  11880. [](const httplib::Request &, httplib::Response &res) {
  11881. res.set_content("body for HEAD", "text/plain");
  11882. });
  11883. svr_.Options("/options",
  11884. [](const httplib::Request &, httplib::Response &res) {
  11885. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11886. });
  11887. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11888. svr_.wait_until_ready();
  11889. }
  11890. void TearDown() override {
  11891. svr_.stop();
  11892. if (thread_.joinable()) thread_.join();
  11893. }
  11894. httplib::Server svr_;
  11895. std::thread thread_;
  11896. };
  11897. // stream::Get tests
  11898. TEST_F(StreamApiTest, GetBasic) {
  11899. httplib::Client cli(HOST, PORT);
  11900. auto result = httplib::stream::Get(cli, "/hello");
  11901. ASSERT_TRUE(result.is_valid());
  11902. EXPECT_EQ(200, result.status());
  11903. EXPECT_EQ("Hello World!", read_body(result));
  11904. }
  11905. TEST_F(StreamApiTest, GetWithParams) {
  11906. httplib::Client cli(HOST, PORT);
  11907. httplib::Params params{{"foo", "bar"}};
  11908. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11909. ASSERT_TRUE(result.is_valid());
  11910. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11911. }
  11912. TEST_F(StreamApiTest, GetConnectionError) {
  11913. httplib::Client cli(HOST, 9999);
  11914. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11915. }
  11916. TEST_F(StreamApiTest, Get404) {
  11917. httplib::Client cli(HOST, PORT);
  11918. auto result = httplib::stream::Get(cli, "/nonexistent");
  11919. EXPECT_TRUE(result.is_valid());
  11920. EXPECT_EQ(404, result.status());
  11921. }
  11922. // stream::Post tests
  11923. TEST_F(StreamApiTest, PostBasic) {
  11924. httplib::Client cli(HOST, PORT);
  11925. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11926. "application/json");
  11927. ASSERT_TRUE(result.is_valid());
  11928. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11929. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11930. }
  11931. TEST_F(StreamApiTest, PostWithHeaders) {
  11932. httplib::Client cli(HOST, PORT);
  11933. httplib::Headers headers{{"X-Custom", "value"}};
  11934. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11935. "text/plain");
  11936. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11937. }
  11938. TEST_F(StreamApiTest, PostWithParams) {
  11939. httplib::Client cli(HOST, PORT);
  11940. httplib::Params params{{"k", "v"}};
  11941. auto result =
  11942. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11943. auto body = read_body(result);
  11944. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11945. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11946. }
  11947. TEST_F(StreamApiTest, PostLarge) {
  11948. httplib::Client cli(HOST, PORT);
  11949. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11950. size_t total = 0;
  11951. while (result.next()) {
  11952. total += result.size();
  11953. }
  11954. EXPECT_EQ(100u * 1024u, total);
  11955. }
  11956. // stream::Put/Patch tests
  11957. TEST_F(StreamApiTest, PutAndPatch) {
  11958. httplib::Client cli(HOST, PORT);
  11959. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11960. EXPECT_EQ("PUT:test", read_body(put));
  11961. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11962. EXPECT_EQ("PATCH:test", read_body(patch));
  11963. }
  11964. // stream::Delete tests
  11965. TEST_F(StreamApiTest, Delete) {
  11966. httplib::Client cli(HOST, PORT);
  11967. auto del1 = httplib::stream::Delete(cli, "/resource");
  11968. EXPECT_EQ("Deleted", read_body(del1));
  11969. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11970. EXPECT_EQ("Deleted:data", read_body(del2));
  11971. }
  11972. // stream::Head/Options tests
  11973. TEST_F(StreamApiTest, HeadAndOptions) {
  11974. httplib::Client cli(HOST, PORT);
  11975. auto head = httplib::stream::Head(cli, "/head-test");
  11976. EXPECT_TRUE(head.is_valid());
  11977. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11978. auto opts = httplib::stream::Options(cli, "/options");
  11979. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11980. }
  11981. // SSL stream::* tests
  11982. #ifdef CPPHTTPLIB_SSL_ENABLED
  11983. class SSLStreamApiTest : public ::testing::Test {
  11984. protected:
  11985. void SetUp() override {
  11986. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11987. res.set_content("Hello SSL!", "text/plain");
  11988. });
  11989. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11990. res.set_content(req.body, "text/plain");
  11991. });
  11992. port_ = svr_.bind_to_any_port("127.0.0.1");
  11993. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11994. svr_.wait_until_ready();
  11995. }
  11996. void TearDown() override {
  11997. svr_.stop();
  11998. if (thread_.joinable()) thread_.join();
  11999. }
  12000. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12001. std::thread thread_;
  12002. int port_ = 0;
  12003. };
  12004. TEST_F(SSLStreamApiTest, GetAndPost) {
  12005. httplib::SSLClient cli("127.0.0.1", port_);
  12006. cli.enable_server_certificate_verification(false);
  12007. auto get = httplib::stream::Get(cli, "/hello");
  12008. EXPECT_EQ("Hello SSL!", read_body(get));
  12009. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12010. EXPECT_EQ("test", read_body(post));
  12011. }
  12012. #endif
  12013. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12014. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12015. // BodyReader
  12016. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12017. // Test that read timeout during streaming is detected
  12018. // Use a large content-length response where server delays mid-stream
  12019. Server svr;
  12020. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12021. // Send a large response with delay in the middle
  12022. res.set_content_provider(
  12023. 1000, // content_length
  12024. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12025. if (offset < 100) {
  12026. // Send first 100 bytes immediately
  12027. std::string data(100, 'A');
  12028. sink.write(data.c_str(), data.size());
  12029. return true;
  12030. }
  12031. // Then delay longer than client timeout
  12032. std::this_thread::sleep_for(std::chrono::seconds(3));
  12033. std::string data(900, 'B');
  12034. sink.write(data.c_str(), data.size());
  12035. return true;
  12036. });
  12037. });
  12038. auto port = 8091;
  12039. std::thread t([&]() { svr.listen("localhost", port); });
  12040. svr.wait_until_ready();
  12041. Client cli("localhost", port);
  12042. cli.set_read_timeout(1, 0); // 1 second timeout
  12043. auto handle = cli.open_stream("GET", "/slow-stream");
  12044. ASSERT_TRUE(handle.is_valid());
  12045. char buf[256];
  12046. ssize_t total = 0;
  12047. ssize_t n;
  12048. bool got_error = false;
  12049. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12050. total += n;
  12051. }
  12052. if (n < 0) {
  12053. got_error = true;
  12054. // Should be timeout or read error
  12055. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12056. handle.get_read_error() == Error::Read)
  12057. << "Actual error: " << to_string(handle.get_read_error());
  12058. }
  12059. // Either we got an error, or we got less data than expected
  12060. EXPECT_TRUE(got_error || total < 1000)
  12061. << "Expected timeout but got all " << total << " bytes";
  12062. svr.stop();
  12063. t.join();
  12064. }
  12065. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12066. // Test connection closed detection via BodyReader
  12067. Server svr;
  12068. std::atomic<bool> close_now{false};
  12069. svr.Get("/will-close", [&](const Request &, Response &res) {
  12070. res.set_content_provider(
  12071. 10000, // Large content_length that we won't fully send
  12072. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12073. if (offset < 100) {
  12074. std::string data(100, 'X');
  12075. sink.write(data.c_str(), data.size());
  12076. return true;
  12077. }
  12078. // Wait for signal then abort
  12079. while (!close_now) {
  12080. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12081. }
  12082. return false; // Abort - server will close connection
  12083. });
  12084. });
  12085. auto port = 8092;
  12086. std::thread t([&]() { svr.listen("localhost", port); });
  12087. svr.wait_until_ready();
  12088. Client cli("localhost", port);
  12089. auto handle = cli.open_stream("GET", "/will-close");
  12090. ASSERT_TRUE(handle.is_valid());
  12091. char buf[256];
  12092. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12093. EXPECT_GT(n, 0) << "First read should succeed";
  12094. // Signal server to close
  12095. close_now = true;
  12096. // Keep reading until error or EOF
  12097. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12098. // Keep reading
  12099. }
  12100. // Should get an error since content_length wasn't satisfied
  12101. if (n < 0) {
  12102. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12103. handle.get_read_error() == Error::Read)
  12104. << "Actual error: " << to_string(handle.get_read_error());
  12105. }
  12106. svr.stop();
  12107. t.join();
  12108. }
  12109. #ifdef CPPHTTPLIB_SSL_ENABLED
  12110. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12111. // Test that read timeout during SSL streaming is detected
  12112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12113. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12114. res.set_content_provider(
  12115. 1000, "text/plain",
  12116. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12117. if (offset < 100) {
  12118. std::string data(100, 'A');
  12119. sink.write(data.c_str(), data.size());
  12120. return true;
  12121. }
  12122. std::this_thread::sleep_for(std::chrono::seconds(3));
  12123. std::string data(900, 'B');
  12124. sink.write(data.c_str(), data.size());
  12125. return true;
  12126. });
  12127. });
  12128. auto port = 8093;
  12129. std::thread t([&]() { svr.listen("localhost", port); });
  12130. svr.wait_until_ready();
  12131. SSLClient cli("localhost", port);
  12132. cli.enable_server_certificate_verification(false);
  12133. cli.set_read_timeout(1, 0); // 1 second timeout
  12134. auto handle = cli.open_stream("GET", "/slow-stream");
  12135. ASSERT_TRUE(handle.is_valid());
  12136. char buf[256];
  12137. ssize_t total = 0;
  12138. ssize_t n;
  12139. bool got_error = false;
  12140. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12141. total += n;
  12142. }
  12143. if (n < 0) {
  12144. got_error = true;
  12145. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12146. handle.get_read_error() == Error::Read)
  12147. << "Actual error: " << to_string(handle.get_read_error());
  12148. }
  12149. EXPECT_TRUE(got_error || total < 1000)
  12150. << "Expected timeout but got all " << total << " bytes";
  12151. svr.stop();
  12152. t.join();
  12153. }
  12154. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12155. // Test SSL connection closed detection
  12156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12157. std::atomic<bool> close_now{false};
  12158. svr.Get("/will-close", [&](const Request &, Response &res) {
  12159. res.set_content_provider(
  12160. 10000, "text/plain",
  12161. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12162. if (offset < 100) {
  12163. std::string data(100, 'X');
  12164. sink.write(data.c_str(), data.size());
  12165. return true;
  12166. }
  12167. while (!close_now) {
  12168. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12169. }
  12170. return false;
  12171. });
  12172. });
  12173. auto port = 8094;
  12174. std::thread t([&]() { svr.listen("localhost", port); });
  12175. svr.wait_until_ready();
  12176. SSLClient cli("localhost", port);
  12177. cli.enable_server_certificate_verification(false);
  12178. auto handle = cli.open_stream("GET", "/will-close");
  12179. ASSERT_TRUE(handle.is_valid());
  12180. char buf[256];
  12181. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12182. EXPECT_GT(n, 0);
  12183. // Signal server to close
  12184. close_now = true;
  12185. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12186. // Keep reading
  12187. }
  12188. if (n < 0) {
  12189. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12190. handle.get_read_error() == Error::Read)
  12191. << "Actual error: " << to_string(handle.get_read_error());
  12192. }
  12193. svr.stop();
  12194. t.join();
  12195. }
  12196. #endif
  12197. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12198. using namespace httplib;
  12199. // Create a test file
  12200. const char *fname = "etag_testfile.txt";
  12201. const char *content = "etag-content";
  12202. {
  12203. std::ofstream ofs(fname);
  12204. ofs << content;
  12205. ASSERT_TRUE(ofs.good());
  12206. }
  12207. Server svr;
  12208. svr.set_mount_point("/static", ".");
  12209. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12210. svr.wait_until_ready();
  12211. Client cli(HOST, PORT);
  12212. // First request: should get 200 with ETag header
  12213. auto res1 = cli.Get("/static/etag_testfile.txt");
  12214. ASSERT_TRUE(res1);
  12215. ASSERT_EQ(200, res1->status);
  12216. ASSERT_TRUE(res1->has_header("ETag"));
  12217. std::string etag = res1->get_header_value("ETag");
  12218. EXPECT_FALSE(etag.empty());
  12219. // Verify ETag format: W/"hex-hex"
  12220. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12221. EXPECT_EQ('W', etag[0]);
  12222. EXPECT_EQ('/', etag[1]);
  12223. EXPECT_EQ('"', etag[2]);
  12224. EXPECT_EQ('"', etag.back());
  12225. // Exact match: expect 304 Not Modified
  12226. Headers h2 = {{"If-None-Match", etag}};
  12227. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12228. ASSERT_TRUE(res2);
  12229. EXPECT_EQ(304, res2->status);
  12230. // Wildcard match: expect 304 Not Modified
  12231. Headers h3 = {{"If-None-Match", "*"}};
  12232. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12233. ASSERT_TRUE(res3);
  12234. EXPECT_EQ(304, res3->status);
  12235. // Non-matching ETag: expect 200
  12236. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12237. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12238. ASSERT_TRUE(res4);
  12239. EXPECT_EQ(200, res4->status);
  12240. // Multiple ETags with one matching: expect 304
  12241. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12242. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12243. ASSERT_TRUE(res5);
  12244. EXPECT_EQ(304, res5->status);
  12245. svr.stop();
  12246. t.join();
  12247. std::remove(fname);
  12248. }
  12249. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12250. using namespace httplib;
  12251. Server svr;
  12252. svr.set_mount_point("/static", ".");
  12253. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12254. svr.wait_until_ready();
  12255. Client cli(HOST, PORT);
  12256. // Send If-None-Match: * to a non-existent file
  12257. Headers h = {{"If-None-Match", "*"}};
  12258. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12259. ASSERT_TRUE(res);
  12260. EXPECT_EQ(404, res->status);
  12261. svr.stop();
  12262. t.join();
  12263. }
  12264. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12265. using namespace httplib;
  12266. // Create a test file
  12267. const char *fname = "etag_boundary_testfile.txt";
  12268. const char *content = "boundary-test";
  12269. {
  12270. std::ofstream ofs(fname);
  12271. ofs << content;
  12272. ASSERT_TRUE(ofs.good());
  12273. }
  12274. Server svr;
  12275. svr.set_mount_point("/static", ".");
  12276. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12277. svr.wait_until_ready();
  12278. Client cli(HOST, PORT);
  12279. // Get the actual ETag
  12280. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12281. ASSERT_TRUE(res1);
  12282. ASSERT_EQ(200, res1->status);
  12283. ASSERT_TRUE(res1->has_header("ETag"));
  12284. std::string etag = res1->get_header_value("ETag");
  12285. // Test 1: Very long ETag value (longer than actual ETag)
  12286. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12287. Headers h1 = {{"If-None-Match", "W/"
  12288. "\"very-long-etag-value-that-is-much-longer-"
  12289. "than-the-actual-etag-value\""}};
  12290. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12291. ASSERT_TRUE(res2);
  12292. EXPECT_EQ(200, res2->status); // Should not match
  12293. // Test 2: Long string followed by wildcard
  12294. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12295. // string)
  12296. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12297. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12298. ASSERT_TRUE(res3);
  12299. EXPECT_EQ(304, res3->status); // Should match on "*"
  12300. // Test 3: Wildcard followed by long string
  12301. // Should match on "*" immediately and return 304
  12302. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12303. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12304. ASSERT_TRUE(res4);
  12305. EXPECT_EQ(304, res4->status); // Should match on "*"
  12306. // Test 4: Multiple long non-matching values
  12307. // Should NOT match and return 200 (test that all comparisons are safe)
  12308. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12309. "W/\"second-long-non-matching-value\", "
  12310. "W/\"third-long-non-matching-value\""}};
  12311. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12312. ASSERT_TRUE(res5);
  12313. EXPECT_EQ(200, res5->status); // Should not match
  12314. // Test 5: Single character that is not "*" (edge case)
  12315. Headers h5 = {{"If-None-Match", "X"}};
  12316. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12317. ASSERT_TRUE(res6);
  12318. EXPECT_EQ(200, res6->status); // Should not match
  12319. svr.stop();
  12320. t.join();
  12321. std::remove(fname);
  12322. }
  12323. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12324. using namespace httplib;
  12325. // Create a test file
  12326. const char *fname = "ims_testfile.txt";
  12327. const char *content = "if-modified-since-test";
  12328. {
  12329. std::ofstream ofs(fname);
  12330. ofs << content;
  12331. ASSERT_TRUE(ofs.good());
  12332. }
  12333. Server svr;
  12334. svr.set_mount_point("/static", ".");
  12335. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12336. svr.wait_until_ready();
  12337. Client cli(HOST, PORT);
  12338. // First request: should get 200 with Last-Modified header
  12339. auto res1 = cli.Get("/static/ims_testfile.txt");
  12340. ASSERT_TRUE(res1);
  12341. ASSERT_EQ(200, res1->status);
  12342. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12343. std::string last_modified = res1->get_header_value("Last-Modified");
  12344. EXPECT_FALSE(last_modified.empty());
  12345. // If-Modified-Since with same time: expect 304
  12346. Headers h2 = {{"If-Modified-Since", last_modified}};
  12347. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12348. ASSERT_TRUE(res2);
  12349. EXPECT_EQ(304, res2->status);
  12350. // If-Modified-Since with future time: expect 304
  12351. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12352. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12353. ASSERT_TRUE(res3);
  12354. EXPECT_EQ(304, res3->status);
  12355. // If-Modified-Since with past time: expect 200
  12356. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12357. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12358. ASSERT_TRUE(res4);
  12359. EXPECT_EQ(200, res4->status);
  12360. // If-None-Match takes precedence over If-Modified-Since
  12361. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12362. ASSERT_TRUE(res1->has_header("ETag"));
  12363. std::string etag = res1->get_header_value("ETag");
  12364. Headers h5 = {{"If-None-Match", etag},
  12365. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12366. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12367. ASSERT_TRUE(res5);
  12368. EXPECT_EQ(304, res5->status);
  12369. svr.stop();
  12370. t.join();
  12371. std::remove(fname);
  12372. }
  12373. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12374. using namespace httplib;
  12375. Server svr;
  12376. // Endpoint that returns compressible content
  12377. svr.Get("/compressible", [](const Request &, Response &res) {
  12378. // Return a large enough body to trigger compression
  12379. std::string body(1000, 'a');
  12380. res.set_content(body, "text/plain");
  12381. });
  12382. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12383. svr.wait_until_ready();
  12384. Client cli(HOST, PORT);
  12385. // Request with gzip support: should get Vary header when compressed
  12386. cli.set_compress(true);
  12387. auto res1 = cli.Get("/compressible");
  12388. ASSERT_TRUE(res1);
  12389. EXPECT_EQ(200, res1->status);
  12390. // If Content-Encoding is set, Vary should also be set
  12391. if (res1->has_header("Content-Encoding")) {
  12392. EXPECT_TRUE(res1->has_header("Vary"));
  12393. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12394. }
  12395. // Request without Accept-Encoding header: should not have compression
  12396. Headers h_no_compress;
  12397. auto res2 = cli.Get("/compressible", h_no_compress);
  12398. ASSERT_TRUE(res2);
  12399. EXPECT_EQ(200, res2->status);
  12400. // Verify Vary header is present when compression is applied
  12401. // (the exact behavior depends on server configuration)
  12402. svr.stop();
  12403. t.join();
  12404. }
  12405. TEST(ETagTest, IfRangeWithETag) {
  12406. using namespace httplib;
  12407. // Create a test file with known content
  12408. const char *fname = "if_range_testfile.txt";
  12409. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12410. {
  12411. std::ofstream ofs(fname);
  12412. ofs << content;
  12413. ASSERT_TRUE(ofs.good());
  12414. }
  12415. Server svr;
  12416. svr.set_mount_point("/static", ".");
  12417. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12418. svr.wait_until_ready();
  12419. Client cli(HOST, PORT);
  12420. // First request: get ETag
  12421. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12422. ASSERT_TRUE(res1);
  12423. ASSERT_EQ(200, res1->status);
  12424. ASSERT_TRUE(res1->has_header("ETag"));
  12425. std::string etag = res1->get_header_value("ETag");
  12426. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12427. // Since our server generates weak ETags (W/"..."), If-Range with our
  12428. // ETag should NOT result in partial content - it should return full content.
  12429. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12430. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12431. ASSERT_TRUE(res2);
  12432. // Weak ETag in If-Range -> full content (200), not partial (206)
  12433. EXPECT_EQ(200, res2->status);
  12434. EXPECT_EQ(content, res2->body);
  12435. EXPECT_FALSE(res2->has_header("Content-Range"));
  12436. // Range request with non-matching If-Range (ETag): should get 200 (full
  12437. // content)
  12438. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12439. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12440. ASSERT_TRUE(res3);
  12441. EXPECT_EQ(200, res3->status);
  12442. EXPECT_EQ(content, res3->body);
  12443. EXPECT_FALSE(res3->has_header("Content-Range"));
  12444. // Range request with strong ETag (hypothetical - our server doesn't generate
  12445. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12446. // should return full content)
  12447. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12448. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12449. ASSERT_TRUE(res4);
  12450. EXPECT_EQ(200, res4->status);
  12451. EXPECT_EQ(content, res4->body);
  12452. EXPECT_FALSE(res4->has_header("Content-Range"));
  12453. svr.stop();
  12454. t.join();
  12455. std::remove(fname);
  12456. }
  12457. TEST(ETagTest, IfRangeWithDate) {
  12458. using namespace httplib;
  12459. // Create a test file
  12460. const char *fname = "if_range_date_testfile.txt";
  12461. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12462. {
  12463. std::ofstream ofs(fname);
  12464. ofs << content;
  12465. ASSERT_TRUE(ofs.good());
  12466. }
  12467. Server svr;
  12468. svr.set_mount_point("/static", ".");
  12469. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12470. svr.wait_until_ready();
  12471. Client cli(HOST, PORT);
  12472. // First request: get Last-Modified
  12473. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12474. ASSERT_TRUE(res1);
  12475. ASSERT_EQ(200, res1->status);
  12476. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12477. std::string last_modified = res1->get_header_value("Last-Modified");
  12478. // Range request with matching If-Range (date): should get 206
  12479. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12480. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12481. ASSERT_TRUE(res2);
  12482. EXPECT_EQ(206, res2->status);
  12483. EXPECT_EQ("FGHIJ", res2->body);
  12484. // Range request with old If-Range date: should get 200 (full content)
  12485. Headers h3 = {{"Range", "bytes=5-9"},
  12486. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12487. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12488. ASSERT_TRUE(res3);
  12489. EXPECT_EQ(200, res3->status);
  12490. EXPECT_EQ(content, res3->body);
  12491. // Range request with future If-Range date: should get 206
  12492. Headers h4 = {{"Range", "bytes=0-4"},
  12493. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12494. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12495. ASSERT_TRUE(res4);
  12496. EXPECT_EQ(206, res4->status);
  12497. EXPECT_EQ("ABCDE", res4->body);
  12498. svr.stop();
  12499. t.join();
  12500. std::remove(fname);
  12501. }
  12502. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12503. using namespace httplib;
  12504. const char *fname = "etag_malformed.txt";
  12505. const char *content = "malformed-etag";
  12506. {
  12507. std::ofstream ofs(fname);
  12508. ofs << content;
  12509. ASSERT_TRUE(ofs.good());
  12510. }
  12511. Server svr;
  12512. svr.set_mount_point("/static", ".");
  12513. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12514. svr.wait_until_ready();
  12515. Client cli(HOST, PORT);
  12516. // baseline: should get 200 and an ETag
  12517. auto res1 = cli.Get("/static/etag_malformed.txt");
  12518. ASSERT_TRUE(res1);
  12519. ASSERT_EQ(200, res1->status);
  12520. ASSERT_TRUE(res1->has_header("ETag"));
  12521. // Malformed ETag value (missing quotes) should be treated as non-matching
  12522. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12523. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12524. ASSERT_TRUE(res_bad);
  12525. EXPECT_EQ(200, res_bad->status);
  12526. // Whitespace-only header value should be considered invalid / non-matching
  12527. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12528. "Host: localhost\r\n"
  12529. "If-None-Match: \r\n"
  12530. "Connection: close\r\n"
  12531. "\r\n";
  12532. std::string out;
  12533. ASSERT_TRUE(send_request(5, raw_req, &out));
  12534. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12535. svr.stop();
  12536. t.join();
  12537. std::remove(fname);
  12538. }
  12539. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12540. using namespace httplib;
  12541. const char *fname = "ims_invalid_format.txt";
  12542. const char *content = "ims-bad-format";
  12543. {
  12544. std::ofstream ofs(fname);
  12545. ofs << content;
  12546. ASSERT_TRUE(ofs.good());
  12547. }
  12548. Server svr;
  12549. svr.set_mount_point("/static", ".");
  12550. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12551. svr.wait_until_ready();
  12552. Client cli(HOST, PORT);
  12553. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12554. ASSERT_TRUE(res1);
  12555. ASSERT_EQ(200, res1->status);
  12556. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12557. // If-Modified-Since with invalid format should not result in 304
  12558. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12559. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12560. ASSERT_TRUE(res_bad);
  12561. EXPECT_EQ(200, res_bad->status);
  12562. // If-Range with invalid date format should be treated as mismatch -> full
  12563. // content (200)
  12564. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12565. {"If-Range", "invalid-date"}};
  12566. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12567. ASSERT_TRUE(res_ifrange);
  12568. EXPECT_EQ(200, res_ifrange->status);
  12569. svr.stop();
  12570. t.join();
  12571. std::remove(fname);
  12572. }
  12573. TEST(ETagTest, IfRangeWithMalformedETag) {
  12574. using namespace httplib;
  12575. const char *fname = "ifrange_malformed.txt";
  12576. const std::string content = "0123456789";
  12577. {
  12578. std::ofstream ofs(fname);
  12579. ofs << content;
  12580. ASSERT_TRUE(ofs.good());
  12581. }
  12582. Server svr;
  12583. svr.set_mount_point("/static", ".");
  12584. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12585. svr.wait_until_ready();
  12586. Client cli(HOST, PORT);
  12587. // First request: get ETag
  12588. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12589. ASSERT_TRUE(res1);
  12590. ASSERT_EQ(200, res1->status);
  12591. ASSERT_TRUE(res1->has_header("ETag"));
  12592. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12593. // full content (200)
  12594. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12595. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12596. ASSERT_TRUE(res2);
  12597. EXPECT_EQ(200, res2->status);
  12598. EXPECT_EQ(content, res2->body);
  12599. svr.stop();
  12600. t.join();
  12601. std::remove(fname);
  12602. }
  12603. TEST(ETagTest, ExtremeLargeDateValues) {
  12604. using namespace httplib;
  12605. const char *fname = "ims_extreme_date.txt";
  12606. const char *content = "ims-extreme-date";
  12607. {
  12608. std::ofstream ofs(fname);
  12609. ofs << content;
  12610. ASSERT_TRUE(ofs.good());
  12611. }
  12612. Server svr;
  12613. svr.set_mount_point("/static", ".");
  12614. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12615. svr.wait_until_ready();
  12616. Client cli(HOST, PORT);
  12617. auto res1 = cli.Get(std::string("/static/") + fname);
  12618. ASSERT_TRUE(res1);
  12619. ASSERT_EQ(200, res1->status);
  12620. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12621. // Extremely large year that may overflow date parsing routines.
  12622. Headers h_large_date = {
  12623. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12624. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12625. ASSERT_TRUE(res_bad);
  12626. // Expect server to treat this as invalid/mismatch and return full content
  12627. EXPECT_EQ(200, res_bad->status);
  12628. // If-Range with extremely large date should be treated as mismatch -> full
  12629. // content (200)
  12630. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12631. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12632. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12633. ASSERT_TRUE(res_ifrange);
  12634. EXPECT_EQ(200, res_ifrange->status);
  12635. svr.stop();
  12636. t.join();
  12637. std::remove(fname);
  12638. }
  12639. TEST(ETagTest, NegativeFileModificationTime) {
  12640. using namespace httplib;
  12641. const char *fname = "ims_negative_mtime.txt";
  12642. const std::string content = "negative-mtime";
  12643. {
  12644. std::ofstream ofs(fname);
  12645. ofs << content;
  12646. ASSERT_TRUE(ofs.good());
  12647. }
  12648. // Try to set file mtime to a negative value. This may fail on some
  12649. // platforms/filesystems; if it fails, the test will still verify server
  12650. // behaves safely by performing a regular conditional request.
  12651. #if defined(__APPLE__) || defined(__linux__)
  12652. bool set_negative = false;
  12653. do {
  12654. struct timeval times[2];
  12655. // access time: now
  12656. times[0].tv_sec = time(nullptr);
  12657. times[0].tv_usec = 0;
  12658. // modification time: negative (e.g., -1)
  12659. times[1].tv_sec = -1;
  12660. times[1].tv_usec = 0;
  12661. if (utimes(fname, times) == 0) { set_negative = true; }
  12662. } while (0);
  12663. #else
  12664. bool set_negative = false;
  12665. #endif
  12666. Server svr;
  12667. svr.set_mount_point("/static", ".");
  12668. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12669. svr.wait_until_ready();
  12670. Client cli(HOST, PORT);
  12671. auto res1 = cli.Get(std::string("/static/") + fname);
  12672. ASSERT_TRUE(res1);
  12673. ASSERT_EQ(200, res1->status);
  12674. bool has_last_modified = res1->has_header("Last-Modified");
  12675. std::string last_modified;
  12676. if (has_last_modified) {
  12677. last_modified = res1->get_header_value("Last-Modified");
  12678. }
  12679. if (set_negative) {
  12680. // If we successfully set a negative mtime, ensure server returns a
  12681. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12682. // with an old date and ensure server handles it without crash.
  12683. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12684. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12685. ASSERT_TRUE(res2);
  12686. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12687. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12688. } else {
  12689. // Could not set negative mtime on this platform; fall back to verifying
  12690. // that normal invalid/malformed dates are treated safely (non-304).
  12691. Headers h_bad_date = {
  12692. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12693. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12694. ASSERT_TRUE(res_bad);
  12695. EXPECT_EQ(200, res_bad->status);
  12696. }
  12697. svr.stop();
  12698. t.join();
  12699. std::remove(fname);
  12700. }
  12701. //==============================================================================
  12702. // SSE Parsing Tests
  12703. //==============================================================================
  12704. class SSEParsingTest : public ::testing::Test {
  12705. protected:
  12706. // Test helper that mimics SSE parsing behavior
  12707. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12708. int &retry_ms) {
  12709. // Blank line signals end of event
  12710. if (line.empty() || line == "\r") { return true; }
  12711. // Lines starting with ':' are comments (ignored)
  12712. if (!line.empty() && line[0] == ':') { return false; }
  12713. // Find the colon separator
  12714. auto colon_pos = line.find(':');
  12715. if (colon_pos == std::string::npos) {
  12716. // Line with no colon is treated as field name with empty value
  12717. return false;
  12718. }
  12719. std::string field = line.substr(0, colon_pos);
  12720. std::string value;
  12721. // Value starts after colon, skip optional single space
  12722. if (colon_pos + 1 < line.size()) {
  12723. size_t value_start = colon_pos + 1;
  12724. if (line[value_start] == ' ') { value_start++; }
  12725. value = line.substr(value_start);
  12726. // Remove trailing \r if present
  12727. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12728. }
  12729. // Handle known fields
  12730. if (field == "event") {
  12731. msg.event = value;
  12732. } else if (field == "data") {
  12733. // Multiple data lines are concatenated with newlines
  12734. if (!msg.data.empty()) { msg.data += "\n"; }
  12735. msg.data += value;
  12736. } else if (field == "id") {
  12737. // Empty id is valid (clears the last event ID)
  12738. msg.id = value;
  12739. } else if (field == "retry") {
  12740. // Parse retry interval in milliseconds
  12741. {
  12742. int v = 0;
  12743. auto res =
  12744. detail::from_chars(value.data(), value.data() + value.size(), v);
  12745. if (res.ec == std::errc{}) { retry_ms = v; }
  12746. }
  12747. }
  12748. // Unknown fields are ignored per SSE spec
  12749. return false;
  12750. }
  12751. };
  12752. // Test: Single-line data
  12753. TEST_F(SSEParsingTest, SingleLineData) {
  12754. sse::SSEMessage msg;
  12755. int retry_ms = 3000;
  12756. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12757. EXPECT_EQ(msg.data, "hello");
  12758. EXPECT_EQ(msg.event, "message");
  12759. // Blank line ends event
  12760. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12761. }
  12762. // Test: Multi-line data
  12763. TEST_F(SSEParsingTest, MultiLineData) {
  12764. sse::SSEMessage msg;
  12765. int retry_ms = 3000;
  12766. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12767. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12768. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12769. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12770. }
  12771. // Test: Custom event types
  12772. TEST_F(SSEParsingTest, CustomEventType) {
  12773. sse::SSEMessage msg;
  12774. int retry_ms = 3000;
  12775. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12776. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12777. EXPECT_EQ(msg.event, "update");
  12778. EXPECT_EQ(msg.data, "payload");
  12779. }
  12780. // Test: Event ID handling
  12781. TEST_F(SSEParsingTest, EventIdHandling) {
  12782. sse::SSEMessage msg;
  12783. int retry_ms = 3000;
  12784. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12785. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12786. EXPECT_EQ(msg.id, "12345");
  12787. }
  12788. // Test: Empty event ID (clears last event ID)
  12789. TEST_F(SSEParsingTest, EmptyEventId) {
  12790. sse::SSEMessage msg;
  12791. msg.id = "previous";
  12792. int retry_ms = 3000;
  12793. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12794. EXPECT_EQ(msg.id, "");
  12795. }
  12796. // Test: Retry field parsing
  12797. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12798. sse::SSEMessage msg;
  12799. int retry_ms = 3000;
  12800. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12801. EXPECT_EQ(retry_ms, 5000);
  12802. }
  12803. // Test: Invalid retry value
  12804. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12805. sse::SSEMessage msg;
  12806. int retry_ms = 3000;
  12807. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12808. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12809. }
  12810. // Test: Comments (lines starting with :)
  12811. TEST_F(SSEParsingTest, CommentsIgnored) {
  12812. sse::SSEMessage msg;
  12813. int retry_ms = 3000;
  12814. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12815. EXPECT_EQ(msg.data, "");
  12816. EXPECT_EQ(msg.event, "message");
  12817. }
  12818. // Test: Colon in value
  12819. TEST_F(SSEParsingTest, ColonInValue) {
  12820. sse::SSEMessage msg;
  12821. int retry_ms = 3000;
  12822. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12823. EXPECT_EQ(msg.data, "hello:world:test");
  12824. }
  12825. // Test: Line with no colon (field name only)
  12826. TEST_F(SSEParsingTest, FieldNameOnly) {
  12827. sse::SSEMessage msg;
  12828. int retry_ms = 3000;
  12829. // According to SSE spec, this is treated as field name with empty value
  12830. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12831. // Since we don't recognize "data" without colon, data should be empty
  12832. EXPECT_EQ(msg.data, "");
  12833. }
  12834. // Test: Trailing \r handling
  12835. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12836. sse::SSEMessage msg;
  12837. int retry_ms = 3000;
  12838. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12839. EXPECT_EQ(msg.data, "hello");
  12840. }
  12841. // Test: Unknown fields ignored
  12842. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12843. sse::SSEMessage msg;
  12844. int retry_ms = 3000;
  12845. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12846. EXPECT_EQ(msg.data, "");
  12847. EXPECT_EQ(msg.event, "message");
  12848. }
  12849. // Test: Space after colon is optional
  12850. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12851. sse::SSEMessage msg1, msg2;
  12852. int retry_ms = 3000;
  12853. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12854. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12855. EXPECT_EQ(msg1.data, "hello");
  12856. EXPECT_EQ(msg2.data, "hello");
  12857. }
  12858. // Test: SSEMessage clear
  12859. TEST_F(SSEParsingTest, MessageClear) {
  12860. sse::SSEMessage msg;
  12861. msg.event = "custom";
  12862. msg.data = "some data";
  12863. msg.id = "123";
  12864. msg.clear();
  12865. EXPECT_EQ(msg.event, "message");
  12866. EXPECT_EQ(msg.data, "");
  12867. EXPECT_EQ(msg.id, "");
  12868. }
  12869. // Test: Complete event parsing
  12870. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12871. sse::SSEMessage msg;
  12872. int retry_ms = 3000;
  12873. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12874. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12875. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12876. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12877. // Blank line ends event
  12878. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12879. EXPECT_EQ(msg.event, "notification");
  12880. EXPECT_EQ(msg.id, "evt-42");
  12881. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12882. EXPECT_EQ(retry_ms, 1000);
  12883. }
  12884. //==============================================================================
  12885. // Integration Tests with Server
  12886. //==============================================================================
  12887. class SSEIntegrationTest : public ::testing::Test {
  12888. protected:
  12889. void SetUp() override {
  12890. stop_server_.store(false);
  12891. events_.clear();
  12892. server_ = httplib::detail::make_unique<Server>();
  12893. setup_server();
  12894. start_server();
  12895. }
  12896. void TearDown() override {
  12897. stop_server_.store(true);
  12898. event_cv_.notify_all();
  12899. server_->stop();
  12900. if (server_thread_.joinable()) { server_thread_.join(); }
  12901. }
  12902. void setup_server() {
  12903. // Simple SSE endpoint
  12904. server_->Get("/events", [this](const Request &req, Response &res) {
  12905. auto last_id = req.get_header_value("Last-Event-ID");
  12906. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12907. res.set_chunked_content_provider(
  12908. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12909. std::unique_lock<std::mutex> lock(event_mutex_);
  12910. if (event_cv_.wait_for(
  12911. lock, std::chrono::milliseconds(200), [this] {
  12912. return !events_.empty() || stop_server_.load();
  12913. })) {
  12914. if (stop_server_.load()) { return false; }
  12915. if (!events_.empty()) {
  12916. std::string event = events_.front();
  12917. events_.erase(events_.begin());
  12918. sink.write(event.data(), event.size());
  12919. return true;
  12920. }
  12921. }
  12922. return !stop_server_.load();
  12923. });
  12924. });
  12925. // Endpoint that returns error
  12926. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12927. res.status = 500;
  12928. res.set_content("Internal Server Error", "text/plain");
  12929. });
  12930. // Endpoint for custom event types
  12931. server_->Get("/custom-events", [](const Request &, Response &res) {
  12932. res.set_chunked_content_provider(
  12933. "text/event-stream", [](size_t offset, DataSink &sink) {
  12934. if (offset == 0) {
  12935. std::string event = "event: update\ndata: updated\n\n"
  12936. "event: delete\ndata: deleted\n\n";
  12937. sink.write(event.data(), event.size());
  12938. }
  12939. return false; // End stream after sending
  12940. });
  12941. });
  12942. }
  12943. void start_server() {
  12944. port_ = server_->bind_to_any_port(HOST);
  12945. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12946. // Wait for server to start
  12947. while (!server_->is_running()) {
  12948. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12949. }
  12950. }
  12951. int get_port() const { return port_; }
  12952. void send_event(const std::string &event) {
  12953. std::lock_guard<std::mutex> lock(event_mutex_);
  12954. events_.push_back(event);
  12955. event_cv_.notify_all();
  12956. }
  12957. std::unique_ptr<Server> server_;
  12958. std::thread server_thread_;
  12959. std::mutex event_mutex_;
  12960. std::condition_variable event_cv_;
  12961. std::vector<std::string> events_;
  12962. std::atomic<bool> stop_server_{false};
  12963. std::string last_received_event_id_;
  12964. int port_ = 0;
  12965. };
  12966. // Test: Successful connection and on_open callback
  12967. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12968. // Add a simple endpoint that sends one event and closes
  12969. server_->Get("/simple-event", [](const Request &, Response &res) {
  12970. res.set_chunked_content_provider(
  12971. "text/event-stream", [](size_t offset, DataSink &sink) {
  12972. if (offset == 0) {
  12973. std::string event = "data: hello\n\n";
  12974. sink.write(event.data(), event.size());
  12975. }
  12976. return false; // Close stream after sending
  12977. });
  12978. });
  12979. Client client("localhost", get_port());
  12980. sse::SSEClient sse(client, "/simple-event");
  12981. std::atomic<bool> open_called{false};
  12982. std::atomic<bool> message_received{false};
  12983. sse.on_open([&open_called]() { open_called.store(true); });
  12984. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12985. if (msg.data == "hello") { message_received.store(true); }
  12986. });
  12987. sse.set_reconnect_interval(100);
  12988. sse.set_max_reconnect_attempts(1);
  12989. // Start async
  12990. sse.start_async();
  12991. // Wait for message to be processed
  12992. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12993. sse.stop();
  12994. EXPECT_TRUE(open_called.load());
  12995. EXPECT_TRUE(message_received.load());
  12996. }
  12997. // Test: on_message callback
  12998. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12999. // Endpoint that sends multiple events then closes
  13000. server_->Get("/multi-event", [](const Request &, Response &res) {
  13001. res.set_chunked_content_provider(
  13002. "text/event-stream", [](size_t offset, DataSink &sink) {
  13003. if (offset == 0) {
  13004. std::string events = "data: message1\n\ndata: message2\n\n";
  13005. sink.write(events.data(), events.size());
  13006. }
  13007. return false;
  13008. });
  13009. });
  13010. Client client("localhost", get_port());
  13011. sse::SSEClient sse(client, "/multi-event");
  13012. std::vector<std::string> received_messages;
  13013. std::mutex messages_mutex;
  13014. sse.on_message([&](const sse::SSEMessage &msg) {
  13015. std::lock_guard<std::mutex> lock(messages_mutex);
  13016. received_messages.push_back(msg.data);
  13017. });
  13018. sse.set_reconnect_interval(100);
  13019. sse.set_max_reconnect_attempts(1);
  13020. sse.start_async();
  13021. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13022. sse.stop();
  13023. std::lock_guard<std::mutex> lock(messages_mutex);
  13024. EXPECT_GE(received_messages.size(), 2u);
  13025. if (received_messages.size() >= 2) {
  13026. EXPECT_EQ(received_messages[0], "message1");
  13027. EXPECT_EQ(received_messages[1], "message2");
  13028. }
  13029. }
  13030. // Test: on_event for specific types
  13031. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13032. Client client("localhost", get_port());
  13033. sse::SSEClient sse(client, "/custom-events");
  13034. std::atomic<bool> update_received{false};
  13035. std::atomic<bool> delete_received{false};
  13036. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13037. if (msg.data == "updated") { update_received.store(true); }
  13038. });
  13039. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13040. if (msg.data == "deleted") { delete_received.store(true); }
  13041. });
  13042. sse.set_max_reconnect_attempts(1);
  13043. sse.start_async();
  13044. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13045. sse.stop();
  13046. EXPECT_TRUE(update_received.load());
  13047. EXPECT_TRUE(delete_received.load());
  13048. }
  13049. // Test: on_error callback on connection failure
  13050. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13051. // Connect to a non-existent port
  13052. Client client("localhost", 59999);
  13053. sse::SSEClient sse(client, "/events");
  13054. std::atomic<bool> error_called{false};
  13055. Error received_error = Error::Success;
  13056. sse.on_error([&](Error err) {
  13057. error_called.store(true);
  13058. received_error = err;
  13059. });
  13060. sse.set_reconnect_interval(50);
  13061. sse.set_max_reconnect_attempts(1);
  13062. sse.start_async();
  13063. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13064. sse.stop();
  13065. EXPECT_TRUE(error_called.load());
  13066. EXPECT_NE(received_error, Error::Success);
  13067. }
  13068. // Test: Last-Event-ID header sent on reconnect
  13069. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13070. // Endpoint that sends event with ID
  13071. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13072. res.set_chunked_content_provider(
  13073. "text/event-stream", [](size_t offset, DataSink &sink) {
  13074. if (offset == 0) {
  13075. std::string event = "id: evt-123\ndata: test\n\n";
  13076. sink.write(event.data(), event.size());
  13077. }
  13078. return false;
  13079. });
  13080. });
  13081. Client client("localhost", get_port());
  13082. sse::SSEClient sse(client, "/event-with-id");
  13083. std::atomic<bool> id_received{false};
  13084. sse.on_message([&](const sse::SSEMessage &msg) {
  13085. if (!msg.id.empty()) { id_received.store(true); }
  13086. });
  13087. sse.set_reconnect_interval(100);
  13088. sse.set_max_reconnect_attempts(1);
  13089. sse.start_async();
  13090. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13091. sse.stop();
  13092. EXPECT_TRUE(id_received.load());
  13093. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13094. }
  13095. // Test: Manual stop
  13096. TEST_F(SSEIntegrationTest, ManualStop) {
  13097. // Endpoint that sends one event and stays open briefly
  13098. std::atomic<bool> handler_running{true};
  13099. server_->Get("/stay-open", [&handler_running](const Request &,
  13100. Response &res) {
  13101. res.set_chunked_content_provider(
  13102. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13103. if (offset == 0) {
  13104. std::string event = "data: connected\n\n";
  13105. sink.write(event.data(), event.size());
  13106. }
  13107. // Keep connection open while handler_running is true
  13108. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13109. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13110. }
  13111. return false;
  13112. });
  13113. });
  13114. Client client("localhost", get_port());
  13115. sse::SSEClient sse(client, "/stay-open");
  13116. std::atomic<bool> connected{false};
  13117. sse.on_open([&connected]() { connected.store(true); });
  13118. sse.set_reconnect_interval(100);
  13119. sse.set_max_reconnect_attempts(1);
  13120. sse.start_async();
  13121. // Wait for connection to establish
  13122. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13123. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13124. }
  13125. EXPECT_TRUE(connected.load());
  13126. EXPECT_TRUE(sse.is_connected());
  13127. // Signal handler to stop
  13128. handler_running.store(false);
  13129. // Stop SSE client
  13130. sse.stop();
  13131. EXPECT_FALSE(sse.is_connected());
  13132. }
  13133. // Test: SSEClient with custom headers
  13134. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13135. // Setup a server endpoint that checks for custom header
  13136. std::atomic<bool> header_received{false};
  13137. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13138. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13139. header_received.store(true);
  13140. }
  13141. res.set_chunked_content_provider("text/event-stream",
  13142. [](size_t, DataSink &) { return false; });
  13143. });
  13144. Client client("localhost", get_port());
  13145. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13146. sse::SSEClient sse(client, "/header-check", headers);
  13147. sse.set_max_reconnect_attempts(1);
  13148. sse.start_async();
  13149. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13150. sse.stop();
  13151. EXPECT_TRUE(header_received.load());
  13152. }
  13153. // Test: Reconnect interval configuration
  13154. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13155. Client client("localhost", get_port());
  13156. sse::SSEClient sse(client, "/events");
  13157. auto &result = sse.set_reconnect_interval(500);
  13158. // Builder pattern should return reference to self
  13159. EXPECT_EQ(&result, &sse);
  13160. }
  13161. // Test: Max reconnect attempts
  13162. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13163. // Connect to non-existent port to force reconnects
  13164. Client client("localhost", 59998);
  13165. sse::SSEClient sse(client, "/events");
  13166. std::atomic<int> error_count{0};
  13167. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13168. sse.set_reconnect_interval(50);
  13169. sse.set_max_reconnect_attempts(2);
  13170. auto start = std::chrono::steady_clock::now();
  13171. sse.start(); // Blocking call
  13172. auto end = std::chrono::steady_clock::now();
  13173. // Should have stopped after 2 failed attempts
  13174. EXPECT_GE(error_count.load(), 2);
  13175. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13176. auto duration =
  13177. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13178. #ifdef _WIN32
  13179. // Windows is much slower for socket connection failures
  13180. EXPECT_LT(duration.count(), 7000);
  13181. #else
  13182. EXPECT_LT(duration.count(), 1000);
  13183. #endif
  13184. }
  13185. // Test: Multi-line data in integration
  13186. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13187. // Endpoint with multi-line data
  13188. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13189. res.set_chunked_content_provider(
  13190. "text/event-stream", [](size_t offset, DataSink &sink) {
  13191. if (offset == 0) {
  13192. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13193. sink.write(event.data(), event.size());
  13194. }
  13195. return false;
  13196. });
  13197. });
  13198. Client client("localhost", get_port());
  13199. sse::SSEClient sse(client, "/multiline-data");
  13200. std::string received_data;
  13201. std::mutex data_mutex;
  13202. sse.on_message([&](const sse::SSEMessage &msg) {
  13203. std::lock_guard<std::mutex> lock(data_mutex);
  13204. received_data = msg.data;
  13205. });
  13206. sse.set_reconnect_interval(100);
  13207. sse.set_max_reconnect_attempts(1);
  13208. sse.start_async();
  13209. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13210. sse.stop();
  13211. std::lock_guard<std::mutex> lock(data_mutex);
  13212. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13213. }
  13214. // Test: Auto-reconnect after server disconnection
  13215. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13216. std::atomic<int> connection_count{0};
  13217. std::atomic<int> message_count{0};
  13218. // Endpoint that sends one event and closes, forcing reconnect
  13219. server_->Get("/reconnect-test",
  13220. [&connection_count](const Request &, Response &res) {
  13221. connection_count.fetch_add(1);
  13222. res.set_chunked_content_provider(
  13223. "text/event-stream", [](size_t offset, DataSink &sink) {
  13224. if (offset == 0) {
  13225. std::string event = "data: hello\n\n";
  13226. sink.write(event.data(), event.size());
  13227. }
  13228. return false; // Close connection after sending
  13229. });
  13230. });
  13231. Client client("localhost", get_port());
  13232. sse::SSEClient sse(client, "/reconnect-test");
  13233. sse.on_message([&message_count](const sse::SSEMessage &) {
  13234. message_count.fetch_add(1);
  13235. });
  13236. sse.set_reconnect_interval(100);
  13237. sse.set_max_reconnect_attempts(3);
  13238. sse.start_async();
  13239. // Wait long enough for multiple reconnects
  13240. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13241. sse.stop();
  13242. // Should have connected multiple times (initial + reconnects)
  13243. EXPECT_GE(connection_count.load(), 2);
  13244. // Should have received messages from multiple connections
  13245. EXPECT_GE(message_count.load(), 2);
  13246. }
  13247. // Test: Last-Event-ID sent on reconnect
  13248. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13249. std::atomic<int> connection_count{0};
  13250. std::vector<std::string> received_last_event_ids;
  13251. std::mutex id_mutex;
  13252. // Endpoint that checks Last-Event-ID header and sends event with ID
  13253. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13254. int conn = connection_count.fetch_add(1);
  13255. // Capture the Last-Event-ID header from each connection
  13256. {
  13257. std::lock_guard<std::mutex> lock(id_mutex);
  13258. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13259. }
  13260. res.set_chunked_content_provider(
  13261. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13262. if (offset == 0) {
  13263. std::string event =
  13264. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13265. sink.write(event.data(), event.size());
  13266. }
  13267. return false;
  13268. });
  13269. });
  13270. Client client("localhost", get_port());
  13271. sse::SSEClient sse(client, "/reconnect-with-id");
  13272. sse.set_reconnect_interval(100);
  13273. sse.set_max_reconnect_attempts(3);
  13274. sse.start_async();
  13275. // Wait for at least 2 connections
  13276. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13277. sse.stop();
  13278. // Verify behavior
  13279. std::lock_guard<std::mutex> lock(id_mutex);
  13280. EXPECT_GE(received_last_event_ids.size(), 2u);
  13281. // First connection should have no Last-Event-ID
  13282. if (!received_last_event_ids.empty()) {
  13283. EXPECT_EQ(received_last_event_ids[0], "");
  13284. }
  13285. // Second connection should have Last-Event-ID from first connection
  13286. if (received_last_event_ids.size() >= 2) {
  13287. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13288. }
  13289. }
  13290. TEST(Issue2318Test, EmptyHostString) {
  13291. {
  13292. httplib::Client cli_empty("", PORT);
  13293. auto res = cli_empty.Get("/");
  13294. ASSERT_FALSE(res);
  13295. EXPECT_EQ(httplib::Error::Connection, res.error());
  13296. }
  13297. {
  13298. httplib::Client cli(" ", PORT);
  13299. auto res = cli.Get("/");
  13300. ASSERT_FALSE(res);
  13301. EXPECT_EQ(httplib::Error::Connection, res.error());
  13302. }
  13303. }
  13304. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13305. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13306. Server svr;
  13307. // Set a small payload limit (1KB)
  13308. svr.set_payload_max_length(1024);
  13309. svr.Post("/test", [&](const Request &req, Response &res) {
  13310. res.set_content("Body size: " + std::to_string(req.body.size()),
  13311. "text/plain");
  13312. });
  13313. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13314. auto se = detail::scope_exit([&] {
  13315. svr.stop();
  13316. listen_thread.join();
  13317. });
  13318. svr.wait_until_ready();
  13319. // Create data that compresses well but exceeds limit when decompressed
  13320. // 8KB of repeated null bytes compresses to a very small size
  13321. std::string original_data(8 * 1024, '\0');
  13322. // Compress the data using gzip
  13323. std::string compressed_data;
  13324. detail::gzip_compressor compressor;
  13325. compressor.compress(original_data.data(), original_data.size(), true,
  13326. [&](const char *data, size_t size) {
  13327. compressed_data.append(data, size);
  13328. return true;
  13329. });
  13330. // Verify compression worked (compressed should be much smaller)
  13331. ASSERT_LT(compressed_data.size(), original_data.size());
  13332. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13333. // Send compressed data with Content-Encoding: gzip
  13334. Client cli(HOST, PORT);
  13335. Headers headers = {{"Content-Encoding", "gzip"}};
  13336. auto res =
  13337. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13338. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13339. ASSERT_TRUE(res);
  13340. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13341. }
  13342. #endif
  13343. // ============================================================================
  13344. // OpenSSL-Specific Tests
  13345. // ============================================================================
  13346. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13347. X509 *readCertificate(const std::string &strFileName) {
  13348. std::ifstream inStream(strFileName);
  13349. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13350. std::istreambuf_iterator<char>());
  13351. if (strCertPEM.empty()) return (nullptr);
  13352. BIO *pbCert = BIO_new(BIO_s_mem());
  13353. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13354. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13355. BIO_free(pbCert);
  13356. return (pCert);
  13357. }
  13358. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13359. std::ifstream inStream(strFileName);
  13360. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13361. std::istreambuf_iterator<char>());
  13362. if (strPrivateKeyPEM.empty()) return (nullptr);
  13363. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13364. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13365. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13366. BIO_free(pbPrivKey);
  13367. return (pPrivateKey);
  13368. }
  13369. TEST(BindServerTest, UpdateCerts) {
  13370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13371. int port = svr.bind_to_any_port("0.0.0.0");
  13372. ASSERT_TRUE(svr.is_valid());
  13373. ASSERT_TRUE(port > 0);
  13374. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13375. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13376. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13377. ASSERT_TRUE(cert != nullptr);
  13378. ASSERT_TRUE(ca_cert != nullptr);
  13379. ASSERT_TRUE(key != nullptr);
  13380. X509_STORE *cert_store = X509_STORE_new();
  13381. X509_STORE_add_cert(cert_store, ca_cert);
  13382. // svr.update_certs(cert, key, cert_store); // deprecated
  13383. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13384. CLIENT_CA_CERT_FILE);
  13385. ASSERT_TRUE(svr.is_valid());
  13386. svr.stop();
  13387. X509_STORE_free(cert_store);
  13388. X509_free(cert);
  13389. X509_free(ca_cert);
  13390. EVP_PKEY_free(key);
  13391. }
  13392. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13393. // client CA list correctly for TLS handshake
  13394. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13395. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13396. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13397. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13398. ASSERT_TRUE(cert != nullptr);
  13399. ASSERT_TRUE(ca_cert != nullptr);
  13400. ASSERT_TRUE(key != nullptr);
  13401. X509_STORE *cert_store = X509_STORE_new();
  13402. X509_STORE_add_cert(cert_store, ca_cert);
  13403. // Use X509-based constructor (deprecated but should still work correctly)
  13404. #pragma GCC diagnostic push
  13405. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13406. SSLServer svr(cert, key, cert_store);
  13407. #pragma GCC diagnostic pop
  13408. ASSERT_TRUE(svr.is_valid());
  13409. // Verify that client CA list is set in SSL_CTX
  13410. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13411. ASSERT_TRUE(ssl_ctx != nullptr);
  13412. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13413. ASSERT_TRUE(ca_list != nullptr);
  13414. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13415. X509_free(cert);
  13416. X509_free(ca_cert);
  13417. EVP_PKEY_free(key);
  13418. }
  13419. // Test that update_certs() updates client CA list correctly
  13420. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13421. // Start with file-based constructor
  13422. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13423. ASSERT_TRUE(svr.is_valid());
  13424. // Initially no client CA list should be set
  13425. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13426. ASSERT_TRUE(ssl_ctx != nullptr);
  13427. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13428. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13429. EXPECT_EQ(0, count_before);
  13430. // Now update with client CA (PEM string)
  13431. std::string cert_pem, key_pem, ca_pem;
  13432. read_file(SERVER_CERT_FILE, cert_pem);
  13433. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13434. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13435. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13436. ASSERT_TRUE(svr.is_valid());
  13437. // Now client CA list should be set
  13438. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13439. ASSERT_TRUE(ca_list_after != nullptr);
  13440. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13441. }
  13442. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13443. // Test that the file-path SSLServer constructor properly sets the client CA
  13444. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13445. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13446. ASSERT_TRUE(svr.is_valid());
  13447. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13448. ASSERT_TRUE(ssl_ctx != nullptr);
  13449. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13450. ASSERT_TRUE(ca_list != nullptr);
  13451. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13452. }
  13453. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13454. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13455. // prepare large data
  13456. std::random_device seed_gen;
  13457. std::mt19937 random(seed_gen());
  13458. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13459. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13460. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13461. // server
  13462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13463. ASSERT_TRUE(svr.is_valid());
  13464. svr.Post("/binary", [&](const Request &req, Response &res) {
  13465. EXPECT_EQ(large_size_byte, req.body.size());
  13466. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13467. res.set_content(req.body, "application/octet-stream");
  13468. });
  13469. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13470. auto se = detail::scope_exit([&] {
  13471. svr.stop();
  13472. listen_thread.join();
  13473. ASSERT_FALSE(svr.is_running());
  13474. });
  13475. svr.wait_until_ready();
  13476. // client POST
  13477. SSLClient cli("localhost", PORT);
  13478. cli.enable_server_certificate_verification(false);
  13479. cli.set_read_timeout(std::chrono::seconds(100));
  13480. cli.set_write_timeout(std::chrono::seconds(100));
  13481. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13482. large_size_byte, "application/octet-stream");
  13483. // compare
  13484. EXPECT_EQ(StatusCode::OK_200, res->status);
  13485. EXPECT_EQ(large_size_byte, res->body.size());
  13486. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13487. }
  13488. #endif
  13489. // ============================================================================
  13490. // MbedTLS-Specific Tests
  13491. // ============================================================================
  13492. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13493. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13494. using namespace httplib::tls;
  13495. // Track if callback was invoked
  13496. bool callback_invoked = false;
  13497. // The callback receives void* ctx which is actually MbedTlsContext*
  13498. // We can access the mbedtls_ssl_config via the context
  13499. auto setup_callback = [&callback_invoked](void *ctx) {
  13500. callback_invoked = true;
  13501. // Cast to MbedTlsContext* to access the ssl config
  13502. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13503. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13504. // Use static variables to hold certificate data (simplified for test)
  13505. static mbedtls_x509_crt own_cert;
  13506. static mbedtls_pk_context own_key;
  13507. static mbedtls_x509_crt ca_chain;
  13508. static bool initialized = false;
  13509. if (!initialized) {
  13510. mbedtls_x509_crt_init(&own_cert);
  13511. mbedtls_pk_init(&own_key);
  13512. mbedtls_x509_crt_init(&ca_chain);
  13513. // Load server certificate
  13514. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13515. return false;
  13516. }
  13517. // Load server private key
  13518. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13519. #if MBEDTLS_VERSION_MAJOR >= 3
  13520. ,
  13521. mbedtls_ctr_drbg_random, nullptr
  13522. #endif
  13523. ) != 0) {
  13524. return false;
  13525. }
  13526. // Load CA chain for client verification
  13527. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13528. return false;
  13529. }
  13530. initialized = true;
  13531. }
  13532. // Configure the SSL config
  13533. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13534. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13535. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13536. // Set minimum TLS version using mbedTLS native API
  13537. #if MBEDTLS_VERSION_MAJOR >= 3
  13538. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13539. #else
  13540. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13541. MBEDTLS_SSL_MINOR_VERSION_3);
  13542. #endif
  13543. return true;
  13544. };
  13545. SSLServer svr(setup_callback);
  13546. ASSERT_TRUE(svr.is_valid());
  13547. ASSERT_TRUE(callback_invoked);
  13548. svr.Get("/test", [&](const Request &req, Response &res) {
  13549. res.set_content("test", "text/plain");
  13550. auto cert = req.peer_cert();
  13551. ASSERT_TRUE(static_cast<bool>(cert));
  13552. auto common_name = cert.subject_cn();
  13553. EXPECT_EQ("Common Name", common_name);
  13554. });
  13555. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13556. auto se = detail::scope_exit([&] {
  13557. svr.stop();
  13558. t.join();
  13559. ASSERT_FALSE(svr.is_running());
  13560. });
  13561. svr.wait_until_ready();
  13562. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13563. cli.enable_server_certificate_verification(false);
  13564. cli.set_connection_timeout(30);
  13565. auto res = cli.Get("/test");
  13566. ASSERT_TRUE(res);
  13567. ASSERT_EQ(StatusCode::OK_200, res->status);
  13568. }
  13569. #endif
  13570. // WebSocket Tests
  13571. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13572. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13573. // defining the meaning of these bits has been negotiated.
  13574. auto make_frame = [](uint8_t first_byte) {
  13575. std::string frame;
  13576. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13577. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13578. frame += "Hello";
  13579. return frame;
  13580. };
  13581. // RSV1 set (0x40)
  13582. {
  13583. detail::BufferStream strm;
  13584. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13585. ws::Opcode opcode;
  13586. std::string payload;
  13587. bool fin;
  13588. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13589. false, 1024));
  13590. }
  13591. // RSV2 set (0x20)
  13592. {
  13593. detail::BufferStream strm;
  13594. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13595. ws::Opcode opcode;
  13596. std::string payload;
  13597. bool fin;
  13598. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13599. false, 1024));
  13600. }
  13601. // RSV3 set (0x10)
  13602. {
  13603. detail::BufferStream strm;
  13604. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13605. ws::Opcode opcode;
  13606. std::string payload;
  13607. bool fin;
  13608. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13609. false, 1024));
  13610. }
  13611. // No RSV bits set - should succeed
  13612. {
  13613. detail::BufferStream strm;
  13614. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13615. ws::Opcode opcode;
  13616. std::string payload;
  13617. bool fin;
  13618. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13619. false, 1024));
  13620. EXPECT_EQ(ws::Opcode::Text, opcode);
  13621. EXPECT_EQ("Hello", payload);
  13622. EXPECT_TRUE(fin);
  13623. }
  13624. }
  13625. TEST(WebSocketTest, ControlFrameValidation) {
  13626. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13627. // payload length <= 125.
  13628. // Ping with FIN=0 - must be rejected
  13629. {
  13630. detail::BufferStream strm;
  13631. std::string frame;
  13632. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13633. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13634. strm.write(frame.data(), frame.size());
  13635. ws::Opcode opcode;
  13636. std::string payload;
  13637. bool fin;
  13638. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13639. false, 1024));
  13640. }
  13641. // Close with FIN=0 - must be rejected
  13642. {
  13643. detail::BufferStream strm;
  13644. std::string frame;
  13645. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13646. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13647. strm.write(frame.data(), frame.size());
  13648. ws::Opcode opcode;
  13649. std::string payload;
  13650. bool fin;
  13651. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13652. false, 1024));
  13653. }
  13654. // Ping with payload_len=126 (extended length) - must be rejected
  13655. {
  13656. detail::BufferStream strm;
  13657. std::string frame;
  13658. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13659. frame += static_cast<char>(126); // payload_len=126 (>125)
  13660. frame += static_cast<char>(0x00); // extended length high byte
  13661. frame += static_cast<char>(126); // extended length low byte
  13662. frame += std::string(126, 'x');
  13663. strm.write(frame.data(), frame.size());
  13664. ws::Opcode opcode;
  13665. std::string payload;
  13666. bool fin;
  13667. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13668. false, 1024));
  13669. }
  13670. // Ping with FIN=1 and payload_len=125 - should succeed
  13671. {
  13672. detail::BufferStream strm;
  13673. std::string frame;
  13674. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13675. frame += static_cast<char>(125); // payload_len=125
  13676. frame += std::string(125, 'x');
  13677. strm.write(frame.data(), frame.size());
  13678. ws::Opcode opcode;
  13679. std::string payload;
  13680. bool fin;
  13681. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13682. false, 1024));
  13683. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13684. EXPECT_EQ(125u, payload.size());
  13685. EXPECT_TRUE(fin);
  13686. }
  13687. }
  13688. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13689. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13690. // length MUST be 0.
  13691. // MSB set - must be rejected
  13692. {
  13693. detail::BufferStream strm;
  13694. std::string frame;
  13695. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13696. frame += static_cast<char>(127); // 64-bit extended length
  13697. frame += static_cast<char>(0x80); // MSB set (invalid)
  13698. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13699. strm.write(frame.data(), frame.size());
  13700. ws::Opcode opcode;
  13701. std::string payload;
  13702. bool fin;
  13703. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13704. false, 1024));
  13705. }
  13706. // MSB clear - should pass length parsing (will be rejected by max_len,
  13707. // but that's a different check; use a small length to verify)
  13708. {
  13709. detail::BufferStream strm;
  13710. std::string frame;
  13711. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13712. frame += static_cast<char>(127); // 64-bit extended length
  13713. frame += std::string(7, '\0'); // high bytes = 0
  13714. frame += static_cast<char>(0x03); // length = 3
  13715. frame += "abc";
  13716. strm.write(frame.data(), frame.size());
  13717. ws::Opcode opcode;
  13718. std::string payload;
  13719. bool fin;
  13720. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13721. false, 1024));
  13722. EXPECT_EQ(ws::Opcode::Text, opcode);
  13723. EXPECT_EQ("abc", payload);
  13724. }
  13725. }
  13726. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13727. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13728. // Valid UTF-8
  13729. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13730. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13731. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13732. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13733. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13734. // Invalid UTF-8
  13735. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13736. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13737. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13738. EXPECT_FALSE(
  13739. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13740. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13741. }
  13742. TEST(WebSocketTest, ConnectAndDisconnect) {
  13743. Server svr;
  13744. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13745. std::string msg;
  13746. while (ws.read(msg)) {}
  13747. });
  13748. auto port = svr.bind_to_any_port(HOST);
  13749. std::thread t([&]() { svr.listen_after_bind(); });
  13750. svr.wait_until_ready();
  13751. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13752. ASSERT_TRUE(client.connect());
  13753. EXPECT_TRUE(client.is_open());
  13754. client.close();
  13755. EXPECT_FALSE(client.is_open());
  13756. svr.stop();
  13757. t.join();
  13758. }
  13759. TEST(WebSocketTest, ValidURL) {
  13760. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13761. EXPECT_TRUE(ws1.is_valid());
  13762. ws::WebSocketClient ws2("ws://example.com/path");
  13763. EXPECT_TRUE(ws2.is_valid());
  13764. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13765. EXPECT_TRUE(ws3.is_valid());
  13766. #ifdef CPPHTTPLIB_SSL_ENABLED
  13767. ws::WebSocketClient wss1("wss://example.com/path");
  13768. EXPECT_TRUE(wss1.is_valid());
  13769. ws::WebSocketClient wss2("wss://example.com:443/path");
  13770. EXPECT_TRUE(wss2.is_valid());
  13771. #endif
  13772. }
  13773. TEST(WebSocketTest, InvalidURL) {
  13774. // No scheme
  13775. ws::WebSocketClient ws1("localhost:8080/path");
  13776. EXPECT_FALSE(ws1.is_valid());
  13777. // No path
  13778. ws::WebSocketClient ws2("ws://localhost:8080");
  13779. EXPECT_FALSE(ws2.is_valid());
  13780. // Empty string
  13781. ws::WebSocketClient ws3("");
  13782. EXPECT_FALSE(ws3.is_valid());
  13783. // Missing host
  13784. ws::WebSocketClient ws4("ws://:8080/path");
  13785. EXPECT_FALSE(ws4.is_valid());
  13786. // Port number overflow — should not crash
  13787. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13788. EXPECT_FALSE(ws5.is_valid());
  13789. // Port out of range
  13790. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13791. EXPECT_FALSE(ws6.is_valid());
  13792. }
  13793. TEST(WebSocketTest, UnsupportedScheme) {
  13794. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13795. ws::WebSocketClient ws1("http://localhost:8080/path");
  13796. EXPECT_FALSE(ws1.is_valid());
  13797. ws::WebSocketClient ws2("https://localhost:8080/path");
  13798. EXPECT_FALSE(ws2.is_valid());
  13799. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13800. EXPECT_FALSE(ws3.is_valid());
  13801. #else
  13802. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13803. std::invalid_argument);
  13804. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13805. std::invalid_argument);
  13806. #endif
  13807. }
  13808. TEST(WebSocketTest, ConnectWhenInvalid) {
  13809. ws::WebSocketClient ws("not a valid url");
  13810. EXPECT_FALSE(ws.is_valid());
  13811. EXPECT_FALSE(ws.connect());
  13812. }
  13813. TEST(WebSocketTest, DefaultPort) {
  13814. ws::WebSocketClient ws1("ws://example.com/path");
  13815. EXPECT_TRUE(ws1.is_valid());
  13816. // ws:// defaults to port 80 (verified by successful parse)
  13817. #ifdef CPPHTTPLIB_SSL_ENABLED
  13818. ws::WebSocketClient ws2("wss://example.com/path");
  13819. EXPECT_TRUE(ws2.is_valid());
  13820. // wss:// defaults to port 443 (verified by successful parse)
  13821. #endif
  13822. }
  13823. TEST(WebSocketTest, IPv6LiteralAddress) {
  13824. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13825. EXPECT_TRUE(ws1.is_valid());
  13826. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13827. EXPECT_TRUE(ws2.is_valid());
  13828. }
  13829. TEST(WebSocketTest, ComplexPath) {
  13830. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13831. EXPECT_TRUE(ws1.is_valid());
  13832. ws::WebSocketClient ws2("ws://localhost:8080/");
  13833. EXPECT_TRUE(ws2.is_valid());
  13834. }
  13835. class WebSocketIntegrationTest : public ::testing::Test {
  13836. protected:
  13837. void SetUp() override {
  13838. server_ = httplib::detail::make_unique<Server>();
  13839. setup_server();
  13840. start_server();
  13841. }
  13842. void TearDown() override {
  13843. server_->stop();
  13844. if (server_thread_.joinable()) { server_thread_.join(); }
  13845. }
  13846. void setup_server() {
  13847. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13848. std::string msg;
  13849. ws::ReadResult ret;
  13850. while ((ret = ws.read(msg))) {
  13851. if (ret == ws::Binary) {
  13852. ws.send(msg.data(), msg.size());
  13853. } else {
  13854. ws.send(msg);
  13855. }
  13856. }
  13857. });
  13858. server_->WebSocket("/ws-echo-string",
  13859. [](const Request &, ws::WebSocket &ws) {
  13860. std::string msg;
  13861. while (ws.read(msg)) {
  13862. ws.send("echo: " + msg);
  13863. }
  13864. });
  13865. server_->WebSocket(
  13866. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13867. // Echo back request metadata
  13868. ws.send("path:" + req.path);
  13869. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13870. std::string msg;
  13871. while (ws.read(msg)) {}
  13872. });
  13873. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13874. std::string msg;
  13875. ws.read(msg); // wait for a message
  13876. ws.close();
  13877. });
  13878. server_->WebSocket("/ws-close-status",
  13879. [](const Request &, ws::WebSocket &ws) {
  13880. std::string msg;
  13881. ws.read(msg); // wait for a message
  13882. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13883. });
  13884. server_->WebSocket(
  13885. "/ws-subprotocol",
  13886. [](const Request &, ws::WebSocket &ws) {
  13887. std::string msg;
  13888. while (ws.read(msg)) {
  13889. ws.send(msg);
  13890. }
  13891. },
  13892. [](const std::vector<std::string> &protocols) -> std::string {
  13893. for (const auto &p : protocols) {
  13894. if (p == "graphql-ws") { return p; }
  13895. }
  13896. return "";
  13897. });
  13898. }
  13899. void start_server() {
  13900. port_ = server_->bind_to_any_port(HOST);
  13901. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13902. server_->wait_until_ready();
  13903. }
  13904. std::unique_ptr<Server> server_;
  13905. std::thread server_thread_;
  13906. int port_ = 0;
  13907. };
  13908. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13909. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13910. "/ws-echo");
  13911. ASSERT_TRUE(client.connect());
  13912. ASSERT_TRUE(client.is_open());
  13913. ASSERT_TRUE(client.send("Hello WebSocket"));
  13914. std::string msg;
  13915. EXPECT_EQ(ws::Text, client.read(msg));
  13916. EXPECT_EQ("Hello WebSocket", msg);
  13917. client.close();
  13918. }
  13919. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13920. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13921. "/ws-echo");
  13922. ASSERT_TRUE(client.connect());
  13923. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13924. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13925. std::string msg;
  13926. EXPECT_EQ(ws::Binary, client.read(msg));
  13927. EXPECT_EQ(binary_data, msg);
  13928. client.close();
  13929. }
  13930. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13931. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13932. "/ws-echo");
  13933. ASSERT_TRUE(client.connect());
  13934. for (int i = 0; i < 10; i++) {
  13935. auto text = "message " + std::to_string(i);
  13936. ASSERT_TRUE(client.send(text));
  13937. std::string msg;
  13938. ASSERT_TRUE(client.read(msg));
  13939. EXPECT_EQ(text, msg);
  13940. }
  13941. client.close();
  13942. }
  13943. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13945. "/ws-close");
  13946. ASSERT_TRUE(client.connect());
  13947. // Send a message to trigger the server to close
  13948. ASSERT_TRUE(client.send("trigger close"));
  13949. // The server will close, so read should return false
  13950. std::string msg;
  13951. EXPECT_FALSE(client.read(msg));
  13952. EXPECT_FALSE(client.is_open());
  13953. }
  13954. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13955. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13956. "/ws-echo");
  13957. ASSERT_TRUE(client.connect());
  13958. // 128KB message
  13959. std::string large_data(128 * 1024, 'X');
  13960. ASSERT_TRUE(client.send(large_data));
  13961. std::string msg;
  13962. ASSERT_TRUE(client.read(msg));
  13963. EXPECT_EQ(large_data, msg);
  13964. client.close();
  13965. }
  13966. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13967. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13968. "/ws-echo");
  13969. ASSERT_TRUE(client.connect());
  13970. const int num_threads = 4;
  13971. std::vector<std::thread> threads;
  13972. std::atomic<int> send_count{0};
  13973. for (int t = 0; t < num_threads; t++) {
  13974. threads.emplace_back([&client, &send_count, t]() {
  13975. for (int i = 0; i < 5; i++) {
  13976. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13977. if (client.send(text)) { send_count++; }
  13978. }
  13979. });
  13980. }
  13981. for (auto &th : threads) {
  13982. th.join();
  13983. }
  13984. int received = 0;
  13985. std::string msg;
  13986. while (received < send_count.load()) {
  13987. if (!client.read(msg)) { break; }
  13988. received++;
  13989. }
  13990. EXPECT_EQ(send_count.load(), received);
  13991. client.close();
  13992. }
  13993. TEST_F(WebSocketIntegrationTest, ReadString) {
  13994. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13995. "/ws-echo-string");
  13996. ASSERT_TRUE(client.connect());
  13997. ASSERT_TRUE(client.send("hello"));
  13998. std::string msg;
  13999. ASSERT_TRUE(client.read(msg));
  14000. EXPECT_EQ("echo: hello", msg);
  14001. ASSERT_TRUE(client.send("world"));
  14002. ASSERT_TRUE(client.read(msg));
  14003. EXPECT_EQ("echo: world", msg);
  14004. client.close();
  14005. }
  14006. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14007. Headers headers = {{"X-Test-Header", "test-value"}};
  14008. ws::WebSocketClient client(
  14009. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14010. ASSERT_TRUE(client.connect());
  14011. std::string msg;
  14012. ASSERT_TRUE(client.read(msg));
  14013. EXPECT_EQ("path:/ws-request-info", msg);
  14014. ASSERT_TRUE(client.read(msg));
  14015. EXPECT_EQ("header:test-value", msg);
  14016. client.close();
  14017. }
  14018. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14019. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14020. "/ws-echo");
  14021. client.set_read_timeout(1, 0); // 1 second
  14022. ASSERT_TRUE(client.connect());
  14023. // Don't send anything — server echo handler waits for a message,
  14024. // so read() should time out and return false.
  14025. std::string msg;
  14026. EXPECT_FALSE(client.read(msg));
  14027. }
  14028. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14029. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14030. "/ws-echo");
  14031. client.set_read_timeout(5, 0);
  14032. ASSERT_TRUE(client.connect());
  14033. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14034. // The server should reject it and close the connection.
  14035. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14036. client.send(oversized);
  14037. // The server's read() should have failed due to payload limit,
  14038. // so our read() should return false (connection closed).
  14039. std::string msg;
  14040. EXPECT_FALSE(client.read(msg));
  14041. }
  14042. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14043. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14044. "/ws-echo");
  14045. client.set_read_timeout(10, 0);
  14046. ASSERT_TRUE(client.connect());
  14047. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14048. // This should succeed.
  14049. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14050. ASSERT_TRUE(client.send(at_limit));
  14051. std::string msg;
  14052. ASSERT_TRUE(client.read(msg));
  14053. EXPECT_EQ(at_limit.size(), msg.size());
  14054. client.close();
  14055. }
  14056. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14057. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14058. "/nonexistent");
  14059. EXPECT_FALSE(client.connect());
  14060. EXPECT_FALSE(client.is_open());
  14061. }
  14062. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14063. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14064. "/ws-echo");
  14065. ASSERT_TRUE(client.connect());
  14066. ASSERT_TRUE(client.send(""));
  14067. std::string msg;
  14068. EXPECT_EQ(ws::Text, client.read(msg));
  14069. EXPECT_EQ("", msg);
  14070. client.close();
  14071. }
  14072. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14073. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14074. "/ws-echo");
  14075. // First connection
  14076. ASSERT_TRUE(client.connect());
  14077. ASSERT_TRUE(client.send("first"));
  14078. std::string msg;
  14079. ASSERT_TRUE(client.read(msg));
  14080. EXPECT_EQ("first", msg);
  14081. client.close();
  14082. EXPECT_FALSE(client.is_open());
  14083. // Reconnect using the same client object
  14084. ASSERT_TRUE(client.connect());
  14085. ASSERT_TRUE(client.is_open());
  14086. ASSERT_TRUE(client.send("second"));
  14087. ASSERT_TRUE(client.read(msg));
  14088. EXPECT_EQ("second", msg);
  14089. client.close();
  14090. }
  14091. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14092. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14093. "/ws-close-status");
  14094. ASSERT_TRUE(client.connect());
  14095. // Trigger the server to close with GoingAway status
  14096. ASSERT_TRUE(client.send("trigger"));
  14097. // read() should return false after receiving the close frame
  14098. std::string msg;
  14099. EXPECT_FALSE(client.read(msg));
  14100. EXPECT_FALSE(client.is_open());
  14101. }
  14102. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14103. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14104. "/ws-echo");
  14105. ASSERT_TRUE(client.connect());
  14106. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14107. EXPECT_FALSE(client.is_open());
  14108. }
  14109. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14110. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14111. ws::WebSocketClient client(
  14112. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14113. ASSERT_TRUE(client.connect());
  14114. // Server should have selected graphql-ws
  14115. EXPECT_EQ("graphql-ws", client.subprotocol());
  14116. client.close();
  14117. }
  14118. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14119. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14120. ws::WebSocketClient client(
  14121. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14122. ASSERT_TRUE(client.connect());
  14123. // Server should not have selected any subprotocol
  14124. EXPECT_TRUE(client.subprotocol().empty());
  14125. client.close();
  14126. }
  14127. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14128. // Connect without requesting any subprotocol
  14129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14130. "/ws-subprotocol");
  14131. ASSERT_TRUE(client.connect());
  14132. EXPECT_TRUE(client.subprotocol().empty());
  14133. client.close();
  14134. }
  14135. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14136. Server svr;
  14137. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14138. if (!req.has_header("Authorization")) {
  14139. res.status = StatusCode::Unauthorized_401;
  14140. res.set_content("Unauthorized", "text/plain");
  14141. return Server::HandlerResponse::Handled;
  14142. }
  14143. return Server::HandlerResponse::Unhandled;
  14144. });
  14145. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14146. std::string msg;
  14147. while (ws.read(msg)) {
  14148. ws.send(msg);
  14149. }
  14150. });
  14151. auto port = svr.bind_to_any_port("localhost");
  14152. std::thread t([&]() { svr.listen_after_bind(); });
  14153. svr.wait_until_ready();
  14154. // Without Authorization header - should be rejected before upgrade
  14155. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14156. EXPECT_FALSE(client1.connect());
  14157. // With Authorization header - should succeed
  14158. Headers headers = {{"Authorization", "Bearer token123"}};
  14159. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14160. headers);
  14161. ASSERT_TRUE(client2.connect());
  14162. ASSERT_TRUE(client2.send("hello"));
  14163. std::string msg;
  14164. ASSERT_TRUE(client2.read(msg));
  14165. EXPECT_EQ("hello", msg);
  14166. client2.close();
  14167. svr.stop();
  14168. t.join();
  14169. }
  14170. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14171. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14172. protected:
  14173. void SetUp() override {
  14174. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14175. SERVER_PRIVATE_KEY_FILE);
  14176. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14177. std::string msg;
  14178. ws::ReadResult ret;
  14179. while ((ret = ws.read(msg))) {
  14180. if (ret == ws::Binary) {
  14181. ws.send(msg.data(), msg.size());
  14182. } else {
  14183. ws.send(msg);
  14184. }
  14185. }
  14186. });
  14187. port_ = server_->bind_to_any_port(HOST);
  14188. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14189. server_->wait_until_ready();
  14190. }
  14191. void TearDown() override {
  14192. server_->stop();
  14193. if (server_thread_.joinable()) { server_thread_.join(); }
  14194. }
  14195. std::unique_ptr<SSLServer> server_;
  14196. std::thread server_thread_;
  14197. int port_ = 0;
  14198. };
  14199. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14200. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14201. "/ws-echo");
  14202. client.enable_server_certificate_verification(false);
  14203. ASSERT_TRUE(client.connect());
  14204. ASSERT_TRUE(client.is_open());
  14205. ASSERT_TRUE(client.send("Hello WSS"));
  14206. std::string msg;
  14207. EXPECT_EQ(ws::Text, client.read(msg));
  14208. EXPECT_EQ("Hello WSS", msg);
  14209. client.close();
  14210. }
  14211. #endif