test.cc 608 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740
  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. #ifdef CPPHTTPLIB_SSL_ENABLED
  50. namespace httplib {
  51. namespace tls {
  52. // Declared here for the split build, where the TLS abstraction declarations
  53. // live below the split border; the definition is linked from httplib.cc.
  54. ca_store_t create_ca_store(const char *pem, size_t len);
  55. } // namespace tls
  56. } // namespace httplib
  57. #endif
  58. using namespace std;
  59. using namespace httplib;
  60. const char *HOST = "localhost";
  61. static int get_base_port() {
  62. const char *shard = getenv("GTEST_SHARD_INDEX");
  63. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  64. }
  65. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  66. // New standalone tests MUST use svr.bind_to_any_port() instead.
  67. const int PORT = get_base_port();
  68. const string LONG_QUERY_VALUE = string(25000, '@');
  69. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  70. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  71. const string TOO_LONG_QUERY_URL =
  72. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  73. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  74. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  75. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  76. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  77. return file.name == key;
  78. });
  79. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  80. return *it;
  81. #else
  82. if (it != items.end()) { return *it; }
  83. throw std::runtime_error("invalid multipart form data name error");
  84. #endif
  85. }
  86. static void read_file(const std::string &path, std::string &out) {
  87. std::ifstream fs(path, std::ios_base::binary);
  88. if (!fs) {
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return;
  91. #else
  92. throw std::runtime_error("File not found: " + path);
  93. #endif
  94. }
  95. fs.seekg(0, std::ios_base::end);
  96. auto size = fs.tellg();
  97. fs.seekg(0);
  98. out.resize(static_cast<size_t>(size));
  99. fs.read(&out[0], static_cast<std::streamsize>(size));
  100. }
  101. class UnixSocketTest : public ::testing::Test {
  102. protected:
  103. void TearDown() override { std::remove(pathname_.c_str()); }
  104. void client_GET(const std::string &addr) {
  105. httplib::Client cli{addr};
  106. cli.set_address_family(AF_UNIX);
  107. ASSERT_TRUE(cli.is_valid());
  108. const auto &result = cli.Get(pattern_);
  109. ASSERT_TRUE(result) << "error: " << result.error();
  110. const auto &resp = result.value();
  111. EXPECT_EQ(resp.status, StatusCode::OK_200);
  112. EXPECT_EQ(resp.body, content_);
  113. }
  114. static std::string make_sock_path() {
  115. const char *shard = getenv("GTEST_SHARD_INDEX");
  116. return shard ? std::string("./httplib-server-") + shard + ".sock"
  117. : "./httplib-server.sock";
  118. }
  119. const std::string pathname_{make_sock_path()};
  120. const std::string pattern_{"/hi"};
  121. const std::string content_{"Hello World!"};
  122. };
  123. TEST_F(UnixSocketTest, pathname) {
  124. httplib::Server svr;
  125. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  126. res.set_content(content_, "text/plain");
  127. });
  128. std::thread t{[&] {
  129. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  130. }};
  131. auto se = detail::scope_exit([&] {
  132. svr.stop();
  133. t.join();
  134. ASSERT_FALSE(svr.is_running());
  135. });
  136. svr.wait_until_ready();
  137. ASSERT_TRUE(svr.is_running());
  138. client_GET(pathname_);
  139. }
  140. #if defined(__linux__) || \
  141. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  142. TEST_F(UnixSocketTest, PeerPid) {
  143. httplib::Server svr;
  144. std::string remote_port_val;
  145. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  146. res.set_content(content_, "text/plain");
  147. remote_port_val = std::to_string(req.remote_port);
  148. });
  149. std::thread t{[&] {
  150. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  151. }};
  152. auto se = detail::scope_exit([&] {
  153. svr.stop();
  154. t.join();
  155. ASSERT_FALSE(svr.is_running());
  156. });
  157. svr.wait_until_ready();
  158. ASSERT_TRUE(svr.is_running());
  159. client_GET(pathname_);
  160. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  161. }
  162. #endif
  163. #ifdef __linux__
  164. TEST_F(UnixSocketTest, abstract) {
  165. constexpr char svr_path[]{"\x00httplib-server.sock"};
  166. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  167. httplib::Server svr;
  168. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. });
  171. std::thread t{[&] {
  172. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  173. }};
  174. auto se = detail::scope_exit([&] {
  175. svr.stop();
  176. t.join();
  177. ASSERT_FALSE(svr.is_running());
  178. });
  179. svr.wait_until_ready();
  180. ASSERT_TRUE(svr.is_running());
  181. client_GET(abstract_addr);
  182. }
  183. #endif
  184. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  185. httplib::Server svr;
  186. std::string received_host_header;
  187. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  188. // Capture the Host header sent by the client
  189. auto host_iter = req.headers.find("Host");
  190. if (host_iter != req.headers.end()) {
  191. received_host_header = host_iter->second;
  192. }
  193. res.set_content(content_, "text/plain");
  194. });
  195. std::thread t{[&] {
  196. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  197. }};
  198. auto se = detail::scope_exit([&] {
  199. svr.stop();
  200. t.join();
  201. ASSERT_FALSE(svr.is_running());
  202. });
  203. svr.wait_until_ready();
  204. ASSERT_TRUE(svr.is_running());
  205. // Test that Host header is automatically set to "localhost" for Unix socket
  206. // connections
  207. httplib::Client cli{pathname_};
  208. cli.set_address_family(AF_UNIX);
  209. ASSERT_TRUE(cli.is_valid());
  210. const auto &result = cli.Get(pattern_);
  211. ASSERT_TRUE(result) << "error: " << result.error();
  212. const auto &resp = result.value();
  213. EXPECT_EQ(resp.status, StatusCode::OK_200);
  214. EXPECT_EQ(resp.body, content_);
  215. // Verify that Host header was automatically set to "localhost"
  216. EXPECT_EQ(received_host_header, "localhost");
  217. }
  218. #ifndef _WIN32
  219. TEST(SocketStream, wait_writable_UNIX) {
  220. int fds[2];
  221. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  222. const auto asSocketStream = [&](socket_t fd,
  223. std::function<bool(Stream &)> func) {
  224. return detail::process_client_socket(
  225. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  226. };
  227. asSocketStream(fds[0], [&](Stream &s0) {
  228. EXPECT_EQ(s0.socket(), fds[0]);
  229. EXPECT_TRUE(s0.wait_writable());
  230. EXPECT_TRUE(s0.is_peer_alive());
  231. EXPECT_EQ(0, close(fds[1]));
  232. EXPECT_FALSE(s0.is_peer_alive());
  233. return true;
  234. });
  235. EXPECT_EQ(0, close(fds[0]));
  236. }
  237. TEST(SocketStream, wait_writable_INET) {
  238. sockaddr_in addr;
  239. memset(&addr, 0, sizeof(addr));
  240. addr.sin_family = AF_INET;
  241. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  242. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  243. int disconnected_svr_sock = -1;
  244. std::thread svr{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, listen(s, 1));
  249. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  250. ASSERT_EQ(0, close(s));
  251. }};
  252. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  253. std::thread cli{[&] {
  254. const int s = socket(AF_INET, SOCK_STREAM, 0);
  255. ASSERT_LE(0, s);
  256. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  257. ASSERT_EQ(0, close(s));
  258. }};
  259. cli.join();
  260. svr.join();
  261. ASSERT_NE(disconnected_svr_sock, -1);
  262. const auto asSocketStream = [&](socket_t fd,
  263. std::function<bool(Stream &)> func) {
  264. return detail::process_client_socket(
  265. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  266. };
  267. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  268. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  269. // wait_writable() returns true because select_write() only checks if the
  270. // send buffer has space. Peer disconnection is detected later by send().
  271. EXPECT_TRUE(ss.wait_writable());
  272. return true;
  273. });
  274. ASSERT_EQ(0, close(disconnected_svr_sock));
  275. }
  276. #endif // #ifndef _WIN32
  277. TEST(SetSocketOptTest, TcpNoDelay) {
  278. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  279. ASSERT_NE(sock, INVALID_SOCKET);
  280. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  281. int val = 0;
  282. socklen_t len = sizeof(val);
  283. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  284. reinterpret_cast<char *>(&val), &len));
  285. EXPECT_NE(val, 0);
  286. detail::close_socket(sock);
  287. }
  288. TEST(ClientTest, MoveConstructible) {
  289. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  290. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  291. }
  292. TEST(ClientTest, MoveAssignable) {
  293. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  294. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  295. }
  296. #ifdef _WIN32
  297. TEST(StartupTest, WSAStartup) {
  298. WSADATA wsaData;
  299. int ret = WSAStartup(0x0002, &wsaData);
  300. ASSERT_EQ(0, ret);
  301. }
  302. #endif
  303. TEST(DecodePathTest, PercentCharacter) {
  304. EXPECT_EQ(
  305. decode_path_component(
  306. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  307. U8("descrip=Gastos áéíóúñÑ 6"));
  308. }
  309. TEST(DecodePathTest, PercentCharacterNUL) {
  310. string expected;
  311. expected.push_back('x');
  312. expected.push_back('\0');
  313. expected.push_back('x');
  314. EXPECT_EQ(decode_path_component("x%00x"), expected);
  315. }
  316. TEST(DecodePathTest, UnicodeEncoding) {
  317. // %u0041 = 'A' (1-byte UTF-8)
  318. EXPECT_EQ("A", decode_path_component("%u0041"));
  319. // %u00E9 = 'é' (2-byte UTF-8)
  320. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  321. // %u3042 = 'あ' (3-byte UTF-8)
  322. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  323. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  324. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  325. // %uD800 = surrogate (invalid, silently dropped)
  326. EXPECT_EQ("", decode_path_component("%uD800"));
  327. }
  328. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  329. // A sign or whitespace inside the two-character escape window must not be
  330. // accepted as a valid percent-encoding; the sequence is passed through
  331. // literally, matching decode_uri_component / decode_path_component.
  332. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  333. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  334. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  335. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  336. // Well-formed escapes still decode.
  337. EXPECT_EQ("-", decode_query_component("%2D", false));
  338. EXPECT_EQ("A", decode_query_component("%41", false));
  339. }
  340. TEST(SanitizeFilenameTest, VariousPatterns) {
  341. // Path traversal
  342. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  343. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  344. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  345. // Normal and edge cases
  346. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  347. EXPECT_EQ("filename.txt",
  348. httplib::sanitize_filename("/path/to/filename.txt"));
  349. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  350. EXPECT_EQ("", httplib::sanitize_filename(".."));
  351. EXPECT_EQ("", httplib::sanitize_filename(""));
  352. // Null bytes stripped
  353. EXPECT_EQ("safe.txt",
  354. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  355. // Whitespace-only rejected
  356. EXPECT_EQ("", httplib::sanitize_filename(" "));
  357. }
  358. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  359. string unescapedCharacters = "-_.!~*'()";
  360. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  361. }
  362. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  363. string reservedCharacters = ";,/?:@&=+$";
  364. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  365. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  366. }
  367. TEST(ClientQueryOrder, PreserveOrder) {
  368. // This test reproduces Issue #2259: client may reorder query parameters
  369. // when sending a GET request. The expected behavior is that the client
  370. // preserves the original query string order when the caller supplied it
  371. // as part of the path.
  372. Server svr;
  373. svr.Get("/", [&](const Request &req, Response &res) {
  374. // Echo back the raw target so the test can assert ordering
  375. res.set_content(req.target, "text/plain");
  376. });
  377. std::thread t{[&] { svr.listen(HOST, PORT); }};
  378. auto se = detail::scope_exit([&] {
  379. svr.stop();
  380. t.join();
  381. ASSERT_FALSE(svr.is_running());
  382. });
  383. svr.wait_until_ready();
  384. Client cli(HOST, PORT);
  385. ASSERT_TRUE(cli.is_valid());
  386. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  387. auto res = cli.Get(original);
  388. ASSERT_TRUE(res);
  389. // Expect the echoed target to exactly match the original path (order
  390. // preserved)
  391. EXPECT_EQ(res->body, original);
  392. }
  393. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  394. string chineseCharacters = U8("中国語");
  395. string russianCharacters = U8("дом");
  396. string brazilianCharacters = U8("óculos");
  397. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  398. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  399. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  400. "%D0%B4%D0%BE%D0%BC");
  401. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  402. }
  403. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  404. string unescapedCharacters = "-_.!~*'()";
  405. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  406. }
  407. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  408. string reservedCharacters = ";,/?:@&=+$";
  409. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  410. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  411. }
  412. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  413. string chineseCharacters = U8("中国語");
  414. string russianCharacters = U8("дом");
  415. string brazilianCharacters = U8("óculos");
  416. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  417. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  418. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  419. "%D0%B4%D0%BE%D0%BC");
  420. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  421. }
  422. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  423. // Issue #2082 use case: encoding path component with ampersand
  424. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  425. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  426. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  427. }
  428. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  429. string unescapedCharacters = "-_.!~*'()";
  430. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  431. }
  432. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  433. string reservedCharacters = ";,/?:@&=+$#";
  434. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  435. }
  436. TEST(EncodeUriTest, TestUTF8Characters) {
  437. string chineseCharacters = U8("中国語");
  438. string russianCharacters = U8("дом");
  439. string brazilianCharacters = U8("óculos");
  440. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  441. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  442. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  443. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  444. }
  445. TEST(EncodeUriTest, TestCompleteUri) {
  446. string uri =
  447. "https://example.com/path/to/resource?query=value&param=test#fragment";
  448. EXPECT_EQ(
  449. httplib::encode_uri(uri),
  450. "https://example.com/path/to/resource?query=value&param=test#fragment");
  451. }
  452. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  453. string uri =
  454. "https://example.com/path with spaces/file name.html?q=hello world";
  455. EXPECT_EQ(httplib::encode_uri(uri),
  456. "https://example.com/path%20with%20spaces/"
  457. "file%20name.html?q=hello%20world");
  458. }
  459. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  461. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  462. }
  463. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'()";
  465. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  466. }
  467. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  476. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  477. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  478. "Piri Tommy Villiers - on & on");
  479. }
  480. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  481. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  482. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  483. }
  484. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  485. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  486. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  487. }
  488. TEST(DecodeUriTest, TestUTF8Characters) {
  489. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  490. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  491. string encodedBrazilian = "%C3%B3culos";
  492. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  493. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  494. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  495. }
  496. TEST(DecodeUriTest, TestCompleteUri) {
  497. string encodedUri = "https://example.com/path%20with%20spaces/"
  498. "file%20name.html?q=hello%20world";
  499. EXPECT_EQ(
  500. httplib::decode_uri(encodedUri),
  501. "https://example.com/path with spaces/file name.html?q=hello world");
  502. }
  503. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  504. string original =
  505. "https://example.com/path with spaces/file name.html?q=hello world";
  506. string encoded = httplib::encode_uri(original);
  507. string decoded = httplib::decode_uri(encoded);
  508. EXPECT_EQ(decoded, original);
  509. }
  510. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  511. string original = "Piri Tommy Villiers - on & on";
  512. string encoded = httplib::encode_uri_component(original);
  513. string decoded = httplib::decode_uri_component(encoded);
  514. EXPECT_EQ(decoded, original);
  515. }
  516. TEST(TrimTests, TrimStringTests) {
  517. EXPECT_EQ("abc", detail::trim_copy("abc"));
  518. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  519. EXPECT_TRUE(detail::trim_copy("").empty());
  520. }
  521. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  522. // Simple case without quality values
  523. std::vector<std::string> result1;
  524. EXPECT_TRUE(detail::parse_accept_header(
  525. "text/html,application/json,text/plain", result1));
  526. EXPECT_EQ(result1.size(), 3U);
  527. EXPECT_EQ(result1[0], "text/html");
  528. EXPECT_EQ(result1[1], "application/json");
  529. EXPECT_EQ(result1[2], "text/plain");
  530. // With quality values
  531. std::vector<std::string> result2;
  532. EXPECT_TRUE(detail::parse_accept_header(
  533. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  534. EXPECT_EQ(result2.size(), 3U);
  535. EXPECT_EQ(result2[0], "application/json"); // highest q value
  536. EXPECT_EQ(result2[1], "text/html");
  537. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  538. }
  539. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  540. // Mixed with and without quality values
  541. std::vector<std::string> result;
  542. EXPECT_TRUE(detail::parse_accept_header(
  543. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  544. EXPECT_EQ(result.size(), 3U);
  545. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  546. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  547. EXPECT_EQ(result[2], "application/json"); // q=0.5
  548. }
  549. TEST(ParseAcceptHeaderTest, EdgeCases) {
  550. // Empty header
  551. std::vector<std::string> empty_result;
  552. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  553. EXPECT_TRUE(empty_result.empty());
  554. // Single type
  555. std::vector<std::string> single_result;
  556. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  557. EXPECT_EQ(single_result.size(), 1U);
  558. EXPECT_EQ(single_result[0], "application/json");
  559. // Wildcard types
  560. std::vector<std::string> wildcard_result;
  561. EXPECT_TRUE(detail::parse_accept_header(
  562. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  563. EXPECT_EQ(wildcard_result.size(), 3U);
  564. EXPECT_EQ(wildcard_result[0], "application/json");
  565. EXPECT_EQ(wildcard_result[1], "text/*");
  566. EXPECT_EQ(wildcard_result[2], "*/*");
  567. }
  568. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  569. // Common browser Accept header
  570. std::vector<std::string> browser_result;
  571. EXPECT_TRUE(
  572. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  573. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  574. browser_result));
  575. EXPECT_EQ(browser_result.size(), 6U);
  576. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  577. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  578. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  579. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  580. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  581. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  582. // API client header
  583. std::vector<std::string> api_result;
  584. EXPECT_TRUE(detail::parse_accept_header(
  585. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  586. api_result));
  587. EXPECT_EQ(api_result.size(), 3U);
  588. EXPECT_EQ(api_result[0], "application/json");
  589. EXPECT_EQ(api_result[1], "application/xml");
  590. EXPECT_EQ(api_result[2], "text/plain");
  591. }
  592. TEST(ParseAcceptHeaderTest, SpecialCases) {
  593. // Quality value with 3 decimal places
  594. std::vector<std::string> decimal_result;
  595. EXPECT_TRUE(detail::parse_accept_header(
  596. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  597. EXPECT_EQ(decimal_result.size(), 2U);
  598. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  599. EXPECT_EQ(decimal_result[1], "text/html");
  600. // Zero quality (should still be included but with lowest priority)
  601. std::vector<std::string> zero_q_result;
  602. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  603. zero_q_result));
  604. EXPECT_EQ(zero_q_result.size(), 2U);
  605. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  606. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  607. // No spaces around commas
  608. std::vector<std::string> no_space_result;
  609. EXPECT_TRUE(detail::parse_accept_header(
  610. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  611. no_space_result));
  612. EXPECT_EQ(no_space_result.size(), 3U);
  613. EXPECT_EQ(no_space_result[0], "text/html");
  614. EXPECT_EQ(no_space_result[1], "application/json");
  615. EXPECT_EQ(no_space_result[2], "text/plain");
  616. }
  617. TEST(ParseAcceptHeaderTest, InvalidCases) {
  618. std::vector<std::string> result;
  619. // Invalid quality value (> 1.0)
  620. EXPECT_FALSE(
  621. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  622. // Invalid quality value (< 0.0)
  623. EXPECT_FALSE(
  624. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  625. // Invalid quality value (not a number)
  626. EXPECT_FALSE(detail::parse_accept_header(
  627. "text/html;q=invalid,application/json", result));
  628. // Empty quality value
  629. EXPECT_FALSE(
  630. detail::parse_accept_header("text/html;q=,application/json", result));
  631. // Invalid media type format (no slash and not wildcard)
  632. EXPECT_FALSE(
  633. detail::parse_accept_header("invalidtype,application/json", result));
  634. // Empty media type
  635. result.clear();
  636. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  637. // Only commas
  638. result.clear();
  639. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  640. // Valid cases should still work
  641. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  642. EXPECT_EQ(result.size(), 1U);
  643. EXPECT_EQ(result[0], "*/*");
  644. EXPECT_TRUE(detail::parse_accept_header("*", result));
  645. EXPECT_EQ(result.size(), 1U);
  646. EXPECT_EQ(result[0], "*");
  647. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  648. EXPECT_EQ(result.size(), 1U);
  649. EXPECT_EQ(result[0], "text/*");
  650. }
  651. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  652. Server svr;
  653. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  654. EXPECT_EQ(req.accept_content_types.size(), 3U);
  655. EXPECT_EQ(req.accept_content_types[0], "application/json");
  656. EXPECT_EQ(req.accept_content_types[1], "text/html");
  657. EXPECT_EQ(req.accept_content_types[2], "*/*");
  658. res.set_content("ok", "text/plain");
  659. });
  660. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  661. EXPECT_TRUE(false);
  662. res.set_content("bad request", "text/plain");
  663. });
  664. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  665. auto se = detail::scope_exit([&] {
  666. svr.stop();
  667. listen_thread.join();
  668. ASSERT_FALSE(svr.is_running());
  669. });
  670. svr.wait_until_ready();
  671. Client cli("localhost", PORT);
  672. {
  673. auto res =
  674. cli.Get("/accept_ok",
  675. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  676. ASSERT_TRUE(res);
  677. EXPECT_EQ(StatusCode::OK_200, res->status);
  678. }
  679. {
  680. auto res = cli.Get("/accept_bad_request",
  681. {{"Accept", "text/html;q=abc,application/json"}});
  682. ASSERT_TRUE(res);
  683. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  684. }
  685. }
  686. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  687. Server svr;
  688. svr.Get("/", [](const Request & /*req*/, Response &res) {
  689. res.set_content("ok", "text/plain");
  690. });
  691. std::atomic<int> start_count{0};
  692. std::atomic<bool> running_when_called{false};
  693. svr.set_start_handler([&]() {
  694. running_when_called = svr.is_running();
  695. start_count++;
  696. });
  697. auto port = svr.bind_to_any_port(HOST);
  698. std::thread t([&]() { svr.listen_after_bind(); });
  699. auto se = detail::scope_exit([&] {
  700. svr.stop();
  701. t.join();
  702. ASSERT_FALSE(svr.is_running());
  703. });
  704. svr.wait_until_ready();
  705. // A successful request proves the accept loop is running, which the start
  706. // handler precedes; so by now the handler must have run exactly once.
  707. Client cli(HOST, port);
  708. cli.set_connection_timeout(std::chrono::seconds(5));
  709. auto res = cli.Get("/");
  710. ASSERT_TRUE(res);
  711. EXPECT_EQ(StatusCode::OK_200, res->status);
  712. EXPECT_EQ(1, start_count.load());
  713. EXPECT_TRUE(running_when_called.load());
  714. }
  715. TEST(DivideTest, DivideStringTests) {
  716. auto divide = [](const std::string &str, char d) {
  717. std::string lhs;
  718. std::string rhs;
  719. detail::divide(str, d,
  720. [&](const char *lhs_data, std::size_t lhs_size,
  721. const char *rhs_data, std::size_t rhs_size) {
  722. lhs.assign(lhs_data, lhs_size);
  723. rhs.assign(rhs_data, rhs_size);
  724. });
  725. return std::make_pair(std::move(lhs), std::move(rhs));
  726. };
  727. {
  728. const auto res = divide("", '=');
  729. EXPECT_EQ(res.first, "");
  730. EXPECT_EQ(res.second, "");
  731. }
  732. {
  733. const auto res = divide("=", '=');
  734. EXPECT_EQ(res.first, "");
  735. EXPECT_EQ(res.second, "");
  736. }
  737. {
  738. const auto res = divide(" ", '=');
  739. EXPECT_EQ(res.first, " ");
  740. EXPECT_EQ(res.second, "");
  741. }
  742. {
  743. const auto res = divide("a", '=');
  744. EXPECT_EQ(res.first, "a");
  745. EXPECT_EQ(res.second, "");
  746. }
  747. {
  748. const auto res = divide("a=", '=');
  749. EXPECT_EQ(res.first, "a");
  750. EXPECT_EQ(res.second, "");
  751. }
  752. {
  753. const auto res = divide("=b", '=');
  754. EXPECT_EQ(res.first, "");
  755. EXPECT_EQ(res.second, "b");
  756. }
  757. {
  758. const auto res = divide("a=b", '=');
  759. EXPECT_EQ(res.first, "a");
  760. EXPECT_EQ(res.second, "b");
  761. }
  762. {
  763. const auto res = divide("a=b=", '=');
  764. EXPECT_EQ(res.first, "a");
  765. EXPECT_EQ(res.second, "b=");
  766. }
  767. {
  768. const auto res = divide("a=b=c", '=');
  769. EXPECT_EQ(res.first, "a");
  770. EXPECT_EQ(res.second, "b=c");
  771. }
  772. }
  773. TEST(SplitTest, ParseQueryString) {
  774. string s = "key1=val1&key2=val2&key3=val3";
  775. Params dic;
  776. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  777. [&](const char *b, const char *e) {
  778. string key, val;
  779. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  780. if (key.empty()) {
  781. key.assign(b2, e2);
  782. } else {
  783. val.assign(b2, e2);
  784. }
  785. });
  786. dic.emplace(key, val);
  787. });
  788. EXPECT_EQ("val1", dic.find("key1")->second);
  789. EXPECT_EQ("val2", dic.find("key2")->second);
  790. EXPECT_EQ("val3", dic.find("key3")->second);
  791. }
  792. TEST(SplitTest, ParseInvalidQueryTests) {
  793. {
  794. string s = " ";
  795. Params dict;
  796. detail::parse_query_text(s, dict);
  797. EXPECT_TRUE(dict.empty());
  798. }
  799. {
  800. string s = " = =";
  801. Params dict;
  802. detail::parse_query_text(s, dict);
  803. EXPECT_TRUE(dict.empty());
  804. }
  805. }
  806. TEST(ParseQueryTest, ParseQueryString) {
  807. {
  808. std::string s = "key1=val1&key2=val2&key3=val3";
  809. Params dic;
  810. detail::parse_query_text(s, dic);
  811. EXPECT_EQ("val1", dic.find("key1")->second);
  812. EXPECT_EQ("val2", dic.find("key2")->second);
  813. EXPECT_EQ("val3", dic.find("key3")->second);
  814. }
  815. {
  816. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  817. Params dic;
  818. detail::parse_query_text(s, dic);
  819. EXPECT_EQ("", dic.find("key1")->second);
  820. EXPECT_EQ("val1", dic.find("key2")->second);
  821. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  822. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  823. }
  824. }
  825. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  826. Params dic;
  827. EXPECT_EQ(detail::params_to_query_str(dic), "");
  828. dic.emplace("key1", "val1");
  829. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  830. dic.emplace("key2", "val2");
  831. dic.emplace("key3", "val3");
  832. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  833. }
  834. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  835. string content_type = "multipart/form-data; boundary=something";
  836. string boundary;
  837. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  838. EXPECT_TRUE(ret);
  839. EXPECT_EQ(boundary, "something");
  840. }
  841. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  842. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  843. string boundary;
  844. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  845. EXPECT_TRUE(ret);
  846. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  847. }
  848. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  849. string content_type =
  850. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  851. string boundary;
  852. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  853. EXPECT_TRUE(ret);
  854. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  855. }
  856. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  857. string content_type =
  858. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  859. string boundary;
  860. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  861. EXPECT_TRUE(ret);
  862. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  863. }
  864. TEST(GetHeaderValueTest, DefaultValue) {
  865. Headers headers = {{"Dummy", "Dummy"}};
  866. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  867. EXPECT_STREQ("text/plain", val);
  868. }
  869. TEST(GetHeaderValueTest, DefaultValueInt) {
  870. Headers headers = {{"Dummy", "Dummy"}};
  871. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  872. EXPECT_EQ(100ull, val);
  873. }
  874. TEST(GetHeaderValueTest, RegularValue) {
  875. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  876. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  877. EXPECT_STREQ("text/html", val);
  878. }
  879. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  880. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  881. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  882. EXPECT_STREQ("text/html", val);
  883. }
  884. TEST(GetHeaderValueTest, SetContent) {
  885. Response res;
  886. res.set_content("html", "text/html");
  887. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  888. res.set_content("text", "text/plain");
  889. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  890. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  891. }
  892. TEST(GetHeaderValueTest, RegularValueInt) {
  893. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  894. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  895. EXPECT_EQ(100ull, val);
  896. }
  897. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  898. Headers headers = {{"Content-Length", "x"}};
  899. auto is_invalid_value = false;
  900. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  901. is_invalid_value);
  902. EXPECT_EQ(0ull, val);
  903. EXPECT_TRUE(is_invalid_value);
  904. }
  905. TEST(GetHeaderValueTest, Range) {
  906. {
  907. Headers headers = {make_range_header({{1, -1}})};
  908. auto val = detail::get_header_value(headers, "Range", 0, 0);
  909. EXPECT_STREQ("bytes=1-", val);
  910. }
  911. {
  912. Headers headers = {make_range_header({{-1, 1}})};
  913. auto val = detail::get_header_value(headers, "Range", 0, 0);
  914. EXPECT_STREQ("bytes=-1", val);
  915. }
  916. {
  917. Headers headers = {make_range_header({{1, 10}})};
  918. auto val = detail::get_header_value(headers, "Range", 0, 0);
  919. EXPECT_STREQ("bytes=1-10", val);
  920. }
  921. {
  922. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  923. auto val = detail::get_header_value(headers, "Range", 0, 0);
  924. EXPECT_STREQ("bytes=1-10, 100-", val);
  925. }
  926. {
  927. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  928. auto val = detail::get_header_value(headers, "Range", 0, 0);
  929. EXPECT_STREQ("bytes=1-10, 100-200", val);
  930. }
  931. {
  932. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  933. auto val = detail::get_header_value(headers, "Range", 0, 0);
  934. EXPECT_STREQ("bytes=0-0, -1", val);
  935. }
  936. }
  937. TEST(ParseHeaderValueTest, Range) {
  938. {
  939. Ranges ranges;
  940. auto ret = detail::parse_range_header("bytes=1-", ranges);
  941. EXPECT_TRUE(ret);
  942. EXPECT_EQ(1u, ranges.size());
  943. EXPECT_EQ(1u, ranges[0].first);
  944. EXPECT_EQ(-1, ranges[0].second);
  945. }
  946. {
  947. Ranges ranges;
  948. auto ret = detail::parse_range_header("bytes=-1", ranges);
  949. EXPECT_TRUE(ret);
  950. EXPECT_EQ(1u, ranges.size());
  951. EXPECT_EQ(-1, ranges[0].first);
  952. EXPECT_EQ(1u, ranges[0].second);
  953. }
  954. {
  955. Ranges ranges;
  956. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  957. EXPECT_TRUE(ret);
  958. EXPECT_EQ(1u, ranges.size());
  959. EXPECT_EQ(1u, ranges[0].first);
  960. EXPECT_EQ(10u, ranges[0].second);
  961. }
  962. {
  963. Ranges ranges;
  964. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  965. EXPECT_FALSE(ret);
  966. }
  967. {
  968. Ranges ranges;
  969. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  970. EXPECT_TRUE(ret);
  971. EXPECT_EQ(2u, ranges.size());
  972. EXPECT_EQ(1u, ranges[0].first);
  973. EXPECT_EQ(10u, ranges[0].second);
  974. EXPECT_EQ(100u, ranges[1].first);
  975. EXPECT_EQ(-1, ranges[1].second);
  976. }
  977. {
  978. Ranges ranges;
  979. auto ret =
  980. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  981. EXPECT_TRUE(ret);
  982. EXPECT_EQ(3u, ranges.size());
  983. EXPECT_EQ(1u, ranges[0].first);
  984. EXPECT_EQ(10u, ranges[0].second);
  985. EXPECT_EQ(100u, ranges[1].first);
  986. EXPECT_EQ(200u, ranges[1].second);
  987. EXPECT_EQ(300u, ranges[2].first);
  988. EXPECT_EQ(400u, ranges[2].second);
  989. }
  990. {
  991. Ranges ranges;
  992. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  993. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  994. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  995. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  996. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  997. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  998. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  999. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1000. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1001. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1002. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1003. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1004. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1005. EXPECT_TRUE(ranges.empty());
  1006. }
  1007. }
  1008. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1009. Request req;
  1010. req.set_header("Accept-Encoding", "gzip");
  1011. Response res;
  1012. res.set_header("Content-Type", "text/plain");
  1013. auto ret = detail::encoding_type(req, res);
  1014. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1015. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1016. #else
  1017. EXPECT_TRUE(ret == detail::EncodingType::None);
  1018. #endif
  1019. }
  1020. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1021. Request req;
  1022. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1023. Response res;
  1024. res.set_header("Content-Type", "text/plain");
  1025. auto ret = detail::encoding_type(req, res);
  1026. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1027. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1028. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1029. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1030. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1031. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1032. #else
  1033. EXPECT_TRUE(ret == detail::EncodingType::None);
  1034. #endif
  1035. }
  1036. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1037. Request req;
  1038. req.set_header("Accept-Encoding",
  1039. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1040. Response res;
  1041. res.set_header("Content-Type", "text/plain");
  1042. auto ret = detail::encoding_type(req, res);
  1043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1044. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1045. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1049. #else
  1050. EXPECT_TRUE(ret == detail::EncodingType::None);
  1051. #endif
  1052. }
  1053. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1054. // All supported encodings rejected with q=0 should return None
  1055. Request req;
  1056. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1057. Response res;
  1058. res.set_header("Content-Type", "text/plain");
  1059. auto ret = detail::encoding_type(req, res);
  1060. EXPECT_TRUE(ret == detail::EncodingType::None);
  1061. }
  1062. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1063. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1064. Request req;
  1065. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1066. Response res;
  1067. res.set_header("Content-Type", "text/plain");
  1068. auto ret = detail::encoding_type(req, res);
  1069. EXPECT_TRUE(ret == detail::EncodingType::None);
  1070. }
  1071. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1072. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1073. Request req;
  1074. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1075. Response res;
  1076. res.set_header("Content-Type", "text/plain");
  1077. auto ret = detail::encoding_type(req, res);
  1078. EXPECT_TRUE(ret == detail::EncodingType::None);
  1079. }
  1080. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1081. // RFC 7231: Accept-Encoding values are case-insensitive
  1082. Request req;
  1083. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1084. Response res;
  1085. res.set_header("Content-Type", "text/plain");
  1086. auto ret = detail::encoding_type(req, res);
  1087. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1088. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1089. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1090. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1091. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1092. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1093. #else
  1094. EXPECT_TRUE(ret == detail::EncodingType::None);
  1095. #endif
  1096. }
  1097. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1098. // q value should determine priority, not hardcoded order
  1099. Request req;
  1100. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1101. Response res;
  1102. res.set_header("Content-Type", "text/plain");
  1103. auto ret = detail::encoding_type(req, res);
  1104. // gzip has highest q=1.0, so it should be selected even though
  1105. // br and zstd are also supported
  1106. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1107. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1108. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1109. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1110. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1111. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1112. #else
  1113. EXPECT_TRUE(ret == detail::EncodingType::None);
  1114. #endif
  1115. }
  1116. TEST(BufferStreamTest, read) {
  1117. detail::BufferStream strm1;
  1118. Stream &strm = strm1;
  1119. EXPECT_EQ(5, strm.write("hello"));
  1120. char buf[512];
  1121. EXPECT_EQ(2, strm.read(buf, 2));
  1122. EXPECT_EQ('h', buf[0]);
  1123. EXPECT_EQ('e', buf[1]);
  1124. EXPECT_EQ(2, strm.read(buf, 2));
  1125. EXPECT_EQ('l', buf[0]);
  1126. EXPECT_EQ('l', buf[1]);
  1127. EXPECT_EQ(1, strm.read(buf, 1));
  1128. EXPECT_EQ('o', buf[0]);
  1129. EXPECT_EQ(0, strm.read(buf, 1));
  1130. }
  1131. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1132. auto host = "www.httpwatch.com";
  1133. auto ip = hosted_at(host);
  1134. EXPECT_EQ("23.96.13.243", ip);
  1135. std::vector<std::string> addrs;
  1136. hosted_at(host, addrs);
  1137. EXPECT_EQ(1u, addrs.size());
  1138. }
  1139. #if 0 // It depends on each test environment...
  1140. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1141. auto host = "www.youtube.com";
  1142. std::vector<std::string> addrs;
  1143. hosted_at(host, addrs);
  1144. EXPECT_EQ(20u, addrs.size());
  1145. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1146. EXPECT_TRUE(it != addrs.end());
  1147. }
  1148. #endif
  1149. class ChunkedEncodingTest : public ::testing::Test {
  1150. protected:
  1151. ChunkedEncodingTest()
  1152. : cli_(HOST, PORT)
  1153. #ifdef CPPHTTPLIB_SSL_ENABLED
  1154. ,
  1155. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1156. #endif
  1157. {
  1158. cli_.set_connection_timeout(2);
  1159. #ifdef CPPHTTPLIB_SSL_ENABLED
  1160. cli_.enable_server_certificate_verification(false);
  1161. #endif
  1162. }
  1163. virtual void SetUp() {
  1164. read_file("./image.jpg", image_data_);
  1165. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1166. res.set_content("Hello World!", "text/plain");
  1167. });
  1168. svr_.Get(
  1169. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1170. res.set_chunked_content_provider(
  1171. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1172. size_t remaining = image_data_.size() - offset;
  1173. if (remaining == 0) {
  1174. sink.done();
  1175. } else {
  1176. constexpr size_t CHUNK_SIZE = 1024;
  1177. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1178. sink.write(&image_data_[offset], send_size);
  1179. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1180. }
  1181. return true;
  1182. });
  1183. });
  1184. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1185. svr_.wait_until_ready();
  1186. }
  1187. virtual void TearDown() {
  1188. svr_.stop();
  1189. if (!request_threads_.empty()) {
  1190. std::this_thread::sleep_for(std::chrono::seconds(1));
  1191. for (auto &t : request_threads_) {
  1192. t.join();
  1193. }
  1194. }
  1195. t_.join();
  1196. }
  1197. #ifdef CPPHTTPLIB_SSL_ENABLED
  1198. SSLClient cli_;
  1199. SSLServer svr_;
  1200. #else
  1201. Client cli_;
  1202. Server svr_;
  1203. #endif
  1204. thread t_;
  1205. std::vector<thread> request_threads_;
  1206. std::string image_data_;
  1207. };
  1208. TEST_F(ChunkedEncodingTest, NormalGet) {
  1209. auto res = cli_.Get("/chunked");
  1210. ASSERT_TRUE(res);
  1211. std::string out;
  1212. read_file("./image.jpg", out);
  1213. EXPECT_EQ(StatusCode::OK_200, res->status);
  1214. EXPECT_EQ(out, res->body);
  1215. }
  1216. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1217. std::string body;
  1218. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1219. body.append(data, data_length);
  1220. return true;
  1221. });
  1222. ASSERT_TRUE(res);
  1223. std::string out;
  1224. read_file("./image.jpg", out);
  1225. EXPECT_EQ(StatusCode::OK_200, res->status);
  1226. EXPECT_EQ(out, body);
  1227. }
  1228. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1229. std::string body;
  1230. auto res = cli_.Get(
  1231. "/chunked",
  1232. [&](const Response &response) {
  1233. EXPECT_EQ(StatusCode::OK_200, response.status);
  1234. return true;
  1235. },
  1236. [&](const char *data, size_t data_length) {
  1237. body.append(data, data_length);
  1238. return true;
  1239. });
  1240. ASSERT_TRUE(res);
  1241. std::string out;
  1242. read_file("./image.jpg", out);
  1243. EXPECT_EQ(StatusCode::OK_200, res->status);
  1244. EXPECT_EQ(out, body);
  1245. }
  1246. TEST(RangeTest, FromHTTPBin_Online) {
  1247. auto host = "httpbingo.org";
  1248. auto path = std::string{"/range/32"};
  1249. #ifdef CPPHTTPLIB_SSL_ENABLED
  1250. auto port = 443;
  1251. SSLClient cli(host, port);
  1252. #else
  1253. auto port = 80;
  1254. Client cli(host, port);
  1255. #endif
  1256. cli.set_connection_timeout(5);
  1257. {
  1258. auto res = cli.Get(path);
  1259. ASSERT_TRUE(res);
  1260. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1261. EXPECT_EQ(StatusCode::OK_200, res->status);
  1262. }
  1263. {
  1264. Headers headers = {make_range_header({{1, -1}})};
  1265. auto res = cli.Get(path, headers);
  1266. ASSERT_TRUE(res);
  1267. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1268. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1269. }
  1270. {
  1271. Headers headers = {make_range_header({{1, 10}})};
  1272. auto res = cli.Get(path, headers);
  1273. ASSERT_TRUE(res);
  1274. EXPECT_EQ("bcdefghijk", res->body);
  1275. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1276. }
  1277. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1278. // entire resource, while the original httpbin returned 200. Both are
  1279. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1280. {
  1281. Headers headers = {make_range_header({{0, 31}})};
  1282. auto res = cli.Get(path, headers);
  1283. ASSERT_TRUE(res);
  1284. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1285. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1286. res->status == StatusCode::PartialContent_206);
  1287. }
  1288. {
  1289. Headers headers = {make_range_header({{0, -1}})};
  1290. auto res = cli.Get(path, headers);
  1291. ASSERT_TRUE(res);
  1292. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1293. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1294. res->status == StatusCode::PartialContent_206);
  1295. }
  1296. // go-httpbin returns 206 with clamped range for over-range requests,
  1297. // while the original httpbin returned 416. Both behaviors are observed
  1298. // in real servers, so we only verify the request succeeds.
  1299. {
  1300. Headers headers = {make_range_header({{0, 32}})};
  1301. auto res = cli.Get(path, headers);
  1302. ASSERT_TRUE(res);
  1303. }
  1304. }
  1305. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1306. auto host = "unresolvableaddress.local";
  1307. auto path = std::string{"/"};
  1308. #ifdef CPPHTTPLIB_SSL_ENABLED
  1309. auto port = 443;
  1310. SSLClient cli(host, port);
  1311. #else
  1312. auto port = 80;
  1313. Client cli(host, port);
  1314. #endif
  1315. cli.set_connection_timeout(1);
  1316. {
  1317. auto res = cli.Get(path);
  1318. ASSERT_FALSE(res);
  1319. }
  1320. std::this_thread::sleep_for(std::chrono::seconds(8));
  1321. }
  1322. #if defined(__linux__) && defined(__GLIBC__) && \
  1323. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1324. // Forward declaration: in split builds split.py strips `inline` and moves the
  1325. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1326. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1327. // against the symbol in both header-only and split builds.
  1328. namespace httplib {
  1329. namespace detail {
  1330. int getaddrinfo_with_timeout(const char *node, const char *service,
  1331. const struct addrinfo *hints,
  1332. struct addrinfo **res, time_t timeout_sec);
  1333. } // namespace detail
  1334. } // namespace httplib
  1335. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1336. //
  1337. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1338. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1339. // gai_suspend() call hits the connection timeout the function calls
  1340. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1341. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1342. // still alive and still references the now-destroyed stack frame.
  1343. //
  1344. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1345. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1346. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1347. // and runs them in a container.
  1348. namespace {
  1349. bool should_run_issue_2431_tests() {
  1350. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1351. return v && *v && std::string(v) != "0";
  1352. }
  1353. std::string unique_unresolvable_host(int n) {
  1354. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1355. // glibc still asks the configured nameserver — which is exactly the path
  1356. // we want to exercise. A unique label per call avoids the resolver cache.
  1357. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1358. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1359. std::to_string(n) + ".invalid";
  1360. }
  1361. } // namespace
  1362. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1363. if (!should_run_issue_2431_tests()) {
  1364. GTEST_SKIP()
  1365. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1366. }
  1367. for (int i = 0; i < 8; ++i) {
  1368. struct addrinfo hints;
  1369. memset(&hints, 0, sizeof(hints));
  1370. hints.ai_family = AF_UNSPEC;
  1371. hints.ai_socktype = SOCK_STREAM;
  1372. auto host = unique_unresolvable_host(i);
  1373. struct addrinfo *result = nullptr;
  1374. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1375. &result, /*timeout_sec=*/1);
  1376. if (rc == 0 && result) { freeaddrinfo(result); }
  1377. }
  1378. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1379. // stack region they still believe holds their gaicb.
  1380. std::this_thread::sleep_for(std::chrono::seconds(3));
  1381. }
  1382. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1383. if (!should_run_issue_2431_tests()) {
  1384. GTEST_SKIP()
  1385. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1386. }
  1387. std::atomic<bool> stop{false};
  1388. std::vector<std::thread> threads;
  1389. for (int t = 0; t < 8; ++t) {
  1390. threads.emplace_back([t, &stop] {
  1391. int i = 0;
  1392. while (!stop.load(std::memory_order_relaxed)) {
  1393. struct addrinfo hints;
  1394. memset(&hints, 0, sizeof(hints));
  1395. hints.ai_family = AF_UNSPEC;
  1396. hints.ai_socktype = SOCK_STREAM;
  1397. auto host = unique_unresolvable_host(t * 100000 + i++);
  1398. struct addrinfo *result = nullptr;
  1399. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1400. &result, /*timeout_sec=*/1);
  1401. if (rc == 0 && result) { freeaddrinfo(result); }
  1402. }
  1403. });
  1404. }
  1405. std::this_thread::sleep_for(std::chrono::seconds(8));
  1406. stop.store(true, std::memory_order_relaxed);
  1407. for (auto &th : threads) {
  1408. th.join();
  1409. }
  1410. std::this_thread::sleep_for(std::chrono::seconds(3));
  1411. }
  1412. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1413. if (!should_run_issue_2431_tests()) {
  1414. GTEST_SKIP()
  1415. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1416. }
  1417. std::atomic<bool> stop{false};
  1418. std::vector<std::thread> threads;
  1419. for (int t = 0; t < 8; ++t) {
  1420. threads.emplace_back([t, &stop] {
  1421. int i = 0;
  1422. while (!stop.load(std::memory_order_relaxed)) {
  1423. auto host = unique_unresolvable_host(t * 100000 + i++);
  1424. Client cli(host, 80);
  1425. cli.set_connection_timeout(1, 0);
  1426. cli.set_read_timeout(1, 0);
  1427. cli.set_write_timeout(1, 0);
  1428. (void)cli.Get("/");
  1429. }
  1430. });
  1431. }
  1432. std::this_thread::sleep_for(std::chrono::seconds(8));
  1433. stop.store(true, std::memory_order_relaxed);
  1434. for (auto &th : threads) {
  1435. th.join();
  1436. }
  1437. std::this_thread::sleep_for(std::chrono::seconds(3));
  1438. }
  1439. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1440. TEST(ConnectionErrorTest, InvalidHost) {
  1441. auto host = "-abcde.com";
  1442. #ifdef CPPHTTPLIB_SSL_ENABLED
  1443. auto port = 443;
  1444. SSLClient cli(host, port);
  1445. #else
  1446. auto port = 80;
  1447. Client cli(host, port);
  1448. #endif
  1449. cli.set_connection_timeout(std::chrono::seconds(2));
  1450. auto res = cli.Get("/");
  1451. ASSERT_TRUE(!res);
  1452. EXPECT_EQ(Error::Connection, res.error());
  1453. }
  1454. TEST(ConnectionErrorTest, InvalidHost2) {
  1455. auto host = "httpcan.org/";
  1456. #ifdef CPPHTTPLIB_SSL_ENABLED
  1457. SSLClient cli(host);
  1458. #else
  1459. Client cli(host);
  1460. #endif
  1461. cli.set_connection_timeout(std::chrono::seconds(2));
  1462. auto res = cli.Get("/");
  1463. ASSERT_TRUE(!res);
  1464. EXPECT_EQ(Error::Connection, res.error());
  1465. }
  1466. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1467. auto host = "httpcan.org/";
  1468. #ifdef CPPHTTPLIB_SSL_ENABLED
  1469. SSLClient cli(host);
  1470. #else
  1471. Client cli(host);
  1472. #endif
  1473. cli.set_connection_timeout(std::chrono::seconds(2));
  1474. auto res = cli.Get("/");
  1475. ASSERT_TRUE(!res);
  1476. stringstream s;
  1477. s << "error code: " << res.error();
  1478. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1479. }
  1480. TEST(ConnectionErrorTest, InvalidPort) {
  1481. auto host = "localhost";
  1482. auto port = 44380;
  1483. #ifdef CPPHTTPLIB_SSL_ENABLED
  1484. SSLClient cli(host, port);
  1485. #else
  1486. Client cli(host, port);
  1487. #endif
  1488. cli.set_connection_timeout(std::chrono::seconds(2));
  1489. auto res = cli.Get("/");
  1490. ASSERT_TRUE(!res);
  1491. EXPECT_TRUE(Error::Connection == res.error() ||
  1492. Error::ConnectionTimeout == res.error());
  1493. }
  1494. TEST(ConnectionErrorTest, Timeout_Online) {
  1495. auto host = "google.com";
  1496. #ifdef CPPHTTPLIB_SSL_ENABLED
  1497. auto port = 44380;
  1498. SSLClient cli(host, port);
  1499. #else
  1500. auto port = 8080;
  1501. Client cli(host, port);
  1502. #endif
  1503. cli.set_connection_timeout(std::chrono::seconds(2));
  1504. // only probe one address type so that the error reason
  1505. // correlates to the timed-out IPv4, not the unsupported
  1506. // IPv6 connection attempt
  1507. cli.set_address_family(AF_INET);
  1508. auto res = cli.Get("/");
  1509. ASSERT_TRUE(!res);
  1510. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1511. }
  1512. TEST(CancelTest, NoCancel_Online) {
  1513. auto host = "httpbingo.org";
  1514. auto path = std::string{"/range/32"};
  1515. #ifdef CPPHTTPLIB_SSL_ENABLED
  1516. auto port = 443;
  1517. SSLClient cli(host, port);
  1518. #else
  1519. auto port = 80;
  1520. Client cli(host, port);
  1521. #endif
  1522. cli.set_connection_timeout(std::chrono::seconds(5));
  1523. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1524. ASSERT_TRUE(res);
  1525. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1526. EXPECT_EQ(StatusCode::OK_200, res->status);
  1527. }
  1528. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1529. // Use /bytes with a large payload so that the DownloadProgress callback
  1530. // (which only fires for Content-Length responses) is invoked before the
  1531. // entire body is received, giving cancellation a chance to fire.
  1532. auto host = "httpbingo.org";
  1533. auto path = std::string{"/bytes/524288"};
  1534. #ifdef CPPHTTPLIB_SSL_ENABLED
  1535. auto port = 443;
  1536. SSLClient cli(host, port);
  1537. #else
  1538. auto port = 80;
  1539. Client cli(host, port);
  1540. #endif
  1541. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1542. cli.set_connection_timeout(std::chrono::seconds(5));
  1543. ASSERT_TRUE(!res);
  1544. EXPECT_EQ(Error::Canceled, res.error());
  1545. }
  1546. TEST(CancelTest, WithCancelLargePayload_Online) {
  1547. auto host = "httpbingo.org";
  1548. auto path = std::string{"/bytes/524288"};
  1549. #ifdef CPPHTTPLIB_SSL_ENABLED
  1550. auto port = 443;
  1551. SSLClient cli(host, port);
  1552. #else
  1553. auto port = 80;
  1554. Client cli(host, port);
  1555. #endif
  1556. cli.set_connection_timeout(std::chrono::seconds(5));
  1557. uint32_t count = 0;
  1558. auto res =
  1559. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1560. ASSERT_TRUE(!res);
  1561. EXPECT_EQ(Error::Canceled, res.error());
  1562. }
  1563. TEST(CancelTest, NoCancelPost) {
  1564. Server svr;
  1565. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1566. res.set_content("Hello World!", "text/plain");
  1567. });
  1568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. thread.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. Client cli(HOST, PORT);
  1576. cli.set_connection_timeout(std::chrono::seconds(5));
  1577. auto res =
  1578. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1579. "application/json", [](uint64_t, uint64_t) { return true; });
  1580. ASSERT_TRUE(res);
  1581. EXPECT_EQ("Hello World!", res->body);
  1582. EXPECT_EQ(StatusCode::OK_200, res->status);
  1583. }
  1584. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1585. Server svr;
  1586. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1587. res.set_content("Hello World!", "text/plain");
  1588. });
  1589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1590. auto se = detail::scope_exit([&] {
  1591. svr.stop();
  1592. thread.join();
  1593. ASSERT_FALSE(svr.is_running());
  1594. });
  1595. svr.wait_until_ready();
  1596. Client cli(HOST, PORT);
  1597. cli.set_connection_timeout(std::chrono::seconds(5));
  1598. auto res =
  1599. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1600. "application/json", [](uint64_t, uint64_t) { return false; });
  1601. ASSERT_TRUE(!res);
  1602. EXPECT_EQ(Error::Canceled, res.error());
  1603. }
  1604. TEST(CancelTest, WithCancelLargePayloadPost) {
  1605. Server svr;
  1606. svr.set_payload_max_length(200 * 1024 * 1024);
  1607. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1608. res.set_content(LARGE_DATA, "text/plain");
  1609. });
  1610. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1611. auto se = detail::scope_exit([&] {
  1612. svr.stop();
  1613. thread.join();
  1614. ASSERT_FALSE(svr.is_running());
  1615. });
  1616. svr.wait_until_ready();
  1617. Client cli(HOST, PORT);
  1618. cli.set_payload_max_length(200 * 1024 * 1024);
  1619. cli.set_connection_timeout(std::chrono::seconds(5));
  1620. auto res =
  1621. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1622. "application/json", [](uint64_t, uint64_t) { return false; });
  1623. ASSERT_TRUE(!res);
  1624. EXPECT_EQ(Error::Canceled, res.error());
  1625. }
  1626. TEST(CancelTest, NoCancelPut) {
  1627. Server svr;
  1628. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1629. res.set_content("Hello World!", "text/plain");
  1630. });
  1631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. thread.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. Client cli(HOST, PORT);
  1639. cli.set_connection_timeout(std::chrono::seconds(5));
  1640. auto res =
  1641. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1642. "application/json", [](uint64_t, uint64_t) { return true; });
  1643. ASSERT_TRUE(res);
  1644. EXPECT_EQ("Hello World!", res->body);
  1645. EXPECT_EQ(StatusCode::OK_200, res->status);
  1646. }
  1647. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1648. Server svr;
  1649. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1650. res.set_content("Hello World!", "text/plain");
  1651. });
  1652. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1653. auto se = detail::scope_exit([&] {
  1654. svr.stop();
  1655. thread.join();
  1656. ASSERT_FALSE(svr.is_running());
  1657. });
  1658. svr.wait_until_ready();
  1659. Client cli(HOST, PORT);
  1660. cli.set_connection_timeout(std::chrono::seconds(5));
  1661. auto res =
  1662. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1663. "application/json", [](uint64_t, uint64_t) { return false; });
  1664. ASSERT_TRUE(!res);
  1665. EXPECT_EQ(Error::Canceled, res.error());
  1666. }
  1667. TEST(CancelTest, WithCancelLargePayloadPut) {
  1668. Server svr;
  1669. svr.set_payload_max_length(200 * 1024 * 1024);
  1670. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1671. res.set_content(LARGE_DATA, "text/plain");
  1672. });
  1673. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1674. auto se = detail::scope_exit([&] {
  1675. svr.stop();
  1676. thread.join();
  1677. ASSERT_FALSE(svr.is_running());
  1678. });
  1679. svr.wait_until_ready();
  1680. Client cli(HOST, PORT);
  1681. cli.set_payload_max_length(200 * 1024 * 1024);
  1682. cli.set_connection_timeout(std::chrono::seconds(5));
  1683. auto res =
  1684. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1685. "application/json", [](uint64_t, uint64_t) { return false; });
  1686. ASSERT_TRUE(!res);
  1687. EXPECT_EQ(Error::Canceled, res.error());
  1688. }
  1689. TEST(CancelTest, NoCancelPatch) {
  1690. Server svr;
  1691. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1692. res.set_content("Hello World!", "text/plain");
  1693. });
  1694. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1695. auto se = detail::scope_exit([&] {
  1696. svr.stop();
  1697. thread.join();
  1698. ASSERT_FALSE(svr.is_running());
  1699. });
  1700. svr.wait_until_ready();
  1701. Client cli(HOST, PORT);
  1702. cli.set_connection_timeout(std::chrono::seconds(5));
  1703. auto res =
  1704. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1705. "application/json", [](uint64_t, uint64_t) { return true; });
  1706. ASSERT_TRUE(res);
  1707. EXPECT_EQ("Hello World!", res->body);
  1708. EXPECT_EQ(StatusCode::OK_200, res->status);
  1709. }
  1710. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1711. Server svr;
  1712. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1713. res.set_content("Hello World!", "text/plain");
  1714. });
  1715. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1716. auto se = detail::scope_exit([&] {
  1717. svr.stop();
  1718. thread.join();
  1719. ASSERT_FALSE(svr.is_running());
  1720. });
  1721. svr.wait_until_ready();
  1722. Client cli(HOST, PORT);
  1723. cli.set_connection_timeout(std::chrono::seconds(5));
  1724. auto res =
  1725. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1726. "application/json", [](uint64_t, uint64_t) { return false; });
  1727. ASSERT_TRUE(!res);
  1728. EXPECT_EQ(Error::Canceled, res.error());
  1729. }
  1730. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1731. Server svr;
  1732. svr.set_payload_max_length(200 * 1024 * 1024);
  1733. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1734. res.set_content(LARGE_DATA, "text/plain");
  1735. });
  1736. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1737. auto se = detail::scope_exit([&] {
  1738. svr.stop();
  1739. thread.join();
  1740. ASSERT_FALSE(svr.is_running());
  1741. });
  1742. svr.wait_until_ready();
  1743. Client cli(HOST, PORT);
  1744. cli.set_payload_max_length(200 * 1024 * 1024);
  1745. cli.set_connection_timeout(std::chrono::seconds(5));
  1746. auto res =
  1747. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1748. "application/json", [](uint64_t, uint64_t) { return false; });
  1749. ASSERT_TRUE(!res);
  1750. EXPECT_EQ(Error::Canceled, res.error());
  1751. }
  1752. TEST(CancelTest, NoCancelDelete) {
  1753. Server svr;
  1754. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1755. res.set_content("Hello World!", "text/plain");
  1756. });
  1757. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1758. auto se = detail::scope_exit([&] {
  1759. svr.stop();
  1760. thread.join();
  1761. ASSERT_FALSE(svr.is_running());
  1762. });
  1763. svr.wait_until_ready();
  1764. Client cli(HOST, PORT);
  1765. cli.set_connection_timeout(std::chrono::seconds(5));
  1766. auto res =
  1767. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1768. "application/json", [](uint64_t, uint64_t) { return true; });
  1769. ASSERT_TRUE(res);
  1770. EXPECT_EQ("Hello World!", res->body);
  1771. EXPECT_EQ(StatusCode::OK_200, res->status);
  1772. }
  1773. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1774. Server svr;
  1775. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1776. res.set_content("Hello World!", "text/plain");
  1777. });
  1778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1779. auto se = detail::scope_exit([&] {
  1780. svr.stop();
  1781. thread.join();
  1782. ASSERT_FALSE(svr.is_running());
  1783. });
  1784. svr.wait_until_ready();
  1785. Client cli(HOST, PORT);
  1786. cli.set_connection_timeout(std::chrono::seconds(5));
  1787. auto res =
  1788. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1789. "application/json", [](uint64_t, uint64_t) { return false; });
  1790. ASSERT_TRUE(!res);
  1791. EXPECT_EQ(Error::Canceled, res.error());
  1792. }
  1793. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1794. Server svr;
  1795. svr.set_payload_max_length(200 * 1024 * 1024);
  1796. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1797. res.set_content(LARGE_DATA, "text/plain");
  1798. });
  1799. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1800. auto se = detail::scope_exit([&] {
  1801. svr.stop();
  1802. thread.join();
  1803. ASSERT_FALSE(svr.is_running());
  1804. });
  1805. svr.wait_until_ready();
  1806. Client cli(HOST, PORT);
  1807. cli.set_payload_max_length(200 * 1024 * 1024);
  1808. cli.set_connection_timeout(std::chrono::seconds(5));
  1809. auto res =
  1810. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1811. "application/json", [](uint64_t, uint64_t) { return false; });
  1812. ASSERT_TRUE(!res);
  1813. EXPECT_EQ(Error::Canceled, res.error());
  1814. }
  1815. static std::string remove_whitespace(const std::string &input) {
  1816. std::string output;
  1817. output.reserve(input.size());
  1818. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1819. [](unsigned char c) { return !std::isspace(c); });
  1820. return output;
  1821. }
  1822. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1823. auto host = "httpbingo.org";
  1824. auto path = std::string{"/basic-auth/hello/world"};
  1825. #ifdef CPPHTTPLIB_SSL_ENABLED
  1826. auto port = 443;
  1827. SSLClient cli(host, port);
  1828. #else
  1829. auto port = 80;
  1830. Client cli(host, port);
  1831. #endif
  1832. {
  1833. auto res = cli.Get(path);
  1834. ASSERT_TRUE(res);
  1835. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1836. }
  1837. {
  1838. auto res =
  1839. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1840. ASSERT_TRUE(res);
  1841. auto body = remove_whitespace(res->body);
  1842. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1843. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1844. EXPECT_EQ(StatusCode::OK_200, res->status);
  1845. }
  1846. {
  1847. cli.set_basic_auth("hello", "world");
  1848. auto res = cli.Get(path);
  1849. ASSERT_TRUE(res);
  1850. auto body = remove_whitespace(res->body);
  1851. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1852. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. {
  1856. cli.set_basic_auth("hello", "bad");
  1857. auto res = cli.Get(path);
  1858. ASSERT_TRUE(res);
  1859. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1860. }
  1861. {
  1862. cli.set_basic_auth("bad", "world");
  1863. auto res = cli.Get(path);
  1864. ASSERT_TRUE(res);
  1865. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1866. }
  1867. }
  1868. #ifdef CPPHTTPLIB_SSL_ENABLED
  1869. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1870. auto host = "httpbingo.org";
  1871. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1872. auto paths = std::vector<std::string>{
  1873. "/digest-auth/auth/hello/world/MD5",
  1874. "/digest-auth/auth/hello/world/SHA-256",
  1875. };
  1876. auto port = 443;
  1877. SSLClient cli(host, port);
  1878. {
  1879. auto res = cli.Get(unauth_path);
  1880. ASSERT_TRUE(res);
  1881. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1882. }
  1883. {
  1884. cli.set_digest_auth("hello", "world");
  1885. for (const auto &path : paths) {
  1886. auto res = cli.Get(path.c_str());
  1887. ASSERT_TRUE(res);
  1888. auto body = remove_whitespace(res->body);
  1889. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1890. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1891. EXPECT_EQ(StatusCode::OK_200, res->status);
  1892. }
  1893. cli.set_digest_auth("hello", "bad");
  1894. for (const auto &path : paths) {
  1895. auto res = cli.Get(path.c_str());
  1896. ASSERT_TRUE(res);
  1897. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1898. }
  1899. }
  1900. }
  1901. #endif
  1902. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1903. auto host = "google.com";
  1904. auto another_host = "example.com";
  1905. auto wrong_ip = "0.0.0.0";
  1906. #ifdef CPPHTTPLIB_SSL_ENABLED
  1907. SSLClient cli(host);
  1908. #else
  1909. Client cli(host);
  1910. #endif
  1911. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1912. auto res = cli.Get("/");
  1913. ASSERT_TRUE(res);
  1914. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1915. }
  1916. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1917. auto host = "google.com";
  1918. auto wrong_ip = "0.0.0.0";
  1919. #ifdef CPPHTTPLIB_SSL_ENABLED
  1920. SSLClient cli(host);
  1921. #else
  1922. Client cli(host);
  1923. #endif
  1924. cli.set_hostname_addr_map({{host, wrong_ip}});
  1925. auto res = cli.Get("/");
  1926. ASSERT_TRUE(!res);
  1927. EXPECT_EQ(Error::Connection, res.error());
  1928. }
  1929. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1930. auto host = "httpbingo.org";
  1931. auto path = std::string{"/absolute-redirect/3"};
  1932. #ifdef CPPHTTPLIB_SSL_ENABLED
  1933. SSLClient cli(host);
  1934. #else
  1935. Client cli(host);
  1936. #endif
  1937. cli.set_follow_location(true);
  1938. auto res = cli.Get(path);
  1939. ASSERT_TRUE(res);
  1940. EXPECT_EQ(StatusCode::OK_200, res->status);
  1941. }
  1942. TEST(RedirectTest, Redirect_Online) {
  1943. auto host = "httpbingo.org";
  1944. auto path = std::string{"/redirect/3"};
  1945. #ifdef CPPHTTPLIB_SSL_ENABLED
  1946. SSLClient cli(host);
  1947. #else
  1948. Client cli(host);
  1949. #endif
  1950. cli.set_follow_location(true);
  1951. auto res = cli.Get(path);
  1952. ASSERT_TRUE(res);
  1953. EXPECT_EQ(StatusCode::OK_200, res->status);
  1954. }
  1955. TEST(RelativeRedirectTest, Redirect_Online) {
  1956. auto host = "httpbingo.org";
  1957. auto path = std::string{"/relative-redirect/3"};
  1958. #ifdef CPPHTTPLIB_SSL_ENABLED
  1959. SSLClient cli(host);
  1960. #else
  1961. Client cli(host);
  1962. #endif
  1963. cli.set_follow_location(true);
  1964. auto res = cli.Get(path);
  1965. ASSERT_TRUE(res);
  1966. EXPECT_EQ(StatusCode::OK_200, res->status);
  1967. }
  1968. TEST(TooManyRedirectTest, Redirect_Online) {
  1969. auto host = "httpbingo.org";
  1970. auto path = std::string{"/redirect/21"};
  1971. #ifdef CPPHTTPLIB_SSL_ENABLED
  1972. SSLClient cli(host);
  1973. #else
  1974. Client cli(host);
  1975. #endif
  1976. cli.set_follow_location(true);
  1977. auto res = cli.Get(path);
  1978. ASSERT_TRUE(!res);
  1979. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1980. }
  1981. #ifdef CPPHTTPLIB_SSL_ENABLED
  1982. TEST(YahooRedirectTest, Redirect_Online) {
  1983. Client cli("yahoo.com");
  1984. auto res = cli.Get("/");
  1985. ASSERT_TRUE(res);
  1986. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1987. cli.set_follow_location(true);
  1988. res = cli.Get("/");
  1989. ASSERT_TRUE(res);
  1990. EXPECT_EQ(StatusCode::OK_200, res->status);
  1991. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1992. }
  1993. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1994. #define REDIR_HOST "httpbingo.org"
  1995. #define REDIR_PATH "/redirect-to"
  1996. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1997. SSLClient cli(REDIR_HOST);
  1998. cli.set_follow_location(true);
  1999. auto res =
  2000. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2001. ASSERT_TRUE(res);
  2002. EXPECT_EQ(StatusCode::OK_200, res->status);
  2003. }
  2004. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2005. SSLClient cli(REDIR_HOST);
  2006. cli.set_follow_location(true);
  2007. Params params;
  2008. params.emplace("url", "http://example.com");
  2009. params.emplace("status_code", "302");
  2010. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2011. ASSERT_TRUE(res);
  2012. EXPECT_EQ(StatusCode::OK_200, res->status);
  2013. }
  2014. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2015. SSLClient cli(REDIR_HOST);
  2016. cli.set_follow_location(true);
  2017. Params params;
  2018. params.emplace("url", "http://example.com");
  2019. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2020. ASSERT_TRUE(res);
  2021. EXPECT_EQ(StatusCode::OK_200, res->status);
  2022. }
  2023. TEST(UrlWithSpace, Redirect_Online) {
  2024. SSLClient cli("edge.forgecdn.net");
  2025. cli.set_follow_location(true);
  2026. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2027. ASSERT_TRUE(res);
  2028. EXPECT_EQ(StatusCode::OK_200, res->status);
  2029. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2030. }
  2031. #endif
  2032. #if !defined(_WIN32) && !defined(_WIN64)
  2033. TEST(ReceiveSignals, Signal) {
  2034. auto setupSignalHandlers = []() {
  2035. struct sigaction act;
  2036. sigemptyset(&act.sa_mask);
  2037. act.sa_flags = SA_SIGINFO;
  2038. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2039. switch (sig) {
  2040. case SIGINT:
  2041. default: break;
  2042. }
  2043. };
  2044. ::sigaction(SIGINT, &act, nullptr);
  2045. };
  2046. Server svr;
  2047. int port = 0;
  2048. auto thread = std::thread([&]() {
  2049. setupSignalHandlers();
  2050. port = svr.bind_to_any_port(HOST);
  2051. svr.listen_after_bind();
  2052. });
  2053. auto se = detail::scope_exit([&] {
  2054. svr.stop();
  2055. thread.join();
  2056. ASSERT_FALSE(svr.is_running());
  2057. });
  2058. svr.wait_until_ready();
  2059. ASSERT_TRUE(svr.is_running());
  2060. pthread_kill(thread.native_handle(), SIGINT);
  2061. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2062. ASSERT_TRUE(svr.is_running());
  2063. }
  2064. #endif
  2065. TEST(RedirectToDifferentPort, Redirect) {
  2066. Server svr1;
  2067. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2068. res.set_content("Hello World!", "text/plain");
  2069. });
  2070. int svr1_port = 0;
  2071. auto thread1 = std::thread([&]() {
  2072. svr1_port = svr1.bind_to_any_port(HOST);
  2073. svr1.listen_after_bind();
  2074. });
  2075. Server svr2;
  2076. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2077. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2078. });
  2079. int svr2_port = 0;
  2080. auto thread2 = std::thread([&]() {
  2081. svr2_port = svr2.bind_to_any_port(HOST);
  2082. svr2.listen_after_bind();
  2083. });
  2084. auto se = detail::scope_exit([&] {
  2085. svr2.stop();
  2086. thread2.join();
  2087. svr1.stop();
  2088. thread1.join();
  2089. ASSERT_FALSE(svr2.is_running());
  2090. ASSERT_FALSE(svr1.is_running());
  2091. });
  2092. svr1.wait_until_ready();
  2093. svr2.wait_until_ready();
  2094. Client cli("localhost", svr2_port);
  2095. cli.set_follow_location(true);
  2096. auto res = cli.Get("/2");
  2097. ASSERT_TRUE(res);
  2098. EXPECT_EQ(StatusCode::OK_200, res->status);
  2099. EXPECT_EQ("Hello World!", res->body);
  2100. }
  2101. static void
  2102. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2103. Server svr1;
  2104. std::string captured_authorization;
  2105. svr1.Get("/target", [&](const Request &req, Response &res) {
  2106. captured_authorization = req.get_header_value("Authorization");
  2107. res.set_content("OK", "text/plain");
  2108. });
  2109. int svr1_port = 0;
  2110. auto thread1 = std::thread([&]() {
  2111. svr1_port = svr1.bind_to_any_port(HOST);
  2112. svr1.listen_after_bind();
  2113. });
  2114. Server svr2;
  2115. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2116. res.set_redirect(
  2117. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2118. });
  2119. int svr2_port = 0;
  2120. auto thread2 = std::thread([&]() {
  2121. svr2_port = svr2.bind_to_any_port(HOST);
  2122. svr2.listen_after_bind();
  2123. });
  2124. auto se = detail::scope_exit([&] {
  2125. svr2.stop();
  2126. thread2.join();
  2127. svr1.stop();
  2128. thread1.join();
  2129. ASSERT_FALSE(svr2.is_running());
  2130. ASSERT_FALSE(svr1.is_running());
  2131. });
  2132. svr1.wait_until_ready();
  2133. svr2.wait_until_ready();
  2134. Client cli("localhost", svr2_port);
  2135. cli.set_follow_location(true);
  2136. set_auth(cli);
  2137. auto res = cli.Get("/redir");
  2138. ASSERT_TRUE(res);
  2139. EXPECT_EQ(StatusCode::OK_200, res->status);
  2140. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2141. EXPECT_TRUE(captured_authorization.empty());
  2142. }
  2143. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2144. TestDoNotForwardCredentialsOnRedirect(
  2145. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2146. }
  2147. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2148. TestDoNotForwardCredentialsOnRedirect(
  2149. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2150. }
  2151. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2152. Server svr;
  2153. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2154. // Port number that overflows int — should not crash
  2155. res.set_redirect("http://localhost:99999999999999999999/target");
  2156. });
  2157. auto port = svr.bind_to_any_port(HOST);
  2158. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2159. auto se = detail::scope_exit([&] {
  2160. svr.stop();
  2161. thread.join();
  2162. ASSERT_FALSE(svr.is_running());
  2163. });
  2164. svr.wait_until_ready();
  2165. Client cli(HOST, port);
  2166. cli.set_follow_location(true);
  2167. auto res = cli.Get("/redir");
  2168. // Should fail gracefully, not crash (no valid response due to bad port)
  2169. EXPECT_FALSE(res);
  2170. }
  2171. TEST(RedirectFromPageWithContent, Redirect) {
  2172. Server svr;
  2173. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2174. res.set_content("___", "text/plain");
  2175. res.set_redirect("/2");
  2176. });
  2177. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2178. res.set_content("Hello World!", "text/plain");
  2179. });
  2180. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2181. auto se = detail::scope_exit([&] {
  2182. svr.stop();
  2183. th.join();
  2184. ASSERT_FALSE(svr.is_running());
  2185. });
  2186. svr.wait_until_ready();
  2187. {
  2188. Client cli("localhost", PORT);
  2189. cli.set_follow_location(true);
  2190. std::string body;
  2191. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2192. body.append(data, data_length);
  2193. return true;
  2194. });
  2195. ASSERT_TRUE(res);
  2196. EXPECT_EQ(StatusCode::OK_200, res->status);
  2197. EXPECT_EQ("Hello World!", body);
  2198. }
  2199. {
  2200. Client cli("localhost", PORT);
  2201. std::string body;
  2202. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2203. body.append(data, data_length);
  2204. return true;
  2205. });
  2206. ASSERT_TRUE(res);
  2207. EXPECT_EQ(StatusCode::Found_302, res->status);
  2208. EXPECT_EQ("___", body);
  2209. }
  2210. }
  2211. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2212. Server svr;
  2213. auto port_str = std::to_string(PORT);
  2214. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2215. auto expected_host = "[::1]:" + port_str;
  2216. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2217. res.set_content("___", "text/plain");
  2218. // res.set_redirect("/2");
  2219. res.set_redirect(redirect_url);
  2220. });
  2221. svr.Get("/2", [&](const Request &req, Response &res) {
  2222. auto host_header = req.headers.find("Host");
  2223. ASSERT_TRUE(host_header != req.headers.end());
  2224. EXPECT_EQ(expected_host, host_header->second);
  2225. res.set_content("Hello World!", "text/plain");
  2226. });
  2227. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2228. auto se = detail::scope_exit([&] {
  2229. svr.stop();
  2230. th.join();
  2231. ASSERT_FALSE(svr.is_running());
  2232. });
  2233. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2234. // actually starts anything, so the condition !svr.is_running() will
  2235. // always remain true, and the loop never stops.
  2236. // This basically counts how many milliseconds have passed since the
  2237. // call to svr.listen(), and if after 5 seconds nothing started yet
  2238. // aborts the test.
  2239. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2240. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2241. ASSERT_LT(milliseconds, 5000U);
  2242. }
  2243. {
  2244. Client cli("::1", PORT);
  2245. cli.set_follow_location(true);
  2246. std::string body;
  2247. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2248. body.append(data, data_length);
  2249. return true;
  2250. });
  2251. ASSERT_TRUE(res);
  2252. EXPECT_EQ(StatusCode::OK_200, res->status);
  2253. EXPECT_EQ("Hello World!", body);
  2254. }
  2255. {
  2256. Client cli("::1", PORT);
  2257. std::string body;
  2258. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2259. body.append(data, data_length);
  2260. return true;
  2261. });
  2262. ASSERT_TRUE(res);
  2263. EXPECT_EQ(StatusCode::Found_302, res->status);
  2264. EXPECT_EQ("___", body);
  2265. }
  2266. }
  2267. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2268. Server svr;
  2269. svr.Get("/foo", [](const Request &req, Response &res) {
  2270. auto a = req.params.find("a");
  2271. if (a != req.params.end()) {
  2272. res.set_content((*a).second, "text/plain");
  2273. res.status = StatusCode::OK_200;
  2274. } else {
  2275. res.status = StatusCode::BadRequest_400;
  2276. }
  2277. });
  2278. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2279. auto se = detail::scope_exit([&] {
  2280. svr.stop();
  2281. thread.join();
  2282. ASSERT_FALSE(svr.is_running());
  2283. });
  2284. svr.wait_until_ready();
  2285. {
  2286. Client cli(HOST, PORT);
  2287. cli.set_path_encode(false);
  2288. auto res = cli.Get("/foo?a=explicitly+encoded");
  2289. ASSERT_TRUE(res);
  2290. EXPECT_EQ(StatusCode::OK_200, res->status);
  2291. // This expects it back with a space, as the `+` won't have been
  2292. // url-encoded, and server-side the params get decoded turning `+`
  2293. // into spaces.
  2294. EXPECT_EQ("explicitly encoded", res->body);
  2295. }
  2296. }
  2297. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2298. Server svr;
  2299. svr.Get("/", [](const Request &req, Response &) {
  2300. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2301. });
  2302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2303. auto se = detail::scope_exit([&] {
  2304. svr.stop();
  2305. thread.join();
  2306. ASSERT_FALSE(svr.is_running());
  2307. });
  2308. svr.wait_until_ready();
  2309. {
  2310. Client cli(HOST, PORT);
  2311. cli.set_path_encode(false);
  2312. auto res = cli.Get("/?something=%0A");
  2313. ASSERT_TRUE(res);
  2314. EXPECT_EQ(StatusCode::OK_200, res->status);
  2315. }
  2316. }
  2317. TEST(BindServerTest, BindDualStack) {
  2318. Server svr;
  2319. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2320. res.set_content("Hello World!", "text/plain");
  2321. });
  2322. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2323. auto se = detail::scope_exit([&] {
  2324. svr.stop();
  2325. thread.join();
  2326. ASSERT_FALSE(svr.is_running());
  2327. });
  2328. svr.wait_until_ready();
  2329. {
  2330. Client cli("127.0.0.1", PORT);
  2331. auto res = cli.Get("/1");
  2332. ASSERT_TRUE(res);
  2333. EXPECT_EQ(StatusCode::OK_200, res->status);
  2334. EXPECT_EQ("Hello World!", res->body);
  2335. }
  2336. {
  2337. Client cli("::1", PORT);
  2338. auto res = cli.Get("/1");
  2339. ASSERT_TRUE(res);
  2340. EXPECT_EQ(StatusCode::OK_200, res->status);
  2341. EXPECT_EQ("Hello World!", res->body);
  2342. }
  2343. }
  2344. TEST(BindServerTest, BindAndListenSeparately) {
  2345. Server svr;
  2346. int port = svr.bind_to_any_port("0.0.0.0");
  2347. ASSERT_TRUE(svr.is_valid());
  2348. ASSERT_TRUE(port > 0);
  2349. svr.stop();
  2350. }
  2351. #ifdef CPPHTTPLIB_SSL_ENABLED
  2352. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2354. CLIENT_CA_CERT_DIR);
  2355. int port = svr.bind_to_any_port("0.0.0.0");
  2356. ASSERT_TRUE(svr.is_valid());
  2357. ASSERT_TRUE(port > 0);
  2358. svr.stop();
  2359. }
  2360. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2361. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2362. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2363. int port = svr.bind_to_any_port("0.0.0.0");
  2364. ASSERT_TRUE(svr.is_valid());
  2365. ASSERT_TRUE(port > 0);
  2366. svr.stop();
  2367. }
  2368. TEST(BindServerTest, UpdateCertsPem) {
  2369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2370. int port = svr.bind_to_any_port("0.0.0.0");
  2371. ASSERT_TRUE(svr.is_valid());
  2372. ASSERT_TRUE(port > 0);
  2373. // Read PEM files
  2374. std::string cert_pem, key_pem, ca_pem;
  2375. read_file(SERVER_CERT_FILE, cert_pem);
  2376. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2377. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2378. // Update server certificates using PEM API
  2379. ASSERT_TRUE(
  2380. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2381. ASSERT_TRUE(svr.is_valid());
  2382. svr.stop();
  2383. }
  2384. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2385. // Start server with client CA (enables client auth)
  2386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2387. ASSERT_TRUE(svr.is_valid());
  2388. bool handler_called = false;
  2389. svr.Get("/test", [&](const Request &req, Response &res) {
  2390. handler_called = true;
  2391. // Verify client certificate is present
  2392. auto cert = req.peer_cert();
  2393. EXPECT_TRUE(static_cast<bool>(cert));
  2394. res.set_content("ok", "text/plain");
  2395. });
  2396. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2397. auto se = detail::scope_exit([&] {
  2398. svr.stop();
  2399. t.join();
  2400. ASSERT_FALSE(svr.is_running());
  2401. });
  2402. svr.wait_until_ready();
  2403. // Read PEM files
  2404. std::string cert_pem, key_pem, ca_pem;
  2405. read_file(SERVER_CERT_FILE, cert_pem);
  2406. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2407. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2408. // Update server certificates and client CA using PEM API while server running
  2409. ASSERT_TRUE(
  2410. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2411. // Connect with client certificate
  2412. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2413. cli.enable_server_certificate_verification(false);
  2414. cli.set_connection_timeout(30);
  2415. auto res = cli.Get("/test");
  2416. ASSERT_TRUE(res);
  2417. ASSERT_EQ(StatusCode::OK_200, res->status);
  2418. ASSERT_TRUE(handler_called);
  2419. EXPECT_EQ("ok", res->body);
  2420. }
  2421. #endif
  2422. TEST(ErrorHandlerTest, ContentLength) {
  2423. Server svr;
  2424. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2425. res.status = StatusCode::OK_200;
  2426. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2427. "text/html"); // <= Content-Length still 13
  2428. });
  2429. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2430. res.set_content("Hello World!\n", "text/plain");
  2431. res.status = 524;
  2432. });
  2433. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2434. auto se = detail::scope_exit([&] {
  2435. svr.stop();
  2436. thread.join();
  2437. ASSERT_FALSE(svr.is_running());
  2438. });
  2439. svr.wait_until_ready();
  2440. {
  2441. Client cli(HOST, PORT);
  2442. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2443. ASSERT_TRUE(res);
  2444. EXPECT_EQ(StatusCode::OK_200, res->status);
  2445. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2446. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2447. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2448. }
  2449. }
  2450. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2451. TEST(ExceptionTest, WithoutExceptionHandler) {
  2452. Server svr;
  2453. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2454. throw std::runtime_error("exception...");
  2455. });
  2456. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2457. throw std::runtime_error("exception\r\n...");
  2458. });
  2459. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2460. auto se = detail::scope_exit([&] {
  2461. svr.stop();
  2462. listen_thread.join();
  2463. ASSERT_FALSE(svr.is_running());
  2464. });
  2465. svr.wait_until_ready();
  2466. Client cli("localhost", PORT);
  2467. {
  2468. auto res = cli.Get("/exception");
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2471. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2472. }
  2473. {
  2474. auto res = cli.Get("/unknown");
  2475. ASSERT_TRUE(res);
  2476. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2477. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2478. }
  2479. }
  2480. TEST(ExceptionTest, WithExceptionHandler) {
  2481. Server svr;
  2482. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2483. std::exception_ptr ep) {
  2484. EXPECT_FALSE(ep == nullptr);
  2485. try {
  2486. std::rethrow_exception(ep);
  2487. } catch (std::exception &e) {
  2488. EXPECT_EQ("abc", std::string(e.what()));
  2489. } catch (...) {}
  2490. res.status = StatusCode::InternalServerError_500;
  2491. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2492. "text/html"); // <= Content-Length still 13 at this point
  2493. });
  2494. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2495. res.set_content("Hello World!\n", "text/plain");
  2496. throw std::runtime_error("abc");
  2497. });
  2498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. thread.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. for (size_t i = 0; i < 10; i++) {
  2506. Client cli(HOST, PORT);
  2507. for (size_t j = 0; j < 100; j++) {
  2508. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2509. ASSERT_TRUE(res);
  2510. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2511. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2512. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2513. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2514. }
  2515. cli.set_keep_alive(true);
  2516. for (size_t j = 0; j < 100; j++) {
  2517. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2518. ASSERT_TRUE(res);
  2519. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2520. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2521. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2522. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2523. }
  2524. }
  2525. }
  2526. TEST(ExceptionTest, AndErrorHandler) {
  2527. Server svr;
  2528. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2529. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2530. });
  2531. svr.set_exception_handler(
  2532. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2533. EXPECT_FALSE(ep == nullptr);
  2534. try {
  2535. std::rethrow_exception(ep);
  2536. } catch (std::exception &e) {
  2537. res.set_content(e.what(), "text/html");
  2538. } catch (...) {}
  2539. res.status = StatusCode::InternalServerError_500;
  2540. });
  2541. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2542. throw std::runtime_error("EXCEPTION");
  2543. });
  2544. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2545. res.set_content("ERROR", "text/html");
  2546. res.status = StatusCode::InternalServerError_500;
  2547. });
  2548. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2549. auto se = detail::scope_exit([&] {
  2550. svr.stop();
  2551. thread.join();
  2552. ASSERT_FALSE(svr.is_running());
  2553. });
  2554. svr.wait_until_ready();
  2555. Client cli(HOST, PORT);
  2556. {
  2557. auto res = cli.Get("/exception");
  2558. ASSERT_TRUE(res);
  2559. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2560. EXPECT_EQ("EXCEPTION", res->body);
  2561. }
  2562. {
  2563. auto res = cli.Get("/error");
  2564. ASSERT_TRUE(res);
  2565. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2566. EXPECT_EQ("ERROR", res->body);
  2567. }
  2568. {
  2569. auto res = cli.Get("/invalid");
  2570. ASSERT_TRUE(res);
  2571. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2572. EXPECT_EQ("NOT_FOUND", res->body);
  2573. }
  2574. }
  2575. #endif
  2576. TEST(NoContentTest, ContentLength) {
  2577. Server svr;
  2578. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2579. res.status = StatusCode::NoContent_204;
  2580. });
  2581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2582. auto se = detail::scope_exit([&] {
  2583. svr.stop();
  2584. thread.join();
  2585. ASSERT_FALSE(svr.is_running());
  2586. });
  2587. svr.wait_until_ready();
  2588. {
  2589. Client cli(HOST, PORT);
  2590. auto res = cli.Get("/hi");
  2591. ASSERT_TRUE(res);
  2592. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2593. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2594. }
  2595. }
  2596. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2597. #ifdef CPPHTTPLIB_SSL_ENABLED
  2598. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2599. ASSERT_TRUE(svr.is_valid());
  2600. #else
  2601. Server svr;
  2602. #endif
  2603. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2604. if (req.path == "/routing_handler") {
  2605. res.set_header("PRE_ROUTING", "on");
  2606. res.set_content("Routing Handler", "text/plain");
  2607. return httplib::Server::HandlerResponse::Handled;
  2608. }
  2609. return httplib::Server::HandlerResponse::Unhandled;
  2610. });
  2611. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2612. res.set_content("Error", "text/html");
  2613. });
  2614. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2615. if (req.path == "/routing_handler") {
  2616. res.set_header("POST_ROUTING", "on");
  2617. }
  2618. });
  2619. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2620. res.set_content("Hello World!\n", "text/plain");
  2621. });
  2622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2623. auto se = detail::scope_exit([&] {
  2624. svr.stop();
  2625. thread.join();
  2626. ASSERT_FALSE(svr.is_running());
  2627. });
  2628. svr.wait_until_ready();
  2629. {
  2630. #ifdef CPPHTTPLIB_SSL_ENABLED
  2631. SSLClient cli(HOST, PORT);
  2632. cli.enable_server_certificate_verification(false);
  2633. #else
  2634. Client cli(HOST, PORT);
  2635. #endif
  2636. auto res = cli.Get("/routing_handler");
  2637. ASSERT_TRUE(res);
  2638. EXPECT_EQ(StatusCode::OK_200, res->status);
  2639. EXPECT_EQ("Routing Handler", res->body);
  2640. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2641. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2642. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2643. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2644. }
  2645. {
  2646. #ifdef CPPHTTPLIB_SSL_ENABLED
  2647. SSLClient cli(HOST, PORT);
  2648. cli.enable_server_certificate_verification(false);
  2649. #else
  2650. Client cli(HOST, PORT);
  2651. #endif
  2652. auto res = cli.Get("/hi");
  2653. ASSERT_TRUE(res);
  2654. EXPECT_EQ(StatusCode::OK_200, res->status);
  2655. EXPECT_EQ("Hello World!\n", res->body);
  2656. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2657. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2658. }
  2659. {
  2660. #ifdef CPPHTTPLIB_SSL_ENABLED
  2661. SSLClient cli(HOST, PORT);
  2662. cli.enable_server_certificate_verification(false);
  2663. #else
  2664. Client cli(HOST, PORT);
  2665. #endif
  2666. auto res = cli.Get("/aaa");
  2667. ASSERT_TRUE(res);
  2668. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2669. EXPECT_EQ("Error", res->body);
  2670. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2671. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2672. }
  2673. }
  2674. TEST(RequestHandlerTest, PreRequestHandler) {
  2675. auto route_path = "/user/:user";
  2676. Server svr;
  2677. svr.Get("/hi", [](const Request &, Response &res) {
  2678. res.set_content("hi", "text/plain");
  2679. });
  2680. svr.Get(route_path, [](const Request &req, Response &res) {
  2681. res.set_content(req.path_params.at("user"), "text/plain");
  2682. });
  2683. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2684. if (req.matched_route == route_path) {
  2685. auto user = req.path_params.at("user");
  2686. if (user != "john") {
  2687. res.status = StatusCode::Forbidden_403;
  2688. res.set_content("error", "text/html");
  2689. return Server::HandlerResponse::Handled;
  2690. }
  2691. }
  2692. return Server::HandlerResponse::Unhandled;
  2693. });
  2694. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2695. auto se = detail::scope_exit([&] {
  2696. svr.stop();
  2697. thread.join();
  2698. ASSERT_FALSE(svr.is_running());
  2699. });
  2700. svr.wait_until_ready();
  2701. Client cli(HOST, PORT);
  2702. {
  2703. auto res = cli.Get("/hi");
  2704. ASSERT_TRUE(res);
  2705. EXPECT_EQ(StatusCode::OK_200, res->status);
  2706. EXPECT_EQ("hi", res->body);
  2707. }
  2708. {
  2709. auto res = cli.Get("/user/john");
  2710. ASSERT_TRUE(res);
  2711. EXPECT_EQ(StatusCode::OK_200, res->status);
  2712. EXPECT_EQ("john", res->body);
  2713. }
  2714. {
  2715. auto res = cli.Get("/user/invalid-user");
  2716. ASSERT_TRUE(res);
  2717. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2718. EXPECT_EQ("error", res->body);
  2719. }
  2720. }
  2721. // The pre-request handler must run before the request body is read, so a
  2722. // rejected request never forces the server to buffer a (potentially large)
  2723. // body. Here the posted body is larger than the payload limit: if the body
  2724. // were read first the server would answer 413, but because the pre-request
  2725. // handler runs first it answers 403 and the body is never read.
  2726. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2727. Server svr;
  2728. svr.set_payload_max_length(8);
  2729. auto handler_ran = false;
  2730. svr.Post("/reject", [&](const Request &req, Response &res) {
  2731. handler_ran = true;
  2732. res.set_content(req.body, "text/plain");
  2733. });
  2734. svr.Post("/accept", [](const Request &req, Response &res) {
  2735. res.set_content(req.body, "text/plain");
  2736. });
  2737. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2738. if (req.matched_route == "/reject") {
  2739. res.status = StatusCode::Forbidden_403;
  2740. res.set_content("denied", "text/plain");
  2741. return Server::HandlerResponse::Handled;
  2742. }
  2743. return Server::HandlerResponse::Unhandled;
  2744. });
  2745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2746. auto se = detail::scope_exit([&] {
  2747. svr.stop();
  2748. thread.join();
  2749. ASSERT_FALSE(svr.is_running());
  2750. });
  2751. svr.wait_until_ready();
  2752. Client cli(HOST, PORT);
  2753. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2754. // rejects with 403 before the body is read, so 413 is never reached.
  2755. {
  2756. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2757. ASSERT_TRUE(res);
  2758. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2759. EXPECT_EQ("denied", res->body);
  2760. EXPECT_FALSE(handler_ran);
  2761. }
  2762. // An approved route still reads the body and enforces the payload limit.
  2763. {
  2764. auto res = cli.Post("/accept", "0123456789", "text/plain");
  2765. ASSERT_TRUE(res);
  2766. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  2767. }
  2768. }
  2769. TEST(UserDataTest, BasicOperations) {
  2770. httplib::UserData ud;
  2771. // Initially empty
  2772. EXPECT_FALSE(ud.has("key"));
  2773. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2774. // set and get
  2775. ud.set("key", 42);
  2776. EXPECT_TRUE(ud.has("key"));
  2777. auto *p = ud.get<int>("key");
  2778. ASSERT_NE(nullptr, p);
  2779. EXPECT_EQ(42, *p);
  2780. // Type mismatch → nullptr
  2781. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2782. // Overwrite with different type
  2783. ud.set("key", std::string("hello"));
  2784. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2785. auto *s = ud.get<std::string>("key");
  2786. ASSERT_NE(nullptr, s);
  2787. EXPECT_EQ("hello", *s);
  2788. // erase
  2789. ud.erase("key");
  2790. EXPECT_FALSE(ud.has("key"));
  2791. // clear
  2792. ud.set("a", 1);
  2793. ud.set("b", 2);
  2794. ud.clear();
  2795. EXPECT_FALSE(ud.has("a"));
  2796. EXPECT_FALSE(ud.has("b"));
  2797. }
  2798. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2799. struct AuthCtx {
  2800. std::string user_id;
  2801. };
  2802. Server svr;
  2803. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2804. res.user_data.set("auth", AuthCtx{"alice"});
  2805. return Server::HandlerResponse::Unhandled;
  2806. });
  2807. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2808. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2809. ASSERT_NE(nullptr, ctx);
  2810. res.set_content("Hello " + ctx->user_id, "text/plain");
  2811. });
  2812. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2813. auto se = detail::scope_exit([&] {
  2814. svr.stop();
  2815. thread.join();
  2816. ASSERT_FALSE(svr.is_running());
  2817. });
  2818. svr.wait_until_ready();
  2819. Client cli(HOST, PORT);
  2820. auto res = cli.Get("/me");
  2821. ASSERT_TRUE(res);
  2822. EXPECT_EQ(StatusCode::OK_200, res->status);
  2823. EXPECT_EQ("Hello alice", res->body);
  2824. }
  2825. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2826. struct RoleCtx {
  2827. std::string role;
  2828. };
  2829. Server svr;
  2830. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2831. res.user_data.set("role", RoleCtx{"admin"});
  2832. return Server::HandlerResponse::Unhandled;
  2833. });
  2834. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2835. auto *ctx = res.user_data.get<RoleCtx>("role");
  2836. ASSERT_NE(nullptr, ctx);
  2837. res.set_content(ctx->role, "text/plain");
  2838. });
  2839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2840. auto se = detail::scope_exit([&] {
  2841. svr.stop();
  2842. thread.join();
  2843. ASSERT_FALSE(svr.is_running());
  2844. });
  2845. svr.wait_until_ready();
  2846. Client cli(HOST, PORT);
  2847. auto res = cli.Get("/role");
  2848. ASSERT_TRUE(res);
  2849. EXPECT_EQ(StatusCode::OK_200, res->status);
  2850. EXPECT_EQ("admin", res->body);
  2851. }
  2852. TEST(InvalidFormatTest, StatusCode) {
  2853. Server svr;
  2854. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2855. res.set_content("Hello World!\n", "text/plain");
  2856. res.status = 9999; // Status should be a three-digit code...
  2857. });
  2858. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2859. auto se = detail::scope_exit([&] {
  2860. svr.stop();
  2861. thread.join();
  2862. ASSERT_FALSE(svr.is_running());
  2863. });
  2864. svr.wait_until_ready();
  2865. {
  2866. Client cli(HOST, PORT);
  2867. auto res = cli.Get("/hi");
  2868. ASSERT_FALSE(res);
  2869. }
  2870. }
  2871. TEST(URLFragmentTest, WithFragment) {
  2872. Server svr;
  2873. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2874. EXPECT_TRUE(req.target == "/hi");
  2875. });
  2876. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2877. auto se = detail::scope_exit([&] {
  2878. svr.stop();
  2879. thread.join();
  2880. ASSERT_FALSE(svr.is_running());
  2881. });
  2882. svr.wait_until_ready();
  2883. {
  2884. Client cli(HOST, PORT);
  2885. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2886. EXPECT_TRUE(res);
  2887. EXPECT_EQ(StatusCode::OK_200, res->status);
  2888. res = cli.Get("/hi%23key1=val1=key2=val2");
  2889. EXPECT_TRUE(res);
  2890. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2891. }
  2892. }
  2893. TEST(HeaderWriter, SetHeaderWriter) {
  2894. Server svr;
  2895. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2896. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2897. return detail::write_headers(strm, hdrs);
  2898. });
  2899. svr.Get("/hi", [](const Request &req, Response &res) {
  2900. auto it = req.headers.find("CustomClientHeader");
  2901. EXPECT_TRUE(it != req.headers.end());
  2902. EXPECT_EQ(it->second, "CustomClientValue");
  2903. res.set_content("Hello World!\n", "text/plain");
  2904. });
  2905. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2906. auto se = detail::scope_exit([&] {
  2907. svr.stop();
  2908. thread.join();
  2909. ASSERT_FALSE(svr.is_running());
  2910. });
  2911. svr.wait_until_ready();
  2912. {
  2913. Client cli(HOST, PORT);
  2914. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2915. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2916. return detail::write_headers(strm, hdrs);
  2917. });
  2918. auto res = cli.Get("/hi");
  2919. EXPECT_TRUE(res);
  2920. EXPECT_EQ(StatusCode::OK_200, res->status);
  2921. auto it = res->headers.find("CustomServerHeader");
  2922. EXPECT_TRUE(it != res->headers.end());
  2923. EXPECT_EQ(it->second, "CustomServerValue");
  2924. }
  2925. }
  2926. class ServerTest : public ::testing::Test {
  2927. protected:
  2928. ServerTest()
  2929. : cli_(HOST, PORT)
  2930. #ifdef CPPHTTPLIB_SSL_ENABLED
  2931. ,
  2932. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2933. #endif
  2934. {
  2935. #ifdef CPPHTTPLIB_SSL_ENABLED
  2936. cli_.enable_server_certificate_verification(false);
  2937. #endif
  2938. // Allow LARGE_DATA (100MB) responses
  2939. cli_.set_payload_max_length(200 * 1024 * 1024);
  2940. }
  2941. virtual void SetUp() {
  2942. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2943. svr_.set_payload_max_length(200 * 1024 * 1024);
  2944. svr_.set_mount_point("/", "./www");
  2945. svr_.set_mount_point("/mount", "./www2");
  2946. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2947. svr_.Get("/hi",
  2948. [&](const Request & /*req*/, Response &res) {
  2949. res.set_content("Hello World!", "text/plain");
  2950. })
  2951. .Get("/file_content",
  2952. [&](const Request & /*req*/, Response &res) {
  2953. res.set_file_content("./www/dir/test.html");
  2954. })
  2955. .Get("/file_content_with_content_type",
  2956. [&](const Request & /*req*/, Response &res) {
  2957. res.set_file_content("./www/file", "text/plain");
  2958. })
  2959. .Get("/invalid_file_content",
  2960. [&](const Request & /*req*/, Response &res) {
  2961. res.set_file_content("./www/dir/invalid_file_path");
  2962. })
  2963. .Get("/http_response_splitting",
  2964. [&](const Request & /*req*/, Response &res) {
  2965. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2966. EXPECT_EQ(0U, res.headers.size());
  2967. EXPECT_FALSE(res.has_header("a"));
  2968. res.set_header("a", "1\nSet-Cookie: a=1");
  2969. EXPECT_EQ(0U, res.headers.size());
  2970. EXPECT_FALSE(res.has_header("a"));
  2971. res.set_header("a", "1\rSet-Cookie: a=1");
  2972. EXPECT_EQ(0U, res.headers.size());
  2973. EXPECT_FALSE(res.has_header("a"));
  2974. res.set_header("a\r\nb", "0");
  2975. EXPECT_EQ(0U, res.headers.size());
  2976. EXPECT_FALSE(res.has_header("a"));
  2977. res.set_header("a\rb", "0");
  2978. EXPECT_EQ(0U, res.headers.size());
  2979. EXPECT_FALSE(res.has_header("a"));
  2980. res.set_header("a\nb", "0");
  2981. EXPECT_EQ(0U, res.headers.size());
  2982. EXPECT_FALSE(res.has_header("a"));
  2983. res.set_redirect("1\r\nSet-Cookie: a=1");
  2984. EXPECT_EQ(0U, res.headers.size());
  2985. EXPECT_FALSE(res.has_header("Location"));
  2986. })
  2987. .Get("/slow",
  2988. [&](const Request & /*req*/, Response &res) {
  2989. std::this_thread::sleep_for(std::chrono::seconds(4));
  2990. res.set_content("slow", "text/plain");
  2991. })
  2992. #if 0
  2993. .Post("/slowpost",
  2994. [&](const Request & /*req*/, Response &res) {
  2995. std::this_thread::sleep_for(std::chrono::seconds(2));
  2996. res.set_content("slow", "text/plain");
  2997. })
  2998. #endif
  2999. .Get("/remote_addr",
  3000. [&](const Request &req, Response &res) {
  3001. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3002. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3003. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3004. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3005. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3006. #endif
  3007. res.set_content(req.remote_addr, "text/plain");
  3008. })
  3009. .Get("/local_addr",
  3010. [&](const Request &req, Response &res) {
  3011. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3012. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3013. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3014. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3015. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3016. #endif
  3017. auto local_addr = req.local_addr;
  3018. auto local_port = std::to_string(req.local_port);
  3019. res.set_content(local_addr.append(":").append(local_port),
  3020. "text/plain");
  3021. })
  3022. .Get("/endwith%",
  3023. [&](const Request & /*req*/, Response &res) {
  3024. res.set_content("Hello World!", "text/plain");
  3025. })
  3026. .Get("/a\\+\\+b",
  3027. [&](const Request &req, Response &res) {
  3028. ASSERT_TRUE(req.has_param("a +b"));
  3029. auto val = req.get_param_value("a +b");
  3030. res.set_content(val, "text/plain");
  3031. })
  3032. .Get("/", [&](const Request & /*req*/,
  3033. Response &res) { res.set_redirect("/hi"); })
  3034. .Post("/1",
  3035. [](const Request & /*req*/, Response &res) {
  3036. res.set_redirect("/2", StatusCode::SeeOther_303);
  3037. })
  3038. .Get("/2",
  3039. [](const Request & /*req*/, Response &res) {
  3040. res.set_content("redirected.", "text/plain");
  3041. res.status = StatusCode::OK_200;
  3042. })
  3043. .Post("/person",
  3044. [&](const Request &req, Response &res) {
  3045. if (req.has_param("name") && req.has_param("note")) {
  3046. persons_[req.get_param_value("name")] =
  3047. req.get_param_value("note");
  3048. } else {
  3049. res.status = StatusCode::BadRequest_400;
  3050. }
  3051. })
  3052. .Put("/person",
  3053. [&](const Request &req, Response &res) {
  3054. if (req.has_param("name") && req.has_param("note")) {
  3055. persons_[req.get_param_value("name")] =
  3056. req.get_param_value("note");
  3057. } else {
  3058. res.status = StatusCode::BadRequest_400;
  3059. }
  3060. })
  3061. .Get("/person/(.*)",
  3062. [&](const Request &req, Response &res) {
  3063. string name = req.matches[1];
  3064. if (persons_.find(name) != persons_.end()) {
  3065. auto note = persons_[name];
  3066. res.set_content(note, "text/plain");
  3067. } else {
  3068. res.status = StatusCode::NotFound_404;
  3069. }
  3070. })
  3071. .Delete("/person",
  3072. [&](const Request &req, Response &res) {
  3073. if (req.has_param("name")) {
  3074. string name = req.get_param_value("name");
  3075. if (persons_.find(name) != persons_.end()) {
  3076. persons_.erase(name);
  3077. res.set_content("DELETED", "text/plain");
  3078. } else {
  3079. res.status = StatusCode::NotFound_404;
  3080. }
  3081. } else {
  3082. res.status = StatusCode::BadRequest_400;
  3083. }
  3084. })
  3085. .Post("/x-www-form-urlencoded-json",
  3086. [&](const Request &req, Response &res) {
  3087. auto json = req.get_param_value("json");
  3088. ASSERT_EQ(JSON_DATA, json);
  3089. res.set_content(json, "appliation/json");
  3090. res.status = StatusCode::OK_200;
  3091. })
  3092. .Get("/streamed-chunked",
  3093. [&](const Request & /*req*/, Response &res) {
  3094. res.set_chunked_content_provider(
  3095. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3096. sink.os << "123";
  3097. sink.os << "456";
  3098. sink.os << "789";
  3099. sink.done();
  3100. return true;
  3101. });
  3102. })
  3103. .Get("/streamed-chunked-with-prohibited-trailer",
  3104. [&](const Request & /*req*/, Response &res) {
  3105. auto i = new int(0);
  3106. // Declare both a prohibited trailer (Content-Length) and an
  3107. // allowed one
  3108. res.set_header("Trailer", "Content-Length, X-Allowed");
  3109. res.set_chunked_content_provider(
  3110. "text/plain",
  3111. [i](size_t /*offset*/, DataSink &sink) {
  3112. switch (*i) {
  3113. case 0: sink.os << "123"; break;
  3114. case 1: sink.os << "456"; break;
  3115. case 2: sink.os << "789"; break;
  3116. case 3: {
  3117. sink.done_with_trailer(
  3118. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3119. } break;
  3120. }
  3121. (*i)++;
  3122. return true;
  3123. },
  3124. [i](bool success) {
  3125. EXPECT_TRUE(success);
  3126. delete i;
  3127. });
  3128. })
  3129. .Get("/streamed-chunked2",
  3130. [&](const Request & /*req*/, Response &res) {
  3131. auto i = new int(0);
  3132. res.set_chunked_content_provider(
  3133. "text/plain",
  3134. [i](size_t /*offset*/, DataSink &sink) {
  3135. switch (*i) {
  3136. case 0: sink.os << "123"; break;
  3137. case 1: sink.os << "456"; break;
  3138. case 2: sink.os << "789"; break;
  3139. case 3: sink.done(); break;
  3140. }
  3141. (*i)++;
  3142. return true;
  3143. },
  3144. [i](bool success) {
  3145. EXPECT_TRUE(success);
  3146. delete i;
  3147. });
  3148. })
  3149. .Get("/streamed-chunked-with-trailer",
  3150. [&](const Request & /*req*/, Response &res) {
  3151. auto i = new int(0);
  3152. res.set_header("Trailer", "Dummy1, Dummy2");
  3153. res.set_chunked_content_provider(
  3154. "text/plain",
  3155. [i](size_t /*offset*/, DataSink &sink) {
  3156. switch (*i) {
  3157. case 0: sink.os << "123"; break;
  3158. case 1: sink.os << "456"; break;
  3159. case 2: sink.os << "789"; break;
  3160. case 3: {
  3161. sink.done_with_trailer(
  3162. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3163. } break;
  3164. }
  3165. (*i)++;
  3166. return true;
  3167. },
  3168. [i](bool success) {
  3169. EXPECT_TRUE(success);
  3170. delete i;
  3171. });
  3172. })
  3173. .Get("/streamed",
  3174. [&](const Request & /*req*/, Response &res) {
  3175. res.set_content_provider(
  3176. 6, "text/plain",
  3177. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3178. sink.os << (offset < 3 ? "a" : "b");
  3179. return true;
  3180. });
  3181. })
  3182. .Get("/streamed-without-length",
  3183. [&](const Request & /*req*/, Response &res) {
  3184. auto data = new std::string("abcdefg");
  3185. res.set_content_provider(
  3186. "text/plain",
  3187. [data](size_t offset, DataSink &sink) {
  3188. if (offset < data->size()) {
  3189. sink.os << data->substr(offset);
  3190. }
  3191. sink.done();
  3192. return true;
  3193. },
  3194. [data](bool success) {
  3195. EXPECT_TRUE(success);
  3196. delete data;
  3197. });
  3198. })
  3199. .Get("/streamed-with-range",
  3200. [&](const Request &req, Response &res) {
  3201. auto data = new std::string("abcdefg");
  3202. res.set_content_provider(
  3203. data->size(), "text/plain",
  3204. [data](size_t offset, size_t length, DataSink &sink) {
  3205. size_t DATA_CHUNK_SIZE = 4;
  3206. const auto &d = *data;
  3207. auto out_len =
  3208. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3209. auto ret =
  3210. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3211. EXPECT_TRUE(ret);
  3212. return true;
  3213. },
  3214. [data, &req](bool success) {
  3215. EXPECT_EQ(success, !req.has_param("error"));
  3216. delete data;
  3217. });
  3218. })
  3219. .Get("/streamed-cancel",
  3220. [&](const Request & /*req*/, Response &res) {
  3221. res.set_content_provider(
  3222. size_t(-1), "text/plain",
  3223. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3224. sink.os << "data_chunk";
  3225. return true;
  3226. });
  3227. })
  3228. .Get("/regex-with-delimiter",
  3229. [&](const Request &req, Response & /*res*/) {
  3230. ASSERT_TRUE(req.has_param("key"));
  3231. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3232. })
  3233. .Get("/with-range",
  3234. [&](const Request & /*req*/, Response &res) {
  3235. res.set_content("abcdefg", "text/plain");
  3236. })
  3237. .Get("/test-start-time",
  3238. [&](const Request &req, Response & /*res*/) {
  3239. EXPECT_NE(req.start_time_,
  3240. std::chrono::steady_clock::time_point::min());
  3241. })
  3242. .Get("/with-range-customized-response",
  3243. [&](const Request & /*req*/, Response &res) {
  3244. res.status = StatusCode::BadRequest_400;
  3245. res.set_content(JSON_DATA, "application/json");
  3246. })
  3247. .Post("/chunked",
  3248. [&](const Request &req, Response & /*res*/) {
  3249. EXPECT_EQ(req.body, "dechunked post body");
  3250. })
  3251. .Post("/large-chunked",
  3252. [&](const Request &req, Response & /*res*/) {
  3253. std::string expected(6 * 30 * 1024u, 'a');
  3254. EXPECT_EQ(req.body, expected);
  3255. })
  3256. .Post("/multipart",
  3257. [&](const Request &req, Response & /*res*/) {
  3258. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3259. req.form.get_field_count("text2") +
  3260. req.form.get_field_count("file3") +
  3261. req.form.get_field_count("file4"));
  3262. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3263. req.form.get_file_count("file2"));
  3264. ASSERT_TRUE(!req.form.has_file("???"));
  3265. ASSERT_TRUE(!req.form.has_field("???"));
  3266. ASSERT_TRUE(req.body.empty());
  3267. {
  3268. const auto &text = req.form.get_field("text1");
  3269. EXPECT_EQ("text default", text);
  3270. }
  3271. {
  3272. const auto &text = req.form.get_field("text2");
  3273. EXPECT_EQ("aωb", text);
  3274. }
  3275. {
  3276. const auto &file = req.form.get_file("file1");
  3277. EXPECT_EQ("hello.txt", file.filename);
  3278. EXPECT_EQ("text/plain", file.content_type);
  3279. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3280. }
  3281. {
  3282. const auto &file = req.form.get_file("file2");
  3283. EXPECT_EQ("world.json", file.filename);
  3284. EXPECT_EQ("application/json", file.content_type);
  3285. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3286. }
  3287. {
  3288. const auto &text = req.form.get_field("file3");
  3289. EXPECT_EQ(0u, text.size());
  3290. }
  3291. {
  3292. const auto &text = req.form.get_field("file4");
  3293. EXPECT_EQ(0u, text.size());
  3294. }
  3295. })
  3296. .Post("/multipart/multi_file_values",
  3297. [&](const Request &req, Response & /*res*/) {
  3298. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3299. req.form.get_field_count("multi_text1"));
  3300. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3301. ASSERT_TRUE(!req.form.has_file("???"));
  3302. ASSERT_TRUE(!req.form.has_field("???"));
  3303. ASSERT_TRUE(req.body.empty());
  3304. {
  3305. const auto &text = req.form.get_field("text");
  3306. EXPECT_EQ("default text", text);
  3307. }
  3308. {
  3309. const auto &text1_values = req.form.get_fields("multi_text1");
  3310. EXPECT_EQ(2u, text1_values.size());
  3311. EXPECT_EQ("aaaaa", text1_values[0]);
  3312. EXPECT_EQ("bbbbb", text1_values[1]);
  3313. }
  3314. {
  3315. const auto &file1_values = req.form.get_files("multi_file1");
  3316. EXPECT_EQ(2u, file1_values.size());
  3317. auto file1 = file1_values[0];
  3318. EXPECT_EQ(file1.filename, "hello.txt");
  3319. EXPECT_EQ(file1.content_type, "text/plain");
  3320. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3321. auto file2 = file1_values[1];
  3322. EXPECT_EQ(file2.filename, "world.json");
  3323. EXPECT_EQ(file2.content_type, "application/json");
  3324. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3325. }
  3326. })
  3327. .Post("/empty",
  3328. [&](const Request &req, Response &res) {
  3329. EXPECT_EQ(req.body, "");
  3330. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3331. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3332. res.set_content("empty", "text/plain");
  3333. })
  3334. .Post("/empty-no-content-type",
  3335. [&](const Request &req, Response &res) {
  3336. EXPECT_EQ(req.body, "");
  3337. EXPECT_FALSE(req.has_header("Content-Type"));
  3338. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3339. res.set_content("empty-no-content-type", "text/plain");
  3340. })
  3341. .Post("/path-only",
  3342. [&](const Request &req, Response &res) {
  3343. EXPECT_EQ(req.body, "");
  3344. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3345. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3346. res.set_content("path-only", "text/plain");
  3347. })
  3348. .Post("/path-headers-only",
  3349. [&](const Request &req, Response &res) {
  3350. EXPECT_EQ(req.body, "");
  3351. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3352. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3353. EXPECT_EQ("world", req.get_header_value("hello"));
  3354. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3355. res.set_content("path-headers-only", "text/plain");
  3356. })
  3357. .Post("/post-large",
  3358. [&](const Request &req, Response &res) {
  3359. EXPECT_EQ(req.body, LARGE_DATA);
  3360. res.set_content(req.body, "text/plain");
  3361. })
  3362. .Post("/post-loopback",
  3363. [&](const Request &, Response &res,
  3364. ContentReader const &content_reader) {
  3365. std::string body;
  3366. content_reader([&](const char *data, size_t data_length) {
  3367. body.append(data, data_length);
  3368. return true;
  3369. });
  3370. res.set_content(body, "text/plain");
  3371. })
  3372. .Put("/put-loopback",
  3373. [&](const Request &, Response &res,
  3374. ContentReader const &content_reader) {
  3375. std::string body;
  3376. content_reader([&](const char *data, size_t data_length) {
  3377. body.append(data, data_length);
  3378. return true;
  3379. });
  3380. res.set_content(body, "text/plain");
  3381. })
  3382. .Patch("/patch-loopback",
  3383. [&](const Request &, Response &res,
  3384. ContentReader const &content_reader) {
  3385. std::string body;
  3386. content_reader([&](const char *data, size_t data_length) {
  3387. body.append(data, data_length);
  3388. return true;
  3389. });
  3390. res.set_content(body, "text/plain");
  3391. })
  3392. .Put("/empty-no-content-type",
  3393. [&](const Request &req, Response &res) {
  3394. EXPECT_EQ(req.body, "");
  3395. EXPECT_FALSE(req.has_header("Content-Type"));
  3396. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3397. res.set_content("empty-no-content-type", "text/plain");
  3398. })
  3399. .Put("/put",
  3400. [&](const Request &req, Response &res) {
  3401. EXPECT_EQ(req.body, "PUT");
  3402. res.set_content(req.body, "text/plain");
  3403. })
  3404. .Put("/put-large",
  3405. [&](const Request &req, Response &res) {
  3406. EXPECT_EQ(req.body, LARGE_DATA);
  3407. res.set_content(req.body, "text/plain");
  3408. })
  3409. .Patch("/patch",
  3410. [&](const Request &req, Response &res) {
  3411. EXPECT_EQ(req.body, "PATCH");
  3412. res.set_content(req.body, "text/plain");
  3413. })
  3414. .Delete("/delete",
  3415. [&](const Request & /*req*/, Response &res) {
  3416. res.set_content("DELETE", "text/plain");
  3417. })
  3418. .Delete("/delete-body",
  3419. [&](const Request &req, Response &res) {
  3420. EXPECT_EQ(req.body, "content");
  3421. res.set_content(req.body, "text/plain");
  3422. })
  3423. .Options(R"(\*)",
  3424. [&](const Request & /*req*/, Response &res) {
  3425. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3426. })
  3427. .Get("/request-target",
  3428. [&](const Request &req, Response & /*res*/) {
  3429. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3430. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3431. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3432. })
  3433. .Get("/long-query-value",
  3434. [&](const Request &req, Response & /*res*/) {
  3435. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3436. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3437. })
  3438. .Get("/too-long-query-value",
  3439. [&](const Request &req, Response & /*res*/) {
  3440. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3441. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3442. })
  3443. .Get("/array-param",
  3444. [&](const Request &req, Response & /*res*/) {
  3445. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3446. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3447. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3448. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3449. })
  3450. .Get("/array-param-values",
  3451. [&](const Request &req, Response & /*res*/) {
  3452. auto values = req.get_param_values("array");
  3453. EXPECT_EQ(3u, values.size());
  3454. EXPECT_EQ("value1", values[0]);
  3455. EXPECT_EQ("value2", values[1]);
  3456. EXPECT_EQ("value3", values[2]);
  3457. auto empty = req.get_param_values("nonexistent");
  3458. EXPECT_TRUE(empty.empty());
  3459. })
  3460. .Post("/validate-no-multiple-headers",
  3461. [&](const Request &req, Response & /*res*/) {
  3462. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3463. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3464. })
  3465. .Post("/content_receiver",
  3466. [&](const Request &req, Response &res,
  3467. const ContentReader &content_reader) {
  3468. if (req.is_multipart_form_data()) {
  3469. std::vector<FormData> items;
  3470. content_reader(
  3471. [&](const FormData &file) {
  3472. items.push_back(file);
  3473. return true;
  3474. },
  3475. [&](const char *data, size_t data_length) {
  3476. items.back().content.append(data, data_length);
  3477. return true;
  3478. });
  3479. EXPECT_EQ(5u, items.size());
  3480. {
  3481. const auto &file = get_file_value(items, "text1");
  3482. EXPECT_TRUE(file.filename.empty());
  3483. EXPECT_EQ("text default", file.content);
  3484. }
  3485. {
  3486. const auto &file = get_file_value(items, "text2");
  3487. EXPECT_TRUE(file.filename.empty());
  3488. EXPECT_EQ("aωb", file.content);
  3489. }
  3490. {
  3491. const auto &file = get_file_value(items, "file1");
  3492. EXPECT_EQ("hello.txt", file.filename);
  3493. EXPECT_EQ("text/plain", file.content_type);
  3494. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3495. }
  3496. {
  3497. const auto &file = get_file_value(items, "file2");
  3498. EXPECT_EQ("world.json", file.filename);
  3499. EXPECT_EQ("application/json", file.content_type);
  3500. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3501. }
  3502. {
  3503. const auto &file = get_file_value(items, "file3");
  3504. EXPECT_TRUE(file.filename.empty());
  3505. EXPECT_EQ("application/octet-stream", file.content_type);
  3506. EXPECT_EQ(0u, file.content.size());
  3507. }
  3508. } else {
  3509. std::string body;
  3510. content_reader([&](const char *data, size_t data_length) {
  3511. EXPECT_EQ(7U, data_length);
  3512. body.append(data, data_length);
  3513. return true;
  3514. });
  3515. EXPECT_EQ(body, "content");
  3516. res.set_content(body, "text/plain");
  3517. }
  3518. })
  3519. .Put("/content_receiver",
  3520. [&](const Request & /*req*/, Response &res,
  3521. const ContentReader &content_reader) {
  3522. std::string body;
  3523. content_reader([&](const char *data, size_t data_length) {
  3524. body.append(data, data_length);
  3525. return true;
  3526. });
  3527. EXPECT_EQ(body, "content");
  3528. res.set_content(body, "text/plain");
  3529. })
  3530. .Patch("/content_receiver",
  3531. [&](const Request & /*req*/, Response &res,
  3532. const ContentReader &content_reader) {
  3533. std::string body;
  3534. content_reader([&](const char *data, size_t data_length) {
  3535. body.append(data, data_length);
  3536. return true;
  3537. });
  3538. EXPECT_EQ(body, "content");
  3539. res.set_content(body, "text/plain");
  3540. })
  3541. .Post("/query-string-and-body",
  3542. [&](const Request &req, Response & /*res*/) {
  3543. ASSERT_TRUE(req.has_param("key"));
  3544. EXPECT_EQ(req.get_param_value("key"), "value");
  3545. EXPECT_EQ(req.body, "content");
  3546. })
  3547. .Get("/last-request",
  3548. [&](const Request &req, Response & /*res*/) {
  3549. EXPECT_EQ("close", req.get_header_value("Connection"));
  3550. })
  3551. .Get(R"(/redirect/(\d+))",
  3552. [&](const Request &req, Response &res) {
  3553. auto num = std::stoi(req.matches[1]) + 1;
  3554. std::string url = "/redirect/" + std::to_string(num);
  3555. res.set_redirect(url);
  3556. })
  3557. .Post("/binary",
  3558. [&](const Request &req, Response &res) {
  3559. EXPECT_EQ(4U, req.body.size());
  3560. EXPECT_EQ("application/octet-stream",
  3561. req.get_header_value("Content-Type"));
  3562. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3563. res.set_content(req.body, "application/octet-stream");
  3564. })
  3565. .Put("/binary",
  3566. [&](const Request &req, Response &res) {
  3567. EXPECT_EQ(4U, req.body.size());
  3568. EXPECT_EQ("application/octet-stream",
  3569. req.get_header_value("Content-Type"));
  3570. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3571. res.set_content(req.body, "application/octet-stream");
  3572. })
  3573. .Patch("/binary",
  3574. [&](const Request &req, Response &res) {
  3575. EXPECT_EQ(4U, req.body.size());
  3576. EXPECT_EQ("application/octet-stream",
  3577. req.get_header_value("Content-Type"));
  3578. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3579. res.set_content(req.body, "application/octet-stream");
  3580. })
  3581. .Delete("/binary",
  3582. [&](const Request &req, Response &res) {
  3583. EXPECT_EQ(4U, req.body.size());
  3584. EXPECT_EQ("application/octet-stream",
  3585. req.get_header_value("Content-Type"));
  3586. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3587. res.set_content(req.body, "application/octet-stream");
  3588. })
  3589. .Get("/issue1772",
  3590. [&](const Request & /*req*/, Response &res) {
  3591. res.status = 401;
  3592. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3593. })
  3594. .Delete("/issue609",
  3595. [](const httplib::Request &, httplib::Response &res,
  3596. const httplib::ContentReader &) {
  3597. res.set_content("ok", "text/plain");
  3598. })
  3599. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3600. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3601. .Get("/compress",
  3602. [&](const Request & /*req*/, Response &res) {
  3603. res.set_content(
  3604. "12345678901234567890123456789012345678901234567890123456789"
  3605. "01234567890123456789012345678901234567890",
  3606. "text/plain");
  3607. })
  3608. .Get("/compress-with-charset",
  3609. [&](const Request & /*req*/, Response &res) {
  3610. res.set_content(
  3611. "12345678901234567890123456789012345678901234567890123456789"
  3612. "01234567890123456789012345678901234567890",
  3613. "application/json; charset=utf-8");
  3614. })
  3615. .Get("/nocompress",
  3616. [&](const Request & /*req*/, Response &res) {
  3617. res.set_content(
  3618. "12345678901234567890123456789012345678901234567890123456789"
  3619. "01234567890123456789012345678901234567890",
  3620. "application/octet-stream");
  3621. })
  3622. .Post("/compress-multipart",
  3623. [&](const Request &req, Response & /*res*/) {
  3624. EXPECT_EQ(2u, req.form.fields.size());
  3625. ASSERT_TRUE(!req.form.has_field("???"));
  3626. {
  3627. const auto &text = req.form.get_field("key1");
  3628. EXPECT_EQ("test", text);
  3629. }
  3630. {
  3631. const auto &text = req.form.get_field("key2");
  3632. EXPECT_EQ("--abcdefg123", text);
  3633. }
  3634. })
  3635. #endif
  3636. ;
  3637. persons_["john"] = "programmer";
  3638. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3639. svr_.wait_until_ready();
  3640. }
  3641. virtual void TearDown() {
  3642. svr_.stop();
  3643. if (!request_threads_.empty()) {
  3644. std::this_thread::sleep_for(std::chrono::seconds(1));
  3645. for (auto &t : request_threads_) {
  3646. t.join();
  3647. }
  3648. }
  3649. t_.join();
  3650. }
  3651. map<string, string> persons_;
  3652. #ifdef CPPHTTPLIB_SSL_ENABLED
  3653. SSLClient cli_;
  3654. SSLServer svr_;
  3655. #else
  3656. Client cli_;
  3657. Server svr_;
  3658. #endif
  3659. thread t_;
  3660. std::vector<thread> request_threads_;
  3661. };
  3662. TEST_F(ServerTest, GetMethod200) {
  3663. auto res = cli_.Get("/hi");
  3664. ASSERT_TRUE(res);
  3665. EXPECT_EQ("HTTP/1.1", res->version);
  3666. EXPECT_EQ(StatusCode::OK_200, res->status);
  3667. EXPECT_EQ("OK", res->reason);
  3668. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3669. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3670. EXPECT_EQ("Hello World!", res->body);
  3671. }
  3672. TEST_F(ServerTest, GetEmptyFile) {
  3673. auto res = cli_.Get("/empty_file");
  3674. ASSERT_TRUE(res);
  3675. EXPECT_EQ(StatusCode::OK_200, res->status);
  3676. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3677. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3678. EXPECT_EQ("", res->body);
  3679. }
  3680. TEST_F(ServerTest, GetFileContent) {
  3681. auto res = cli_.Get("/file_content");
  3682. ASSERT_TRUE(res);
  3683. EXPECT_EQ(StatusCode::OK_200, res->status);
  3684. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3685. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3686. EXPECT_EQ("test.html", res->body);
  3687. }
  3688. TEST_F(ServerTest, GetFileContentWithRange) {
  3689. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3690. ASSERT_TRUE(res);
  3691. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3692. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3693. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3694. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3695. EXPECT_EQ("est", res->body);
  3696. }
  3697. TEST_F(ServerTest, GetFileContentWithContentType) {
  3698. auto res = cli_.Get("/file_content_with_content_type");
  3699. ASSERT_TRUE(res);
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3702. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3703. EXPECT_EQ("file\n", res->body);
  3704. }
  3705. TEST_F(ServerTest, GetInvalidFileContent) {
  3706. auto res = cli_.Get("/invalid_file_content");
  3707. ASSERT_TRUE(res);
  3708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3709. }
  3710. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3711. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3712. ASSERT_TRUE(res);
  3713. EXPECT_EQ("HTTP/1.1", res->version);
  3714. EXPECT_EQ(StatusCode::OK_200, res->status);
  3715. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3716. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3717. EXPECT_EQ("Hello World!", res->body);
  3718. }
  3719. TEST_F(ServerTest, GetMethod302) {
  3720. auto res = cli_.Get("/");
  3721. ASSERT_TRUE(res);
  3722. EXPECT_EQ(StatusCode::Found_302, res->status);
  3723. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3724. }
  3725. TEST_F(ServerTest, GetMethod302Redirect) {
  3726. cli_.set_follow_location(true);
  3727. auto res = cli_.Get("/");
  3728. ASSERT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::OK_200, res->status);
  3730. EXPECT_EQ("Hello World!", res->body);
  3731. EXPECT_EQ("/hi", res->location);
  3732. }
  3733. TEST_F(ServerTest, GetMethod404) {
  3734. auto res = cli_.Get("/invalid");
  3735. ASSERT_TRUE(res);
  3736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3737. }
  3738. TEST_F(ServerTest, HeadMethod200) {
  3739. auto res = cli_.Head("/hi");
  3740. ASSERT_TRUE(res);
  3741. EXPECT_EQ(StatusCode::OK_200, res->status);
  3742. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3743. EXPECT_TRUE(res->body.empty());
  3744. }
  3745. TEST_F(ServerTest, HeadMethod200Static) {
  3746. auto res = cli_.Head("/mount/dir/index.html");
  3747. ASSERT_TRUE(res);
  3748. EXPECT_EQ(StatusCode::OK_200, res->status);
  3749. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3750. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3751. EXPECT_TRUE(res->body.empty());
  3752. }
  3753. TEST_F(ServerTest, HeadMethod404) {
  3754. auto res = cli_.Head("/invalid");
  3755. ASSERT_TRUE(res);
  3756. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3757. EXPECT_TRUE(res->body.empty());
  3758. }
  3759. TEST_F(ServerTest, GetMethodPersonJohn) {
  3760. auto res = cli_.Get("/person/john");
  3761. ASSERT_TRUE(res);
  3762. EXPECT_EQ(StatusCode::OK_200, res->status);
  3763. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3764. EXPECT_EQ("programmer", res->body);
  3765. }
  3766. TEST_F(ServerTest, PostMethod1) {
  3767. auto res = cli_.Get("/person/john1");
  3768. ASSERT_TRUE(res);
  3769. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3770. res = cli_.Post("/person", "name=john1&note=coder",
  3771. "application/x-www-form-urlencoded");
  3772. ASSERT_TRUE(res);
  3773. ASSERT_EQ(StatusCode::OK_200, res->status);
  3774. res = cli_.Get("/person/john1");
  3775. ASSERT_TRUE(res);
  3776. ASSERT_EQ(StatusCode::OK_200, res->status);
  3777. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3778. ASSERT_EQ("coder", res->body);
  3779. }
  3780. TEST_F(ServerTest, PostMethod2) {
  3781. auto res = cli_.Get("/person/john2");
  3782. ASSERT_TRUE(res);
  3783. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3784. Params params;
  3785. params.emplace("name", "john2");
  3786. params.emplace("note", "coder");
  3787. res = cli_.Post("/person", params);
  3788. ASSERT_TRUE(res);
  3789. ASSERT_EQ(StatusCode::OK_200, res->status);
  3790. res = cli_.Get("/person/john2");
  3791. ASSERT_TRUE(res);
  3792. ASSERT_EQ(StatusCode::OK_200, res->status);
  3793. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3794. ASSERT_EQ("coder", res->body);
  3795. }
  3796. TEST_F(ServerTest, PutMethod3) {
  3797. auto res = cli_.Get("/person/john3");
  3798. ASSERT_TRUE(res);
  3799. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3800. Params params;
  3801. params.emplace("name", "john3");
  3802. params.emplace("note", "coder");
  3803. res = cli_.Put("/person", params);
  3804. ASSERT_TRUE(res);
  3805. ASSERT_EQ(StatusCode::OK_200, res->status);
  3806. res = cli_.Get("/person/john3");
  3807. ASSERT_TRUE(res);
  3808. ASSERT_EQ(StatusCode::OK_200, res->status);
  3809. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3810. ASSERT_EQ("coder", res->body);
  3811. }
  3812. TEST_F(ServerTest, DeleteMethod1) {
  3813. auto res = cli_.Get("/person/john4");
  3814. ASSERT_TRUE(res);
  3815. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3816. Params params;
  3817. params.emplace("name", "john4");
  3818. params.emplace("note", "coder");
  3819. res = cli_.Post("/person", params);
  3820. ASSERT_TRUE(res);
  3821. ASSERT_EQ(StatusCode::OK_200, res->status);
  3822. res = cli_.Get("/person/john4");
  3823. ASSERT_TRUE(res);
  3824. ASSERT_EQ(StatusCode::OK_200, res->status);
  3825. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3826. ASSERT_EQ("coder", res->body);
  3827. Params delete_params;
  3828. delete_params.emplace("name", "john4");
  3829. res = cli_.Delete("/person", delete_params);
  3830. ASSERT_TRUE(res);
  3831. ASSERT_EQ(StatusCode::OK_200, res->status);
  3832. ASSERT_EQ("DELETED", res->body);
  3833. res = cli_.Get("/person/john4");
  3834. ASSERT_TRUE(res);
  3835. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3836. }
  3837. TEST_F(ServerTest, DeleteMethod2) {
  3838. auto res = cli_.Get("/person/john5");
  3839. ASSERT_TRUE(res);
  3840. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3841. Params params;
  3842. params.emplace("name", "john5");
  3843. params.emplace("note", "developer");
  3844. res = cli_.Post("/person", params);
  3845. ASSERT_TRUE(res);
  3846. ASSERT_EQ(StatusCode::OK_200, res->status);
  3847. res = cli_.Get("/person/john5");
  3848. ASSERT_TRUE(res);
  3849. ASSERT_EQ(StatusCode::OK_200, res->status);
  3850. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3851. ASSERT_EQ("developer", res->body);
  3852. Params delete_params;
  3853. delete_params.emplace("name", "john5");
  3854. Headers headers;
  3855. headers.emplace("Custom-Header", "test-value");
  3856. res = cli_.Delete("/person", headers, delete_params);
  3857. ASSERT_TRUE(res);
  3858. ASSERT_EQ(StatusCode::OK_200, res->status);
  3859. ASSERT_EQ("DELETED", res->body);
  3860. res = cli_.Get("/person/john5");
  3861. ASSERT_TRUE(res);
  3862. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3863. }
  3864. TEST_F(ServerTest, DeleteMethod3) {
  3865. auto res = cli_.Get("/person/john6");
  3866. ASSERT_TRUE(res);
  3867. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3868. Params params;
  3869. params.emplace("name", "john6");
  3870. params.emplace("note", "tester");
  3871. res = cli_.Post("/person", params);
  3872. ASSERT_TRUE(res);
  3873. ASSERT_EQ(StatusCode::OK_200, res->status);
  3874. res = cli_.Get("/person/john6");
  3875. ASSERT_TRUE(res);
  3876. ASSERT_EQ(StatusCode::OK_200, res->status);
  3877. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3878. ASSERT_EQ("tester", res->body);
  3879. Params delete_params;
  3880. delete_params.emplace("name", "john6");
  3881. Headers headers;
  3882. headers.emplace("Custom-Header", "test-value");
  3883. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3884. ASSERT_TRUE(res);
  3885. ASSERT_EQ(StatusCode::OK_200, res->status);
  3886. ASSERT_EQ("DELETED", res->body);
  3887. res = cli_.Get("/person/john6");
  3888. ASSERT_TRUE(res);
  3889. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3890. }
  3891. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3892. Params params;
  3893. params.emplace("json", JSON_DATA);
  3894. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3895. ASSERT_TRUE(res);
  3896. ASSERT_EQ(StatusCode::OK_200, res->status);
  3897. ASSERT_EQ(JSON_DATA, res->body);
  3898. }
  3899. TEST_F(ServerTest, PostEmptyContent) {
  3900. auto res = cli_.Post("/empty", "", "text/plain");
  3901. ASSERT_TRUE(res);
  3902. ASSERT_EQ(StatusCode::OK_200, res->status);
  3903. ASSERT_EQ("empty", res->body);
  3904. }
  3905. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3906. auto res = cli_.Post("/empty-no-content-type");
  3907. ASSERT_TRUE(res);
  3908. ASSERT_EQ(StatusCode::OK_200, res->status);
  3909. ASSERT_EQ("empty-no-content-type", res->body);
  3910. }
  3911. TEST_F(ServerTest, PostPathOnly) {
  3912. auto res = cli_.Post("/path-only");
  3913. ASSERT_TRUE(res);
  3914. ASSERT_EQ(StatusCode::OK_200, res->status);
  3915. ASSERT_EQ("path-only", res->body);
  3916. }
  3917. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3918. auto res = cli_.Post("/path-headers-only",
  3919. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3920. ASSERT_TRUE(res);
  3921. ASSERT_EQ(StatusCode::OK_200, res->status);
  3922. ASSERT_EQ("path-headers-only", res->body);
  3923. }
  3924. TEST_F(ServerTest, PostLarge) {
  3925. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3926. ASSERT_TRUE(res);
  3927. ASSERT_EQ(StatusCode::OK_200, res->status);
  3928. EXPECT_EQ(LARGE_DATA, res->body);
  3929. }
  3930. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3931. auto res = cli_.Put("/empty-no-content-type");
  3932. ASSERT_TRUE(res);
  3933. ASSERT_EQ(StatusCode::OK_200, res->status);
  3934. ASSERT_EQ("empty-no-content-type", res->body);
  3935. }
  3936. TEST_F(ServerTest, GetMethodDir) {
  3937. auto res = cli_.Get("/dir/");
  3938. ASSERT_TRUE(res);
  3939. EXPECT_EQ(StatusCode::OK_200, res->status);
  3940. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3941. auto body = R"(<html>
  3942. <head>
  3943. </head>
  3944. <body>
  3945. <a href="/dir/test.html">Test</a>
  3946. <a href="/hi">hi</a>
  3947. </body>
  3948. </html>
  3949. )";
  3950. EXPECT_EQ(body, res->body);
  3951. }
  3952. TEST_F(ServerTest, GetMethodDirTest) {
  3953. auto res = cli_.Get("/dir/test.html");
  3954. ASSERT_TRUE(res);
  3955. EXPECT_EQ(StatusCode::OK_200, res->status);
  3956. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3957. EXPECT_EQ("test.html", res->body);
  3958. }
  3959. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3960. auto res = cli_.Get("/dir/../dir/test.html");
  3961. ASSERT_TRUE(res);
  3962. EXPECT_EQ(StatusCode::OK_200, res->status);
  3963. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3964. EXPECT_EQ("test.html", res->body);
  3965. }
  3966. TEST_F(ServerTest, GetMethodInvalidPath) {
  3967. auto res = cli_.Get("/dir/../test.html");
  3968. ASSERT_TRUE(res);
  3969. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3970. }
  3971. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3972. auto res = cli_.Get("/../www/dir/test.html");
  3973. ASSERT_TRUE(res);
  3974. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3975. }
  3976. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3977. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3978. ASSERT_TRUE(res);
  3979. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3980. }
  3981. TEST_F(ServerTest, GetMethodDirMountTest) {
  3982. auto res = cli_.Get("/mount/dir/test.html");
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::OK_200, res->status);
  3985. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3986. EXPECT_EQ("test.html", res->body);
  3987. }
  3988. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3989. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3990. ASSERT_TRUE(res);
  3991. EXPECT_EQ(StatusCode::OK_200, res->status);
  3992. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3993. EXPECT_EQ("test.html", res->body);
  3994. }
  3995. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3996. auto res = cli_.Get("/mount/dir/../test.html");
  3997. ASSERT_TRUE(res);
  3998. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3999. }
  4000. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4001. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4002. ASSERT_TRUE(res);
  4003. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4004. }
  4005. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4006. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4007. ASSERT_TRUE(res);
  4008. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4009. }
  4010. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4011. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4012. ASSERT_TRUE(res);
  4013. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4014. }
  4015. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4016. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4017. ASSERT_TRUE(res);
  4018. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4019. }
  4020. TEST_F(ServerTest, PostMethod303) {
  4021. auto res = cli_.Post("/1", "body", "text/plain");
  4022. ASSERT_TRUE(res);
  4023. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4024. EXPECT_EQ("/2", res->get_header_value("Location"));
  4025. }
  4026. TEST_F(ServerTest, PostMethod303Redirect) {
  4027. cli_.set_follow_location(true);
  4028. auto res = cli_.Post("/1", "body", "text/plain");
  4029. ASSERT_TRUE(res);
  4030. EXPECT_EQ(StatusCode::OK_200, res->status);
  4031. EXPECT_EQ("redirected.", res->body);
  4032. EXPECT_EQ("/2", res->location);
  4033. }
  4034. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4035. auto res = cli_.Get("/dir/test.abcde");
  4036. ASSERT_TRUE(res);
  4037. EXPECT_EQ(StatusCode::OK_200, res->status);
  4038. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4039. EXPECT_EQ("abcde", res->body);
  4040. }
  4041. TEST_F(ServerTest, StaticFileRange) {
  4042. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4043. ASSERT_TRUE(res);
  4044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4045. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4046. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4047. EXPECT_EQ(true, res->has_header("Content-Range"));
  4048. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4049. EXPECT_EQ(std::string("cd"), res->body);
  4050. }
  4051. TEST_F(ServerTest, StaticFileRanges) {
  4052. auto res =
  4053. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  4054. ASSERT_TRUE(res);
  4055. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4056. EXPECT_TRUE(
  4057. res->get_header_value("Content-Type")
  4058. .find(
  4059. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4060. 0);
  4061. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4062. }
  4063. TEST_F(ServerTest, StaticFileRangeHead) {
  4064. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4065. ASSERT_TRUE(res);
  4066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4067. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4068. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4069. EXPECT_EQ(true, res->has_header("Content-Range"));
  4070. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4071. }
  4072. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4073. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  4074. ASSERT_TRUE(res);
  4075. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4076. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4077. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4078. EXPECT_EQ(true, res->has_header("Content-Range"));
  4079. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4080. res->get_header_value("Content-Range"));
  4081. EXPECT_EQ("LAST\n", res->body);
  4082. }
  4083. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4084. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  4085. ASSERT_TRUE(res);
  4086. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4088. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4089. EXPECT_EQ(true, res->has_header("Content-Range"));
  4090. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4091. }
  4092. TEST_F(ServerTest, StaticFileBigFile) {
  4093. auto res = cli_.Get("/dir/1MB.txt");
  4094. ASSERT_TRUE(res);
  4095. EXPECT_EQ(StatusCode::OK_200, res->status);
  4096. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4097. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4098. }
  4099. TEST_F(ServerTest, InvalidBaseDirMount) {
  4100. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4101. }
  4102. TEST_F(ServerTest, Binary) {
  4103. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4104. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4105. "application/octet-stream");
  4106. ASSERT_TRUE(res);
  4107. ASSERT_EQ(StatusCode::OK_200, res->status);
  4108. ASSERT_EQ(4U, res->body.size());
  4109. res = cli_.Put("/binary", binary.data(), binary.size(),
  4110. "application/octet-stream");
  4111. ASSERT_TRUE(res);
  4112. ASSERT_EQ(StatusCode::OK_200, res->status);
  4113. ASSERT_EQ(4U, res->body.size());
  4114. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4115. "application/octet-stream");
  4116. ASSERT_TRUE(res);
  4117. ASSERT_EQ(StatusCode::OK_200, res->status);
  4118. ASSERT_EQ(4U, res->body.size());
  4119. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4120. "application/octet-stream");
  4121. ASSERT_TRUE(res);
  4122. ASSERT_EQ(StatusCode::OK_200, res->status);
  4123. ASSERT_EQ(4U, res->body.size());
  4124. }
  4125. TEST_F(ServerTest, BinaryString) {
  4126. auto binary = std::string("\x00\x01\x02\x03", 4);
  4127. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4128. ASSERT_TRUE(res);
  4129. ASSERT_EQ(StatusCode::OK_200, res->status);
  4130. ASSERT_EQ(4U, res->body.size());
  4131. res = cli_.Put("/binary", binary, "application/octet-stream");
  4132. ASSERT_TRUE(res);
  4133. ASSERT_EQ(StatusCode::OK_200, res->status);
  4134. ASSERT_EQ(4U, res->body.size());
  4135. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4136. ASSERT_TRUE(res);
  4137. ASSERT_EQ(StatusCode::OK_200, res->status);
  4138. ASSERT_EQ(4U, res->body.size());
  4139. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4140. ASSERT_TRUE(res);
  4141. ASSERT_EQ(StatusCode::OK_200, res->status);
  4142. ASSERT_EQ(4U, res->body.size());
  4143. }
  4144. TEST_F(ServerTest, EmptyRequest) {
  4145. auto res = cli_.Get("");
  4146. ASSERT_TRUE(!res);
  4147. EXPECT_EQ(Error::Connection, res.error());
  4148. }
  4149. TEST_F(ServerTest, LongRequest) {
  4150. std::string request;
  4151. for (size_t i = 0; i < 545; i++) {
  4152. request += "/TooLongRequest";
  4153. }
  4154. request += "OK";
  4155. auto res = cli_.Get(request.c_str());
  4156. ASSERT_TRUE(res);
  4157. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4158. }
  4159. TEST_F(ServerTest, TooLongRequest) {
  4160. std::string request;
  4161. for (size_t i = 0; i < 546; i++) {
  4162. request += "/TooLongRequest";
  4163. }
  4164. request += "_NG";
  4165. auto start = std::chrono::high_resolution_clock::now();
  4166. cli_.set_keep_alive(true);
  4167. auto res = cli_.Get(request.c_str());
  4168. auto end = std::chrono::high_resolution_clock::now();
  4169. auto elapsed =
  4170. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4171. .count();
  4172. ASSERT_TRUE(res);
  4173. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4174. EXPECT_LE(elapsed, 1000);
  4175. EXPECT_EQ("close", res->get_header_value("Connection"));
  4176. EXPECT_FALSE(cli_.is_socket_open());
  4177. }
  4178. TEST_F(ServerTest, AlmostTooLongRequest) {
  4179. // test for #2046 - URI length check shouldn't include other content on req
  4180. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4181. // leading /, space, HTTP/1.1)
  4182. std::string request =
  4183. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4184. auto res = cli_.Get(request.c_str());
  4185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4187. }
  4188. TEST_F(ServerTest, LongHeader) {
  4189. Request req;
  4190. req.method = "GET";
  4191. req.path = "/hi";
  4192. std::string host_and_port;
  4193. host_and_port += HOST;
  4194. host_and_port += ":";
  4195. host_and_port += std::to_string(PORT);
  4196. req.headers.emplace("Host", host_and_port.c_str());
  4197. req.headers.emplace("Accept", "*/*");
  4198. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4199. req.headers.emplace(
  4200. "Header-Name",
  4201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4227. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4228. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4229. "@@@@@@@@@@@@@@@@");
  4230. auto res = std::make_shared<Response>();
  4231. auto error = Error::Success;
  4232. auto ret = cli_.send(req, *res, error);
  4233. ASSERT_TRUE(ret);
  4234. EXPECT_EQ(StatusCode::OK_200, res->status);
  4235. }
  4236. TEST_F(ServerTest, LongQueryValue) {
  4237. auto start = std::chrono::high_resolution_clock::now();
  4238. cli_.set_keep_alive(true);
  4239. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4240. auto end = std::chrono::high_resolution_clock::now();
  4241. auto elapsed =
  4242. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4243. .count();
  4244. ASSERT_TRUE(res);
  4245. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4246. EXPECT_LE(elapsed, 1000);
  4247. EXPECT_EQ("close", res->get_header_value("Connection"));
  4248. EXPECT_FALSE(cli_.is_socket_open());
  4249. }
  4250. TEST_F(ServerTest, TooLongQueryValue) {
  4251. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4252. ASSERT_FALSE(res);
  4253. EXPECT_EQ(Error::Read, res.error());
  4254. }
  4255. TEST_F(ServerTest, TooLongHeader) {
  4256. Request req;
  4257. req.method = "GET";
  4258. req.path = "/hi";
  4259. std::string host_and_port;
  4260. host_and_port += HOST;
  4261. host_and_port += ":";
  4262. host_and_port += std::to_string(PORT);
  4263. req.headers.emplace("Host", host_and_port.c_str());
  4264. req.headers.emplace("Accept", "*/*");
  4265. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4266. req.headers.emplace(
  4267. "Header-Name",
  4268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4275. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4276. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4286. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4296. "@@@@@@@@@@@@@@@@@");
  4297. auto res = std::make_shared<Response>();
  4298. auto error = Error::Success;
  4299. auto ret = cli_.send(req, *res, error);
  4300. ASSERT_TRUE(ret);
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. }
  4303. TEST_F(ServerTest, HeaderCountAtLimit) {
  4304. // Test with headers just under the 100 limit
  4305. httplib::Headers headers;
  4306. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4307. // This should keep us just under the 100 header limit
  4308. for (int i = 0; i < 95; i++) {
  4309. std::string name = "X-Test-Header-" + std::to_string(i);
  4310. std::string value = "value" + std::to_string(i);
  4311. headers.emplace(name, value);
  4312. }
  4313. // This should work fine as we're under the limit
  4314. auto res = cli_.Get("/hi", headers);
  4315. EXPECT_TRUE(res);
  4316. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4317. }
  4318. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4319. // Test with many headers to exceed the 100 limit
  4320. httplib::Headers headers;
  4321. // Add 150 headers to definitely exceed the 100 limit
  4322. for (int i = 0; i < 150; i++) {
  4323. std::string name = "X-Test-Header-" + std::to_string(i);
  4324. std::string value = "value" + std::to_string(i);
  4325. headers.emplace(name, value);
  4326. }
  4327. // This should fail due to exceeding header count limit
  4328. cli_.set_keep_alive(true);
  4329. auto res = cli_.Get("/hi", headers);
  4330. // The server should respond with 400 Bad Request
  4331. ASSERT_TRUE(res);
  4332. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4333. EXPECT_EQ("close", res->get_header_value("Connection"));
  4334. EXPECT_FALSE(cli_.is_socket_open());
  4335. }
  4336. TEST_F(ServerTest, PercentEncoding) {
  4337. auto res = cli_.Get("/e%6edwith%");
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::OK_200, res->status);
  4340. }
  4341. TEST_F(ServerTest, PercentEncodingUnicode) {
  4342. auto res = cli_.Get("/e%u006edwith%");
  4343. ASSERT_TRUE(res);
  4344. EXPECT_EQ(StatusCode::OK_200, res->status);
  4345. }
  4346. TEST_F(ServerTest, InvalidPercentEncoding) {
  4347. auto res = cli_.Get("/%endwith%");
  4348. ASSERT_TRUE(res);
  4349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4350. }
  4351. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4352. auto res = cli_.Get("/%uendwith%");
  4353. ASSERT_TRUE(res);
  4354. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4355. }
  4356. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4357. auto res = cli_.Get("/hello?aaa=bbb%");
  4358. ASSERT_TRUE(res);
  4359. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4360. }
  4361. TEST_F(ServerTest, PlusSignEncoding) {
  4362. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4363. ASSERT_TRUE(res);
  4364. EXPECT_EQ(StatusCode::OK_200, res->status);
  4365. EXPECT_EQ("a +b", res->body);
  4366. }
  4367. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4368. // This test simulates a potential DoS attack using many headers
  4369. // to verify our security fix prevents memory exhaustion
  4370. httplib::Headers attack_headers;
  4371. // Attempt to add many headers like an attacker would (200 headers to far
  4372. // exceed limit)
  4373. for (int i = 0; i < 200; i++) {
  4374. std::string name = "X-Attack-Header-" + std::to_string(i);
  4375. std::string value = "attack_payload_" + std::to_string(i);
  4376. attack_headers.emplace(name, value);
  4377. }
  4378. // Try to POST with excessive headers
  4379. cli_.set_keep_alive(true);
  4380. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4381. // Should either fail or return 400 Bad Request due to security limit
  4382. if (res) {
  4383. // If we get a response, it should be 400 Bad Request
  4384. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4385. EXPECT_EQ("close", res->get_header_value("Connection"));
  4386. }
  4387. EXPECT_FALSE(cli_.is_socket_open());
  4388. }
  4389. TEST_F(ServerTest, MultipartFormData) {
  4390. UploadFormDataItems items = {
  4391. {"text1", "text default", "", ""},
  4392. {"text2", "aωb", "", ""},
  4393. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4394. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4395. {"file3", "", "", "application/octet-stream"},
  4396. {"file4", "", "", " application/json tmp-string "}};
  4397. auto res = cli_.Post("/multipart", items);
  4398. ASSERT_TRUE(res);
  4399. EXPECT_EQ(StatusCode::OK_200, res->status);
  4400. }
  4401. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4402. UploadFormDataItems items = {
  4403. {"text", "default text", "", ""},
  4404. {"multi_text1", "aaaaa", "", ""},
  4405. {"multi_text1", "bbbbb", "", ""},
  4406. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4407. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4408. "application/json"},
  4409. };
  4410. auto res = cli_.Post("/multipart/multi_file_values", items);
  4411. ASSERT_TRUE(res);
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. }
  4414. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4415. auto res = cli_.Get("/hi");
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::OK_200, res->status);
  4418. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4419. EXPECT_EQ("Hello World!", res->body);
  4420. }
  4421. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4422. Request req;
  4423. req.method = "POST";
  4424. req.path = "/chunked";
  4425. std::string host_and_port;
  4426. host_and_port += HOST;
  4427. host_and_port += ":";
  4428. host_and_port += std::to_string(PORT);
  4429. req.headers.emplace("Host", host_and_port.c_str());
  4430. req.headers.emplace("Accept", "*/*");
  4431. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4432. req.headers.emplace("Content-Type", "text/plain");
  4433. req.headers.emplace("Content-Length", "0");
  4434. req.headers.emplace(
  4435. "Transfer-Encoding",
  4436. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4437. // Client does not chunk, so make a chunked body manually.
  4438. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4439. auto res = std::make_shared<Response>();
  4440. auto error = Error::Success;
  4441. auto ret = cli_.send(req, *res, error);
  4442. ASSERT_TRUE(ret);
  4443. EXPECT_EQ(StatusCode::OK_200, res->status);
  4444. }
  4445. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4446. // rather than treat them as valid lengths.
  4447. template <typename ClientT>
  4448. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4449. Request req;
  4450. req.method = "POST";
  4451. req.path = "/chunked";
  4452. std::string host_and_port;
  4453. host_and_port += HOST;
  4454. host_and_port += ":";
  4455. host_and_port += std::to_string(PORT);
  4456. req.headers.emplace("Host", host_and_port.c_str());
  4457. req.headers.emplace("Content-Length", "0");
  4458. req.headers.emplace("Transfer-Encoding", "chunked");
  4459. req.body = body;
  4460. auto res = std::make_shared<Response>();
  4461. auto error = Error::Success;
  4462. ASSERT_TRUE(cli.send(req, *res, error));
  4463. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4464. }
  4465. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4466. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4467. }
  4468. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4469. expect_chunked_body_rejected(
  4470. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4471. }
  4472. TEST_F(ServerTest, GetStreamed2) {
  4473. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4474. ASSERT_TRUE(res);
  4475. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4476. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4477. EXPECT_EQ(true, res->has_header("Content-Range"));
  4478. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4479. EXPECT_EQ(std::string("ab"), res->body);
  4480. }
  4481. TEST_F(ServerTest, GetStreamed) {
  4482. auto res = cli_.Get("/streamed");
  4483. ASSERT_TRUE(res);
  4484. EXPECT_EQ(StatusCode::OK_200, res->status);
  4485. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4486. EXPECT_EQ(std::string("aaabbb"), res->body);
  4487. }
  4488. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4489. auto res =
  4490. cli_.Get("/streamed-without-length", {make_range_header({{0, -1}})});
  4491. ASSERT_TRUE(res);
  4492. EXPECT_EQ(StatusCode::OK_200, res->status);
  4493. EXPECT_EQ(false, res->has_header("Content-Length"));
  4494. EXPECT_EQ(false, res->has_header("Content-Range"));
  4495. EXPECT_EQ(std::string("abcdefg"), res->body);
  4496. }
  4497. TEST_F(ServerTest, GetStreamedWithRange1) {
  4498. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4499. ASSERT_TRUE(res);
  4500. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4501. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4502. EXPECT_EQ(true, res->has_header("Content-Range"));
  4503. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4504. EXPECT_EQ(std::string("def"), res->body);
  4505. }
  4506. TEST_F(ServerTest, GetStreamedWithRange2) {
  4507. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4508. ASSERT_TRUE(res);
  4509. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4510. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4511. EXPECT_EQ(true, res->has_header("Content-Range"));
  4512. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4513. EXPECT_EQ(std::string("bcdefg"), res->body);
  4514. }
  4515. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4516. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4517. ASSERT_TRUE(res);
  4518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4519. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4520. EXPECT_EQ(true, res->has_header("Content-Range"));
  4521. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4522. EXPECT_EQ(std::string("efg"), res->body);
  4523. }
  4524. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4525. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4526. ASSERT_TRUE(res);
  4527. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4528. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4529. EXPECT_EQ(false, res->has_header("Content-Range"));
  4530. EXPECT_EQ(0U, res->body.size());
  4531. }
  4532. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4533. auto res = cli_.Get("/streamed-with-range",
  4534. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4535. "92233720368547758079223372036854775807"}});
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4538. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4539. EXPECT_EQ(false, res->has_header("Content-Range"));
  4540. EXPECT_EQ(0U, res->body.size());
  4541. }
  4542. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4543. auto res = cli_.Get(
  4544. "/with-range",
  4545. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4546. {"Accept-Encoding", ""}});
  4547. ASSERT_TRUE(res);
  4548. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4549. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4550. EXPECT_EQ(true, res->has_header("Content-Range"));
  4551. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4552. EXPECT_EQ(std::string("abcdefg"), res->body);
  4553. }
  4554. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4555. auto res = cli_.Get("/with-range", {
  4556. {"Range", "bytes=0-"},
  4557. {"Accept-Encoding", ""},
  4558. });
  4559. ASSERT_TRUE(res);
  4560. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4561. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4562. EXPECT_EQ(true, res->has_header("Content-Range"));
  4563. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4564. EXPECT_EQ(std::string("abcdefg"), res->body);
  4565. }
  4566. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4567. auto res =
  4568. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4569. ASSERT_TRUE(res);
  4570. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4571. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4572. EXPECT_EQ(false, res->has_header("Content-Range"));
  4573. EXPECT_EQ(267U, res->body.size());
  4574. // Check that both range contents are present
  4575. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4576. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4577. // Check that Content-Range headers are present for both ranges
  4578. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4579. std::string::npos);
  4580. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4581. std::string::npos);
  4582. }
  4583. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4584. Ranges ranges;
  4585. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4586. ranges.emplace_back(0, -1);
  4587. }
  4588. auto res =
  4589. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4590. ASSERT_TRUE(res);
  4591. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4592. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4593. EXPECT_EQ(false, res->has_header("Content-Range"));
  4594. EXPECT_EQ(0U, res->body.size());
  4595. }
  4596. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4597. auto res =
  4598. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4599. ASSERT_TRUE(res);
  4600. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4601. EXPECT_EQ(5U, res->body.size());
  4602. // Check that overlapping ranges are coalesced into a single range
  4603. EXPECT_EQ("bcdef", res->body);
  4604. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4605. // Should be single range, not multipart
  4606. EXPECT_TRUE(res->has_header("Content-Range"));
  4607. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4608. }
  4609. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4610. auto res =
  4611. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4612. ASSERT_TRUE(res);
  4613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4614. EXPECT_EQ(268U, res->body.size());
  4615. // Check that both range contents are present
  4616. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4617. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4618. // Check that Content-Range headers are present for both ranges
  4619. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4620. std::string::npos);
  4621. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4622. std::string::npos);
  4623. }
  4624. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4625. auto res =
  4626. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4627. ASSERT_TRUE(res);
  4628. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4629. EXPECT_EQ(269U, res->body.size());
  4630. // Check that both duplicate range contents are present
  4631. size_t first_abc = res->body.find("abc\r\n");
  4632. EXPECT_TRUE(first_abc != std::string::npos);
  4633. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4634. EXPECT_TRUE(second_abc != std::string::npos);
  4635. // Check that Content-Range headers are present for both ranges
  4636. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4637. EXPECT_TRUE(first_range != std::string::npos);
  4638. size_t second_range =
  4639. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4640. EXPECT_TRUE(second_range != std::string::npos);
  4641. }
  4642. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4643. auto res = cli_.Get("/streamed-with-range?error",
  4644. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4645. ASSERT_TRUE(res);
  4646. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4647. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4648. EXPECT_EQ(false, res->has_header("Content-Range"));
  4649. EXPECT_EQ(0U, res->body.size());
  4650. }
  4651. TEST_F(ServerTest, GetStreamedEndless) {
  4652. uint64_t offset = 0;
  4653. auto res = cli_.Get("/streamed-cancel",
  4654. [&](const char * /*data*/, uint64_t data_length) {
  4655. if (offset < 100) {
  4656. offset += data_length;
  4657. return true;
  4658. }
  4659. return false;
  4660. });
  4661. ASSERT_TRUE(!res);
  4662. EXPECT_EQ(Error::Canceled, res.error());
  4663. }
  4664. TEST_F(ServerTest, ClientStop) {
  4665. std::atomic_size_t count{4};
  4666. std::vector<std::thread> threads;
  4667. for (auto i = count.load(); i != 0; --i) {
  4668. threads.emplace_back([&]() {
  4669. auto res = cli_.Get("/streamed-cancel",
  4670. [&](const char *, uint64_t) { return true; });
  4671. --count;
  4672. ASSERT_TRUE(!res);
  4673. EXPECT_TRUE(res.error() == Error::Canceled ||
  4674. res.error() == Error::Read || res.error() == Error::Write);
  4675. });
  4676. }
  4677. std::this_thread::sleep_for(std::chrono::seconds(2));
  4678. while (count != 0) {
  4679. cli_.stop();
  4680. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4681. }
  4682. for (auto &t : threads) {
  4683. t.join();
  4684. }
  4685. }
  4686. TEST_F(ServerTest, GetWithRange1) {
  4687. auto res = cli_.Get("/with-range", {
  4688. make_range_header({{3, 5}}),
  4689. {"Accept-Encoding", ""},
  4690. });
  4691. ASSERT_TRUE(res);
  4692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4693. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4694. EXPECT_EQ(true, res->has_header("Content-Range"));
  4695. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4696. EXPECT_EQ(std::string("def"), res->body);
  4697. }
  4698. TEST_F(ServerTest, GetWithRange2) {
  4699. auto res = cli_.Get("/with-range", {
  4700. make_range_header({{1, -1}}),
  4701. {"Accept-Encoding", ""},
  4702. });
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4705. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4706. EXPECT_EQ(true, res->has_header("Content-Range"));
  4707. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4708. EXPECT_EQ(std::string("bcdefg"), res->body);
  4709. }
  4710. TEST_F(ServerTest, GetWithRange3) {
  4711. auto res = cli_.Get("/with-range", {
  4712. make_range_header({{0, 0}}),
  4713. {"Accept-Encoding", ""},
  4714. });
  4715. ASSERT_TRUE(res);
  4716. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4717. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4718. EXPECT_EQ(true, res->has_header("Content-Range"));
  4719. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4720. EXPECT_EQ(std::string("a"), res->body);
  4721. }
  4722. TEST_F(ServerTest, GetWithRange4) {
  4723. auto res = cli_.Get("/with-range", {
  4724. make_range_header({{-1, 2}}),
  4725. {"Accept-Encoding", ""},
  4726. });
  4727. ASSERT_TRUE(res);
  4728. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4729. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4730. EXPECT_EQ(true, res->has_header("Content-Range"));
  4731. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4732. EXPECT_EQ(std::string("fg"), res->body);
  4733. }
  4734. TEST_F(ServerTest, GetWithRange5) {
  4735. auto res = cli_.Get("/with-range", {
  4736. make_range_header({{0, 5}}),
  4737. {"Accept-Encoding", ""},
  4738. });
  4739. ASSERT_TRUE(res);
  4740. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4741. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4742. EXPECT_EQ(true, res->has_header("Content-Range"));
  4743. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4744. EXPECT_EQ(std::string("abcdef"), res->body);
  4745. }
  4746. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4747. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4748. ASSERT_TRUE(res);
  4749. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4750. }
  4751. TEST_F(ServerTest, GetWithRangeMultipart) {
  4752. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4753. ASSERT_TRUE(res);
  4754. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4755. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4756. EXPECT_EQ(false, res->has_header("Content-Range"));
  4757. EXPECT_EQ(267U, res->body.size());
  4758. }
  4759. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4760. auto res =
  4761. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4762. ASSERT_TRUE(res);
  4763. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4764. }
  4765. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4766. auto res = cli_.Get("/with-range-customized-response",
  4767. {{make_range_header({{1, 2}})}});
  4768. ASSERT_TRUE(res);
  4769. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4770. EXPECT_EQ(true, res->has_header("Content-Length"));
  4771. EXPECT_EQ(false, res->has_header("Content-Range"));
  4772. EXPECT_EQ(JSON_DATA, res->body);
  4773. }
  4774. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4775. auto res = cli_.Get("/with-range-customized-response",
  4776. {{make_range_header({{1, 2}, {4, 5}})}});
  4777. ASSERT_TRUE(res);
  4778. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4779. EXPECT_EQ(true, res->has_header("Content-Length"));
  4780. EXPECT_EQ(false, res->has_header("Content-Range"));
  4781. EXPECT_EQ(JSON_DATA, res->body);
  4782. }
  4783. TEST_F(ServerTest, Issue1772) {
  4784. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4785. ASSERT_TRUE(res);
  4786. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4787. }
  4788. TEST_F(ServerTest, Issue609) {
  4789. auto res = cli_.Delete("/issue609");
  4790. ASSERT_TRUE(res);
  4791. EXPECT_EQ(StatusCode::OK_200, res->status);
  4792. EXPECT_EQ(std::string("ok"), res->body);
  4793. }
  4794. TEST_F(ServerTest, GetStreamedChunked) {
  4795. auto res = cli_.Get("/streamed-chunked");
  4796. ASSERT_TRUE(res);
  4797. EXPECT_EQ(StatusCode::OK_200, res->status);
  4798. EXPECT_EQ(std::string("123456789"), res->body);
  4799. }
  4800. TEST_F(ServerTest, GetStreamedChunked2) {
  4801. auto res = cli_.Get("/streamed-chunked2");
  4802. ASSERT_TRUE(res);
  4803. EXPECT_EQ(StatusCode::OK_200, res->status);
  4804. EXPECT_EQ(std::string("123456789"), res->body);
  4805. }
  4806. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4807. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. EXPECT_EQ(std::string("123456789"), res->body);
  4811. EXPECT_TRUE(res->has_header("Trailer"));
  4812. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4813. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4814. // Trailers are now stored separately from headers (security fix)
  4815. EXPECT_EQ(2U, res->trailers.size());
  4816. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4817. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4818. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4819. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4820. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4821. // Verify trailers are NOT in headers (security verification)
  4822. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4823. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4824. }
  4825. TEST_F(ServerTest, LargeChunkedPost) {
  4826. Request req;
  4827. req.method = "POST";
  4828. req.path = "/large-chunked";
  4829. std::string host_and_port;
  4830. host_and_port += HOST;
  4831. host_and_port += ":";
  4832. host_and_port += std::to_string(PORT);
  4833. req.headers.emplace("Host", host_and_port.c_str());
  4834. req.headers.emplace("Accept", "*/*");
  4835. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4836. req.headers.emplace("Content-Type", "text/plain");
  4837. req.headers.emplace("Content-Length", "0");
  4838. req.headers.emplace("Transfer-Encoding", "chunked");
  4839. std::string long_string(30 * 1024u, 'a');
  4840. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4841. // Attempt to make a large enough post to exceed OS buffers, to test that
  4842. // the server handles short reads if the full chunk data isn't available.
  4843. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4844. auto res = std::make_shared<Response>();
  4845. auto error = Error::Success;
  4846. auto ret = cli_.send(req, *res, error);
  4847. ASSERT_TRUE(ret);
  4848. EXPECT_EQ(StatusCode::OK_200, res->status);
  4849. }
  4850. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4851. auto res = cli_.Get("/remote_addr");
  4852. ASSERT_TRUE(res);
  4853. EXPECT_EQ(StatusCode::OK_200, res->status);
  4854. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4855. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4856. }
  4857. TEST_F(ServerTest, GetMethodLocalAddr) {
  4858. auto res = cli_.Get("/local_addr");
  4859. ASSERT_TRUE(res);
  4860. EXPECT_EQ(StatusCode::OK_200, res->status);
  4861. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4862. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4863. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4864. }
  4865. TEST_F(ServerTest, HTTPResponseSplitting) {
  4866. auto res = cli_.Get("/http_response_splitting");
  4867. ASSERT_TRUE(res);
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. }
  4870. TEST_F(ServerTest, SlowRequest) {
  4871. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4872. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4873. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4874. }
  4875. #if 0
  4876. TEST_F(ServerTest, SlowPost) {
  4877. char buffer[64 * 1024];
  4878. memset(buffer, 0x42, sizeof(buffer));
  4879. auto res = cli_.Post(
  4880. "/slowpost", 64 * 1024 * 1024,
  4881. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4882. auto ret = sink.write(buffer, sizeof(buffer));
  4883. EXPECT_TRUE(ret);
  4884. return true;
  4885. },
  4886. "text/plain");
  4887. ASSERT_TRUE(res);
  4888. EXPECT_EQ(StatusCode::OK_200, res->status);
  4889. }
  4890. TEST_F(ServerTest, SlowPostFail) {
  4891. char buffer[64 * 1024];
  4892. memset(buffer, 0x42, sizeof(buffer));
  4893. cli_.set_write_timeout(std::chrono::seconds(0));
  4894. auto res = cli_.Post(
  4895. "/slowpost", 64 * 1024 * 1024,
  4896. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4897. sink.write(buffer, sizeof(buffer));
  4898. return true;
  4899. },
  4900. "text/plain");
  4901. ASSERT_TRUE(!res);
  4902. EXPECT_EQ(Error::Write, res.error());
  4903. }
  4904. #endif
  4905. TEST_F(ServerTest, Put) {
  4906. auto res = cli_.Put("/put", "PUT", "text/plain");
  4907. ASSERT_TRUE(res);
  4908. EXPECT_EQ(StatusCode::OK_200, res->status);
  4909. EXPECT_EQ("PUT", res->body);
  4910. }
  4911. TEST_F(ServerTest, PutWithContentProvider) {
  4912. auto res = cli_.Put(
  4913. "/put", 3,
  4914. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4915. sink.os << "PUT";
  4916. return true;
  4917. },
  4918. "text/plain");
  4919. ASSERT_TRUE(res);
  4920. EXPECT_EQ(StatusCode::OK_200, res->status);
  4921. EXPECT_EQ("PUT", res->body);
  4922. }
  4923. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4924. auto res = cli_.Post(
  4925. "/post", 42,
  4926. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4927. return false;
  4928. },
  4929. "text/plain");
  4930. ASSERT_TRUE(!res);
  4931. EXPECT_EQ(Error::Canceled, res.error());
  4932. }
  4933. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4934. auto res = cli_.Put(
  4935. "/put",
  4936. [](size_t /*offset*/, DataSink &sink) {
  4937. sink.os << "PUT";
  4938. sink.done();
  4939. return true;
  4940. },
  4941. "text/plain");
  4942. ASSERT_TRUE(res);
  4943. EXPECT_EQ(StatusCode::OK_200, res->status);
  4944. EXPECT_EQ("PUT", res->body);
  4945. }
  4946. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4947. auto res = cli_.Post(
  4948. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4949. "text/plain");
  4950. ASSERT_TRUE(!res);
  4951. EXPECT_EQ(Error::Canceled, res.error());
  4952. }
  4953. TEST_F(ServerTest, PostLoopBack) {
  4954. std::string body;
  4955. auto res = cli_.Post(
  4956. "/post-loopback", 9,
  4957. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4958. EXPECT_EQ(9u, length);
  4959. sink.write("123", 3);
  4960. sink.write("456", 3);
  4961. sink.write("789", 3);
  4962. return true;
  4963. },
  4964. "text/plain",
  4965. [&body](const char *data, size_t data_length) {
  4966. body.append(data, data_length);
  4967. return true;
  4968. });
  4969. ASSERT_TRUE(res);
  4970. EXPECT_EQ(StatusCode::OK_200, res->status);
  4971. EXPECT_EQ("123456789", body);
  4972. }
  4973. TEST_F(ServerTest, PutLoopBack) {
  4974. std::string body;
  4975. auto res = cli_.Put(
  4976. "/put-loopback", 9,
  4977. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4978. EXPECT_EQ(9u, length);
  4979. sink.write("123", 3);
  4980. sink.write("456", 3);
  4981. sink.write("789", 3);
  4982. return true;
  4983. },
  4984. "text/plain",
  4985. [&body](const char *data, size_t data_length) {
  4986. body.append(data, data_length);
  4987. return true;
  4988. });
  4989. ASSERT_TRUE(res);
  4990. EXPECT_EQ(StatusCode::OK_200, res->status);
  4991. EXPECT_EQ("123456789", body);
  4992. }
  4993. TEST_F(ServerTest, PatchLoopBack) {
  4994. std::string body;
  4995. auto res = cli_.Patch(
  4996. "/patch-loopback", 9,
  4997. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4998. EXPECT_EQ(9u, length);
  4999. sink.write("123", 3);
  5000. sink.write("456", 3);
  5001. sink.write("789", 3);
  5002. return true;
  5003. },
  5004. "text/plain",
  5005. [&body](const char *data, size_t data_length) {
  5006. body.append(data, data_length);
  5007. return true;
  5008. });
  5009. ASSERT_TRUE(res);
  5010. EXPECT_EQ(StatusCode::OK_200, res->status);
  5011. EXPECT_EQ("123456789", body);
  5012. }
  5013. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5014. std::string body;
  5015. auto res = cli_.Post(
  5016. "/post-loopback",
  5017. [](size_t /*offset*/, DataSink &sink) {
  5018. sink.write("123", 3);
  5019. sink.write("456", 3);
  5020. sink.write("789", 3);
  5021. sink.done();
  5022. return true;
  5023. },
  5024. "text/plain",
  5025. [&body](const char *data, size_t data_length) {
  5026. body.append(data, data_length);
  5027. return true;
  5028. });
  5029. ASSERT_TRUE(res);
  5030. EXPECT_EQ(StatusCode::OK_200, res->status);
  5031. EXPECT_EQ("123456789", body);
  5032. }
  5033. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5034. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5035. cli_.set_compress(true);
  5036. auto res = cli_.Put(
  5037. "/put", 3,
  5038. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5039. sink.os << "PUT";
  5040. return true;
  5041. },
  5042. "text/plain");
  5043. ASSERT_TRUE(res);
  5044. EXPECT_EQ(StatusCode::OK_200, res->status);
  5045. EXPECT_EQ("PUT", res->body);
  5046. }
  5047. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5048. cli_.set_compress(true);
  5049. auto res = cli_.Post(
  5050. "/post", 42,
  5051. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5052. return false;
  5053. },
  5054. "text/plain");
  5055. ASSERT_TRUE(!res);
  5056. EXPECT_EQ(Error::Canceled, res.error());
  5057. }
  5058. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5059. cli_.set_compress(true);
  5060. auto res = cli_.Put(
  5061. "/put",
  5062. [](size_t /*offset*/, DataSink &sink) {
  5063. sink.os << "PUT";
  5064. sink.done();
  5065. return true;
  5066. },
  5067. "text/plain");
  5068. ASSERT_TRUE(res);
  5069. EXPECT_EQ(StatusCode::OK_200, res->status);
  5070. EXPECT_EQ("PUT", res->body);
  5071. }
  5072. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5073. cli_.set_compress(true);
  5074. auto res = cli_.Post(
  5075. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5076. "text/plain");
  5077. ASSERT_TRUE(!res);
  5078. EXPECT_EQ(Error::Canceled, res.error());
  5079. }
  5080. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5081. cli_.set_compress(true);
  5082. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5083. ASSERT_TRUE(res);
  5084. EXPECT_EQ(StatusCode::OK_200, res->status);
  5085. EXPECT_EQ(LARGE_DATA, res->body);
  5086. }
  5087. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5088. #ifdef CPPHTTPLIB_SSL_ENABLED
  5089. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5090. Client cli(s.c_str());
  5091. cli.enable_server_certificate_verification(false);
  5092. #else
  5093. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5094. Client cli(s.c_str());
  5095. #endif
  5096. cli.set_compress(true);
  5097. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5098. ASSERT_TRUE(res);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. EXPECT_EQ(LARGE_DATA, res->body);
  5101. // The compressed size should be less than a 10th of the original. May vary
  5102. // depending on the zlib library.
  5103. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5104. static_cast<uint64_t>(10 * 1024 * 1024));
  5105. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5106. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5107. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5108. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5109. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5110. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5111. #endif
  5112. }
  5113. TEST_F(ServerTest, PutContentWithDeflate) {
  5114. cli_.set_compress(false);
  5115. Headers headers;
  5116. headers.emplace("Content-Encoding", "deflate");
  5117. // PUT in deflate format:
  5118. auto res = cli_.Put("/put", headers,
  5119. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5120. ASSERT_TRUE(res);
  5121. EXPECT_EQ(StatusCode::OK_200, res->status);
  5122. EXPECT_EQ("PUT", res->body);
  5123. }
  5124. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5125. Headers headers;
  5126. headers.emplace("Accept-Encoding", "gzip, deflate");
  5127. auto res = cli_.Get("/streamed-chunked", headers);
  5128. ASSERT_TRUE(res);
  5129. EXPECT_EQ(StatusCode::OK_200, res->status);
  5130. EXPECT_EQ(std::string("123456789"), res->body);
  5131. }
  5132. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5133. Headers headers;
  5134. headers.emplace("Accept-Encoding", "gzip, deflate");
  5135. auto res = cli_.Get("/streamed-chunked2", headers);
  5136. ASSERT_TRUE(res);
  5137. EXPECT_EQ(StatusCode::OK_200, res->status);
  5138. EXPECT_EQ(std::string("123456789"), res->body);
  5139. }
  5140. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5141. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5142. ASSERT_TRUE(res);
  5143. EXPECT_EQ(StatusCode::OK_200, res->status);
  5144. }
  5145. TEST(GzipDecompressor, ChunkedDecompression) {
  5146. std::string data;
  5147. for (size_t i = 0; i < 32 * 1024; ++i) {
  5148. data.push_back(static_cast<char>('a' + i % 26));
  5149. }
  5150. std::string compressed_data;
  5151. {
  5152. httplib::detail::gzip_compressor compressor;
  5153. bool result = compressor.compress(
  5154. data.data(), data.size(),
  5155. /*last=*/true,
  5156. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5157. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5158. compressed_data_size);
  5159. return true;
  5160. });
  5161. ASSERT_TRUE(result);
  5162. }
  5163. std::string decompressed_data;
  5164. {
  5165. httplib::detail::gzip_decompressor decompressor;
  5166. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5167. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5168. size_t chunk_size = 130;
  5169. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5170. chunk_begin += chunk_size) {
  5171. size_t current_chunk_size =
  5172. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5173. bool result = decompressor.decompress(
  5174. compressed_data.data() + chunk_begin, current_chunk_size,
  5175. [&](const char *decompressed_data_chunk,
  5176. size_t decompressed_data_chunk_size) {
  5177. decompressed_data.insert(decompressed_data.size(),
  5178. decompressed_data_chunk,
  5179. decompressed_data_chunk_size);
  5180. return true;
  5181. });
  5182. ASSERT_TRUE(result);
  5183. }
  5184. }
  5185. ASSERT_EQ(data, decompressed_data);
  5186. }
  5187. TEST(GzipDecompressor, DeflateDecompression) {
  5188. std::string original_text = "Raw deflate without gzip";
  5189. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5190. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5191. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5192. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5193. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5194. std::string decompressed_data;
  5195. {
  5196. httplib::detail::gzip_decompressor decompressor;
  5197. bool result = decompressor.decompress(
  5198. compressed_data.data(), compressed_data.size(),
  5199. [&](const char *decompressed_data_chunk,
  5200. size_t decompressed_data_chunk_size) {
  5201. decompressed_data.insert(decompressed_data.size(),
  5202. decompressed_data_chunk,
  5203. decompressed_data_chunk_size);
  5204. return true;
  5205. });
  5206. ASSERT_TRUE(result);
  5207. }
  5208. ASSERT_EQ(original_text, decompressed_data);
  5209. }
  5210. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5211. std::string original_text = "Raw deflate without gzip";
  5212. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5213. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5214. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5215. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5216. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5217. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5218. std::string decompressed_data;
  5219. {
  5220. httplib::detail::gzip_decompressor decompressor;
  5221. bool result = decompressor.decompress(
  5222. compressed_data.data(), compressed_data.size(),
  5223. [&](const char *decompressed_data_chunk,
  5224. size_t decompressed_data_chunk_size) {
  5225. decompressed_data.insert(decompressed_data.size(),
  5226. decompressed_data_chunk,
  5227. decompressed_data_chunk_size);
  5228. return true;
  5229. });
  5230. ASSERT_TRUE(result);
  5231. }
  5232. ASSERT_EQ(original_text, decompressed_data);
  5233. }
  5234. #endif
  5235. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5236. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5237. Headers headers;
  5238. headers.emplace("Accept-Encoding", "br");
  5239. auto res = cli_.Get("/streamed-chunked", headers);
  5240. ASSERT_TRUE(res);
  5241. EXPECT_EQ(StatusCode::OK_200, res->status);
  5242. EXPECT_EQ(std::string("123456789"), res->body);
  5243. }
  5244. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5245. Headers headers;
  5246. headers.emplace("Accept-Encoding", "br");
  5247. auto res = cli_.Get("/streamed-chunked2", headers);
  5248. ASSERT_TRUE(res);
  5249. EXPECT_EQ(StatusCode::OK_200, res->status);
  5250. EXPECT_EQ(std::string("123456789"), res->body);
  5251. }
  5252. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5253. cli_.set_compress(true);
  5254. auto res = cli_.Put(
  5255. "/put", 3,
  5256. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5257. sink.os << "PUT";
  5258. return true;
  5259. },
  5260. "text/plain");
  5261. ASSERT_TRUE(res);
  5262. EXPECT_EQ(StatusCode::OK_200, res->status);
  5263. EXPECT_EQ("PUT", res->body);
  5264. }
  5265. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5266. cli_.set_compress(true);
  5267. auto res = cli_.Put(
  5268. "/put",
  5269. [](size_t /*offset*/, DataSink &sink) {
  5270. sink.os << "PUT";
  5271. sink.done();
  5272. return true;
  5273. },
  5274. "text/plain");
  5275. ASSERT_TRUE(res);
  5276. EXPECT_EQ(StatusCode::OK_200, res->status);
  5277. EXPECT_EQ("PUT", res->body);
  5278. }
  5279. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5280. cli_.set_compress(true);
  5281. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5282. ASSERT_TRUE(res);
  5283. EXPECT_EQ(StatusCode::OK_200, res->status);
  5284. EXPECT_EQ(LARGE_DATA, res->body);
  5285. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5286. }
  5287. #endif
  5288. TEST_F(ServerTest, Patch) {
  5289. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. EXPECT_EQ("PATCH", res->body);
  5293. }
  5294. TEST_F(ServerTest, Delete) {
  5295. auto res = cli_.Delete("/delete");
  5296. ASSERT_TRUE(res);
  5297. EXPECT_EQ(StatusCode::OK_200, res->status);
  5298. EXPECT_EQ("DELETE", res->body);
  5299. }
  5300. TEST_F(ServerTest, DeleteContentReceiver) {
  5301. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5302. ASSERT_TRUE(res);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ("content", res->body);
  5305. }
  5306. TEST_F(ServerTest, Options) {
  5307. auto res = cli_.Options("*");
  5308. ASSERT_TRUE(res);
  5309. EXPECT_EQ(StatusCode::OK_200, res->status);
  5310. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5311. EXPECT_TRUE(res->body.empty());
  5312. }
  5313. TEST_F(ServerTest, URL) {
  5314. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5315. ASSERT_TRUE(res);
  5316. EXPECT_EQ(StatusCode::OK_200, res->status);
  5317. }
  5318. TEST_F(ServerTest, ArrayParam) {
  5319. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5320. ASSERT_TRUE(res);
  5321. EXPECT_EQ(StatusCode::OK_200, res->status);
  5322. }
  5323. TEST_F(ServerTest, ArrayParamValues) {
  5324. auto res =
  5325. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5326. ASSERT_TRUE(res);
  5327. EXPECT_EQ(StatusCode::OK_200, res->status);
  5328. }
  5329. TEST_F(ServerTest, NoMultipleHeaders) {
  5330. Headers headers = {{"Content-Length", "5"}};
  5331. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5332. "text/plain");
  5333. ASSERT_TRUE(res);
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. }
  5336. TEST_F(ServerTest, PostContentReceiver) {
  5337. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5338. ASSERT_TRUE(res);
  5339. ASSERT_EQ(StatusCode::OK_200, res->status);
  5340. ASSERT_EQ("content", res->body);
  5341. }
  5342. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5343. UploadFormDataItems items = {
  5344. {"text1", "text default", "", ""},
  5345. {"text2", "aωb", "", ""},
  5346. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5347. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5348. {"file3", "", "", "application/octet-stream"},
  5349. };
  5350. auto res = cli_.Post("/content_receiver", items);
  5351. ASSERT_TRUE(res);
  5352. EXPECT_EQ(StatusCode::OK_200, res->status);
  5353. }
  5354. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5355. UploadFormDataItems items = {
  5356. {"text1", "text default", "", ""},
  5357. {"text2", "aωb", "", ""},
  5358. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5359. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5360. {"file3", "", "", "application/octet-stream"},
  5361. };
  5362. auto boundary = std::string("+++++");
  5363. std::string body;
  5364. for (const auto &item : items) {
  5365. body += "--" + boundary + "\r\n";
  5366. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5367. if (!item.filename.empty()) {
  5368. body += "; filename=\"" + item.filename + "\"";
  5369. }
  5370. body += "\r\n";
  5371. if (!item.content_type.empty()) {
  5372. body += "Content-Type: " + item.content_type + "\r\n";
  5373. }
  5374. body += "\r\n";
  5375. body += item.content + "\r\n";
  5376. }
  5377. body += "--" + boundary + "--\r\n";
  5378. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5379. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5380. ASSERT_TRUE(res);
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. }
  5383. TEST_F(ServerTest, PostContentReceiverGzip) {
  5384. cli_.set_compress(true);
  5385. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5386. ASSERT_TRUE(res);
  5387. ASSERT_EQ(StatusCode::OK_200, res->status);
  5388. ASSERT_EQ("content", res->body);
  5389. }
  5390. TEST_F(ServerTest, PutContentReceiver) {
  5391. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5392. ASSERT_TRUE(res);
  5393. ASSERT_EQ(StatusCode::OK_200, res->status);
  5394. ASSERT_EQ("content", res->body);
  5395. }
  5396. TEST_F(ServerTest, PatchContentReceiver) {
  5397. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5398. ASSERT_TRUE(res);
  5399. ASSERT_EQ(StatusCode::OK_200, res->status);
  5400. ASSERT_EQ("content", res->body);
  5401. }
  5402. template <typename ClientType>
  5403. void TestWithHeadersAndContentReceiver(
  5404. ClientType &cli,
  5405. std::function<Result(ClientType &, const std::string &, const Headers &,
  5406. const std::string &, const std::string &,
  5407. ContentReceiver, DownloadProgress)>
  5408. request_func) {
  5409. Headers headers;
  5410. headers.emplace("X-Custom-Header", "test-value");
  5411. std::string received_body;
  5412. auto res = request_func(
  5413. cli, "/content_receiver", headers, "content", "application/json",
  5414. [&](const char *data, size_t data_length) {
  5415. received_body.append(data, data_length);
  5416. return true;
  5417. },
  5418. nullptr);
  5419. ASSERT_TRUE(res);
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. EXPECT_EQ("content", received_body);
  5422. }
  5423. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5424. #ifdef CPPHTTPLIB_SSL_ENABLED
  5425. using ClientT = SSLClient;
  5426. #else
  5427. using ClientT = Client;
  5428. #endif
  5429. TestWithHeadersAndContentReceiver<ClientT>(
  5430. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5431. const std::string &body, const std::string &content_type,
  5432. ContentReceiver receiver, DownloadProgress progress) {
  5433. return cli.Post(path, headers, body, content_type, receiver, progress);
  5434. });
  5435. }
  5436. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5437. #ifdef CPPHTTPLIB_SSL_ENABLED
  5438. using ClientT = SSLClient;
  5439. #else
  5440. using ClientT = Client;
  5441. #endif
  5442. TestWithHeadersAndContentReceiver<ClientT>(
  5443. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5444. const std::string &body, const std::string &content_type,
  5445. ContentReceiver receiver, DownloadProgress progress) {
  5446. return cli.Put(path, headers, body, content_type, receiver, progress);
  5447. });
  5448. }
  5449. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5450. #ifdef CPPHTTPLIB_SSL_ENABLED
  5451. using ClientT = SSLClient;
  5452. #else
  5453. using ClientT = Client;
  5454. #endif
  5455. TestWithHeadersAndContentReceiver<ClientT>(
  5456. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5457. const std::string &body, const std::string &content_type,
  5458. ContentReceiver receiver, DownloadProgress progress) {
  5459. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5460. });
  5461. }
  5462. template <typename ClientType>
  5463. void TestWithHeadersAndContentReceiverWithProgress(
  5464. ClientType &cli,
  5465. std::function<Result(ClientType &, const std::string &, const Headers &,
  5466. const std::string &, const std::string &,
  5467. ContentReceiver, DownloadProgress)>
  5468. request_func) {
  5469. Headers headers;
  5470. headers.emplace("X-Test-Header", "progress-test");
  5471. std::string received_body;
  5472. auto progress_called = false;
  5473. auto res = request_func(
  5474. cli, "/content_receiver", headers, "content", "text/plain",
  5475. [&](const char *data, size_t data_length) {
  5476. received_body.append(data, data_length);
  5477. return true;
  5478. },
  5479. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5480. progress_called = true;
  5481. return true;
  5482. });
  5483. ASSERT_TRUE(res);
  5484. EXPECT_EQ(StatusCode::OK_200, res->status);
  5485. EXPECT_EQ("content", received_body);
  5486. EXPECT_TRUE(progress_called);
  5487. }
  5488. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5489. #ifdef CPPHTTPLIB_SSL_ENABLED
  5490. using ClientT = SSLClient;
  5491. #else
  5492. using ClientT = Client;
  5493. #endif
  5494. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5495. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5496. const std::string &body, const std::string &content_type,
  5497. ContentReceiver receiver, DownloadProgress progress) {
  5498. return cli.Post(path, headers, body, content_type, receiver, progress);
  5499. });
  5500. }
  5501. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5502. #ifdef CPPHTTPLIB_SSL_ENABLED
  5503. using ClientT = SSLClient;
  5504. #else
  5505. using ClientT = Client;
  5506. #endif
  5507. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5508. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5509. const std::string &body, const std::string &content_type,
  5510. ContentReceiver receiver, DownloadProgress progress) {
  5511. return cli.Put(path, headers, body, content_type, receiver, progress);
  5512. });
  5513. }
  5514. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5515. #ifdef CPPHTTPLIB_SSL_ENABLED
  5516. using ClientT = SSLClient;
  5517. #else
  5518. using ClientT = Client;
  5519. #endif
  5520. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5521. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5522. const std::string &body, const std::string &content_type,
  5523. ContentReceiver receiver, DownloadProgress progress) {
  5524. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5525. });
  5526. }
  5527. template <typename ClientType>
  5528. void TestWithHeadersAndContentReceiverError(
  5529. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5530. const Headers &, const std::string &,
  5531. const std::string &, ContentReceiver)>
  5532. request_func) {
  5533. Headers headers;
  5534. headers.emplace("X-Error-Test", "true");
  5535. std::string received_body;
  5536. auto receiver_failed = false;
  5537. auto res =
  5538. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5539. [&](const char *data, size_t data_length) {
  5540. received_body.append(data, data_length);
  5541. receiver_failed = true;
  5542. return false;
  5543. });
  5544. ASSERT_FALSE(res);
  5545. EXPECT_TRUE(receiver_failed);
  5546. }
  5547. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5548. #ifdef CPPHTTPLIB_SSL_ENABLED
  5549. using ClientT = SSLClient;
  5550. #else
  5551. using ClientT = Client;
  5552. #endif
  5553. TestWithHeadersAndContentReceiverError<ClientT>(
  5554. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5555. const std::string &body, const std::string &content_type,
  5556. ContentReceiver receiver) {
  5557. return cli.Post(path, headers, body, content_type, receiver);
  5558. });
  5559. }
  5560. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5561. #ifdef CPPHTTPLIB_SSL_ENABLED
  5562. using ClientT = SSLClient;
  5563. #else
  5564. using ClientT = Client;
  5565. #endif
  5566. TestWithHeadersAndContentReceiverError<ClientT>(
  5567. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5568. const std::string &body, const std::string &content_type,
  5569. ContentReceiver receiver) {
  5570. return cli.Put(path, headers, body, content_type, receiver);
  5571. });
  5572. }
  5573. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5574. #ifdef CPPHTTPLIB_SSL_ENABLED
  5575. using ClientT = SSLClient;
  5576. #else
  5577. using ClientT = Client;
  5578. #endif
  5579. TestWithHeadersAndContentReceiverError<ClientT>(
  5580. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5581. const std::string &body, const std::string &content_type,
  5582. ContentReceiver receiver) {
  5583. return cli.Patch(path, headers, body, content_type, receiver);
  5584. });
  5585. }
  5586. TEST_F(ServerTest, PostQueryStringAndBody) {
  5587. auto res =
  5588. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5589. ASSERT_TRUE(res);
  5590. ASSERT_EQ(StatusCode::OK_200, res->status);
  5591. }
  5592. TEST_F(ServerTest, HTTP2Magic) {
  5593. Request req;
  5594. req.method = "PRI";
  5595. req.path = "*";
  5596. req.body = "SM";
  5597. auto res = std::make_shared<Response>();
  5598. auto error = Error::Success;
  5599. auto ret = cli_.send(req, *res, error);
  5600. ASSERT_TRUE(ret);
  5601. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5602. }
  5603. TEST_F(ServerTest, KeepAlive) {
  5604. auto res = cli_.Get("/hi");
  5605. ASSERT_TRUE(res);
  5606. EXPECT_EQ(StatusCode::OK_200, res->status);
  5607. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5608. EXPECT_EQ("Hello World!", res->body);
  5609. res = cli_.Get("/hi");
  5610. ASSERT_TRUE(res);
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5613. EXPECT_EQ("Hello World!", res->body);
  5614. res = cli_.Get("/hi");
  5615. ASSERT_TRUE(res);
  5616. EXPECT_EQ(StatusCode::OK_200, res->status);
  5617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5618. EXPECT_EQ("Hello World!", res->body);
  5619. res = cli_.Get("/not-exist");
  5620. ASSERT_TRUE(res);
  5621. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5622. res = cli_.Post("/empty", "", "text/plain");
  5623. ASSERT_TRUE(res);
  5624. EXPECT_EQ(StatusCode::OK_200, res->status);
  5625. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5626. EXPECT_EQ("empty", res->body);
  5627. EXPECT_EQ("close", res->get_header_value("Connection"));
  5628. res = cli_.Post(
  5629. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5630. "text/plain");
  5631. ASSERT_TRUE(res);
  5632. EXPECT_EQ(StatusCode::OK_200, res->status);
  5633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5634. EXPECT_EQ("empty", res->body);
  5635. cli_.set_keep_alive(false);
  5636. res = cli_.Get("/last-request");
  5637. ASSERT_TRUE(res);
  5638. EXPECT_EQ(StatusCode::OK_200, res->status);
  5639. EXPECT_EQ("close", res->get_header_value("Connection"));
  5640. }
  5641. TEST_F(ServerTest, TooManyRedirect) {
  5642. cli_.set_follow_location(true);
  5643. auto res = cli_.Get("/redirect/0");
  5644. ASSERT_TRUE(!res);
  5645. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5646. }
  5647. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5648. Request req;
  5649. req.method = "FOOBAR";
  5650. req.path = "/hi";
  5651. cli_.set_keep_alive(true);
  5652. auto res = cli_.send(req);
  5653. ASSERT_TRUE(res);
  5654. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5655. EXPECT_EQ("close", res->get_header_value("Connection"));
  5656. EXPECT_FALSE(cli_.is_socket_open());
  5657. }
  5658. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5659. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5660. TEST_F(ServerTest, Gzip) {
  5661. Headers headers;
  5662. headers.emplace("Accept-Encoding", "gzip, deflate");
  5663. auto res = cli_.Get("/compress", headers);
  5664. ASSERT_TRUE(res);
  5665. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5666. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5667. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5668. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5669. "7890123456789012345678901234567890",
  5670. res->body);
  5671. EXPECT_EQ(StatusCode::OK_200, res->status);
  5672. }
  5673. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5674. Headers headers;
  5675. headers.emplace("Accept-Encoding", "gzip, deflate");
  5676. auto res = cli_.Get("/compress-with-charset", headers);
  5677. ASSERT_TRUE(res);
  5678. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5679. EXPECT_EQ("application/json; charset=utf-8",
  5680. res->get_header_value("Content-Type"));
  5681. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5682. "7890123456789012345678901234567890",
  5683. res->body);
  5684. EXPECT_EQ(StatusCode::OK_200, res->status);
  5685. }
  5686. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5687. Headers headers;
  5688. headers.emplace("Accept-Encoding", "");
  5689. auto res = cli_.Get("/compress", headers);
  5690. ASSERT_TRUE(res);
  5691. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5692. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5693. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5694. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5695. "7890123456789012345678901234567890",
  5696. res->body);
  5697. EXPECT_EQ(StatusCode::OK_200, res->status);
  5698. }
  5699. TEST_F(ServerTest, GzipWithContentReceiver) {
  5700. Headers headers;
  5701. headers.emplace("Accept-Encoding", "gzip, deflate");
  5702. std::string body;
  5703. auto res = cli_.Get("/compress", headers,
  5704. [&](const char *data, uint64_t data_length) {
  5705. EXPECT_EQ(100U, data_length);
  5706. body.append(data, data_length);
  5707. return true;
  5708. });
  5709. ASSERT_TRUE(res);
  5710. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5711. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5712. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5713. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5714. "7890123456789012345678901234567890",
  5715. body);
  5716. EXPECT_EQ(StatusCode::OK_200, res->status);
  5717. }
  5718. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5719. Headers headers;
  5720. headers.emplace("Accept-Encoding", "gzip, deflate");
  5721. cli_.set_decompress(false);
  5722. auto res = cli_.Get("/compress", headers);
  5723. ASSERT_TRUE(res);
  5724. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5725. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5726. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5727. EXPECT_EQ(33U, res->body.size());
  5728. EXPECT_EQ(StatusCode::OK_200, res->status);
  5729. }
  5730. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5731. Headers headers;
  5732. headers.emplace("Accept-Encoding", "");
  5733. std::string body;
  5734. auto res = cli_.Get("/compress", headers,
  5735. [&](const char *data, uint64_t data_length) {
  5736. EXPECT_EQ(100U, data_length);
  5737. body.append(data, data_length);
  5738. return true;
  5739. });
  5740. ASSERT_TRUE(res);
  5741. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5742. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5743. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5744. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5745. "7890123456789012345678901234567890",
  5746. body);
  5747. EXPECT_EQ(StatusCode::OK_200, res->status);
  5748. }
  5749. TEST_F(ServerTest, NoGzip) {
  5750. Headers headers;
  5751. headers.emplace("Accept-Encoding", "gzip, deflate");
  5752. auto res = cli_.Get("/nocompress", headers);
  5753. ASSERT_TRUE(res);
  5754. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5755. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5756. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5757. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5758. "7890123456789012345678901234567890",
  5759. res->body);
  5760. EXPECT_EQ(StatusCode::OK_200, res->status);
  5761. }
  5762. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5763. Headers headers;
  5764. headers.emplace("Accept-Encoding", "gzip, deflate");
  5765. std::string body;
  5766. auto res = cli_.Get("/nocompress", headers,
  5767. [&](const char *data, uint64_t data_length) {
  5768. EXPECT_EQ(100U, data_length);
  5769. body.append(data, data_length);
  5770. return true;
  5771. });
  5772. ASSERT_TRUE(res);
  5773. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5774. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5775. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5776. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5777. "7890123456789012345678901234567890",
  5778. body);
  5779. EXPECT_EQ(StatusCode::OK_200, res->status);
  5780. }
  5781. TEST_F(ServerTest, MultipartFormDataGzip) {
  5782. UploadFormDataItems items = {
  5783. {"key1", "test", "", ""},
  5784. {"key2", "--abcdefg123", "", ""},
  5785. };
  5786. cli_.set_compress(true);
  5787. auto res = cli_.Post("/compress-multipart", items);
  5788. ASSERT_TRUE(res);
  5789. EXPECT_EQ(StatusCode::OK_200, res->status);
  5790. }
  5791. #endif
  5792. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5793. TEST_F(ServerTest, Brotli) {
  5794. Headers headers;
  5795. headers.emplace("Accept-Encoding", "br");
  5796. auto res = cli_.Get("/compress", headers);
  5797. ASSERT_TRUE(res);
  5798. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5799. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5800. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5801. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5802. "7890123456789012345678901234567890",
  5803. res->body);
  5804. EXPECT_EQ(StatusCode::OK_200, res->status);
  5805. }
  5806. #endif
  5807. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5808. TEST_F(ServerTest, Zstd) {
  5809. Headers headers;
  5810. headers.emplace("Accept-Encoding", "zstd");
  5811. auto res = cli_.Get("/compress", headers);
  5812. ASSERT_TRUE(res);
  5813. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5814. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5815. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5816. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5817. "7890123456789012345678901234567890",
  5818. res->body);
  5819. EXPECT_EQ(StatusCode::OK_200, res->status);
  5820. }
  5821. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5822. Headers headers;
  5823. headers.emplace("Accept-Encoding", "");
  5824. auto res = cli_.Get("/compress", headers);
  5825. ASSERT_TRUE(res);
  5826. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5827. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5828. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5829. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5830. "7890123456789012345678901234567890",
  5831. res->body);
  5832. EXPECT_EQ(StatusCode::OK_200, res->status);
  5833. }
  5834. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5835. Headers headers;
  5836. headers.emplace("Accept-Encoding", "zstd");
  5837. std::string body;
  5838. auto res = cli_.Get("/compress", headers,
  5839. [&](const char *data, uint64_t data_length) {
  5840. EXPECT_EQ(100U, data_length);
  5841. body.append(data, data_length);
  5842. return true;
  5843. });
  5844. ASSERT_TRUE(res);
  5845. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5846. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5847. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5848. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5849. "7890123456789012345678901234567890",
  5850. body);
  5851. EXPECT_EQ(StatusCode::OK_200, res->status);
  5852. }
  5853. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5854. Headers headers;
  5855. headers.emplace("Accept-Encoding", "zstd");
  5856. cli_.set_decompress(false);
  5857. auto res = cli_.Get("/compress", headers);
  5858. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5859. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5860. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5861. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5862. ASSERT_TRUE(res);
  5863. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5864. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5865. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5866. EXPECT_EQ(StatusCode::OK_200, res->status);
  5867. ASSERT_EQ(26U, res->body.size());
  5868. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5869. 0);
  5870. }
  5871. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5872. Headers headers;
  5873. headers.emplace("Accept-Encoding", "");
  5874. std::string body;
  5875. auto res = cli_.Get("/compress", headers,
  5876. [&](const char *data, uint64_t data_length) {
  5877. EXPECT_EQ(100U, data_length);
  5878. body.append(data, data_length);
  5879. return true;
  5880. });
  5881. ASSERT_TRUE(res);
  5882. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5884. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5885. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5886. "7890123456789012345678901234567890",
  5887. body);
  5888. EXPECT_EQ(StatusCode::OK_200, res->status);
  5889. }
  5890. TEST_F(ServerTest, NoZstd) {
  5891. Headers headers;
  5892. headers.emplace("Accept-Encoding", "zstd");
  5893. auto res = cli_.Get("/nocompress", headers);
  5894. ASSERT_TRUE(res);
  5895. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5896. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5897. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5898. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5899. "7890123456789012345678901234567890",
  5900. res->body);
  5901. EXPECT_EQ(StatusCode::OK_200, res->status);
  5902. }
  5903. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5904. Headers headers;
  5905. headers.emplace("Accept-Encoding", "zstd");
  5906. std::string body;
  5907. auto res = cli_.Get("/nocompress", headers,
  5908. [&](const char *data, uint64_t data_length) {
  5909. EXPECT_EQ(100U, data_length);
  5910. body.append(data, data_length);
  5911. return true;
  5912. });
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5915. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5916. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5917. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5918. "7890123456789012345678901234567890",
  5919. body);
  5920. EXPECT_EQ(StatusCode::OK_200, res->status);
  5921. }
  5922. // TODO: How to enable zstd ??
  5923. TEST_F(ServerTest, MultipartFormDataZstd) {
  5924. UploadFormDataItems items = {
  5925. {"key1", "test", "", ""},
  5926. {"key2", "--abcdefg123", "", ""},
  5927. };
  5928. Headers headers;
  5929. headers.emplace("Accept-Encoding", "zstd");
  5930. cli_.set_compress(true);
  5931. auto res = cli_.Post("/compress-multipart", headers, items);
  5932. ASSERT_TRUE(res);
  5933. EXPECT_EQ(StatusCode::OK_200, res->status);
  5934. }
  5935. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5936. Headers headers;
  5937. headers.emplace("Accept-Encoding", "zstd");
  5938. cli_.set_compress(true);
  5939. auto res = cli_.Put(
  5940. "/put", headers, 3,
  5941. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5942. sink.os << "PUT";
  5943. return true;
  5944. },
  5945. "text/plain");
  5946. ASSERT_TRUE(res);
  5947. EXPECT_EQ(StatusCode::OK_200, res->status);
  5948. EXPECT_EQ("PUT", res->body);
  5949. }
  5950. // Pre-compression logging tests
  5951. TEST_F(ServerTest, PreCompressionLogging) {
  5952. // Test data for compression (matches the actual /compress endpoint content)
  5953. const std::string test_content =
  5954. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5955. "3456789012345678901234567890";
  5956. // Variables to capture logging data
  5957. std::string pre_compression_body;
  5958. std::string pre_compression_content_type;
  5959. std::string pre_compression_content_encoding;
  5960. std::string post_compression_body;
  5961. std::string post_compression_content_type;
  5962. std::string post_compression_content_encoding;
  5963. // Set up pre-compression logger
  5964. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5965. const Response &res) {
  5966. pre_compression_body = res.body;
  5967. pre_compression_content_type = res.get_header_value("Content-Type");
  5968. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5969. });
  5970. // Set up post-compression logger
  5971. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5972. post_compression_body = res.body;
  5973. post_compression_content_type = res.get_header_value("Content-Type");
  5974. post_compression_content_encoding =
  5975. res.get_header_value("Content-Encoding");
  5976. });
  5977. // Test with gzip compression
  5978. Headers headers;
  5979. headers.emplace("Accept-Encoding", "gzip");
  5980. auto res = cli_.Get("/compress", headers);
  5981. // Verify response was compressed
  5982. ASSERT_TRUE(res);
  5983. EXPECT_EQ(StatusCode::OK_200, res->status);
  5984. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5985. // Verify pre-compression logger captured uncompressed content
  5986. EXPECT_EQ(test_content, pre_compression_body);
  5987. EXPECT_EQ("text/plain", pre_compression_content_type);
  5988. EXPECT_TRUE(pre_compression_content_encoding
  5989. .empty()); // No encoding header before compression
  5990. // Verify post-compression logger captured compressed content
  5991. EXPECT_NE(test_content,
  5992. post_compression_body); // Should be different after compression
  5993. EXPECT_EQ("text/plain", post_compression_content_type);
  5994. EXPECT_EQ("gzip", post_compression_content_encoding);
  5995. // Verify compressed content is smaller
  5996. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5997. }
  5998. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5999. const std::string test_content =
  6000. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6001. "3456789012345678901234567890";
  6002. std::string pre_compression_body;
  6003. std::string post_compression_body;
  6004. svr_.set_pre_compression_logger(
  6005. [&](const Request & /*req*/, const Response &res) {
  6006. pre_compression_body = res.body;
  6007. });
  6008. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6009. post_compression_body = res.body;
  6010. });
  6011. Headers headers;
  6012. headers.emplace("Accept-Encoding", "br");
  6013. auto res = cli_.Get("/compress", headers);
  6014. ASSERT_TRUE(res);
  6015. EXPECT_EQ(StatusCode::OK_200, res->status);
  6016. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6017. // Verify pre-compression content is uncompressed
  6018. EXPECT_EQ(test_content, pre_compression_body);
  6019. // Verify post-compression content is compressed
  6020. EXPECT_NE(test_content, post_compression_body);
  6021. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6022. }
  6023. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6024. const std::string test_content =
  6025. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6026. "3456789012345678901234567890";
  6027. std::string pre_compression_body;
  6028. std::string post_compression_body;
  6029. svr_.set_pre_compression_logger(
  6030. [&](const Request & /*req*/, const Response &res) {
  6031. pre_compression_body = res.body;
  6032. });
  6033. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6034. post_compression_body = res.body;
  6035. });
  6036. // Request without compression (use /nocompress endpoint)
  6037. Headers headers;
  6038. auto res = cli_.Get("/nocompress", headers);
  6039. ASSERT_TRUE(res);
  6040. EXPECT_EQ(StatusCode::OK_200, res->status);
  6041. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6042. // Pre-compression logger should not be called when no compression is applied
  6043. EXPECT_TRUE(
  6044. pre_compression_body.empty()); // Pre-compression logger not called
  6045. EXPECT_EQ(
  6046. test_content,
  6047. post_compression_body); // Post-compression logger captures final content
  6048. }
  6049. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6050. const std::string test_content =
  6051. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6052. "3456789012345678901234567890";
  6053. std::string pre_compression_body;
  6054. bool pre_logger_called = false;
  6055. // Set only pre-compression logger
  6056. svr_.set_pre_compression_logger(
  6057. [&](const Request & /*req*/, const Response &res) {
  6058. pre_compression_body = res.body;
  6059. pre_logger_called = true;
  6060. });
  6061. Headers headers;
  6062. headers.emplace("Accept-Encoding", "gzip");
  6063. auto res = cli_.Get("/compress", headers);
  6064. ASSERT_TRUE(res);
  6065. EXPECT_EQ(StatusCode::OK_200, res->status);
  6066. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6067. // Verify pre-compression logger was called
  6068. EXPECT_TRUE(pre_logger_called);
  6069. EXPECT_EQ(test_content, pre_compression_body);
  6070. }
  6071. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6072. {
  6073. // Test with Expect: 100-continue header - success case
  6074. // Server returns 100 Continue, client sends body, server returns 200 OK
  6075. Request req;
  6076. req.method = "POST";
  6077. req.path = "/post-large";
  6078. req.set_header("Expect", "100-continue");
  6079. req.body = LARGE_DATA;
  6080. Response res;
  6081. auto error = Error::Success;
  6082. cli_.set_keep_alive(true);
  6083. auto ret = cli_.send(req, res, error);
  6084. EXPECT_TRUE(ret);
  6085. EXPECT_EQ(StatusCode::OK_200, res.status);
  6086. EXPECT_EQ(LARGE_DATA, res.body);
  6087. }
  6088. {
  6089. // Test with Expect: 100-continue header - error case
  6090. // Client should not send the body when server returns an error
  6091. Request req;
  6092. req.method = "POST";
  6093. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6094. req.set_header("Expect", "100-continue");
  6095. req.body = LARGE_DATA;
  6096. Response res;
  6097. auto error = Error::Success;
  6098. auto start = std::chrono::high_resolution_clock::now();
  6099. cli_.set_keep_alive(true);
  6100. auto ret = cli_.send(req, res, error);
  6101. auto end = std::chrono::high_resolution_clock::now();
  6102. auto elapsed =
  6103. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6104. .count();
  6105. // With Expect: 100-continue, request completes successfully but with error
  6106. EXPECT_TRUE(ret);
  6107. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6108. EXPECT_EQ("close", res.get_header_value("Connection"));
  6109. EXPECT_FALSE(cli_.is_socket_open());
  6110. EXPECT_LE(elapsed, 2000);
  6111. }
  6112. {
  6113. // Send an extra GET request to ensure error recovery without hanging
  6114. Request req;
  6115. req.method = "GET";
  6116. req.path = "/hi";
  6117. auto start = std::chrono::high_resolution_clock::now();
  6118. auto res = cli_.send(req);
  6119. auto end = std::chrono::high_resolution_clock::now();
  6120. auto elapsed =
  6121. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6122. .count();
  6123. ASSERT_TRUE(res);
  6124. EXPECT_EQ(StatusCode::OK_200, res->status);
  6125. EXPECT_EQ("Hello World!", res->body);
  6126. EXPECT_LE(elapsed, 500);
  6127. }
  6128. }
  6129. TEST(ZstdDecompressor, ChunkedDecompression) {
  6130. std::string data;
  6131. for (size_t i = 0; i < 32 * 1024; ++i) {
  6132. data.push_back(static_cast<char>('a' + i % 26));
  6133. }
  6134. std::string compressed_data;
  6135. {
  6136. httplib::detail::zstd_compressor compressor;
  6137. bool result = compressor.compress(
  6138. data.data(), data.size(),
  6139. /*last=*/true,
  6140. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6141. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6142. compressed_data_size);
  6143. return true;
  6144. });
  6145. ASSERT_TRUE(result);
  6146. }
  6147. std::string decompressed_data;
  6148. {
  6149. httplib::detail::zstd_decompressor decompressor;
  6150. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6151. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6152. size_t chunk_size = 130;
  6153. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6154. chunk_begin += chunk_size) {
  6155. size_t current_chunk_size =
  6156. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6157. bool result = decompressor.decompress(
  6158. compressed_data.data() + chunk_begin, current_chunk_size,
  6159. [&](const char *decompressed_data_chunk,
  6160. size_t decompressed_data_chunk_size) {
  6161. decompressed_data.insert(decompressed_data.size(),
  6162. decompressed_data_chunk,
  6163. decompressed_data_chunk_size);
  6164. return true;
  6165. });
  6166. ASSERT_TRUE(result);
  6167. }
  6168. }
  6169. ASSERT_EQ(data, decompressed_data);
  6170. }
  6171. TEST(ZstdDecompressor, Decompress) {
  6172. std::string original_text = "Compressed with ZSTD";
  6173. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6174. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6175. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6176. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6177. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6178. std::string decompressed_data;
  6179. {
  6180. httplib::detail::zstd_decompressor decompressor;
  6181. bool result = decompressor.decompress(
  6182. compressed_data.data(), compressed_data.size(),
  6183. [&](const char *decompressed_data_chunk,
  6184. size_t decompressed_data_chunk_size) {
  6185. decompressed_data.insert(decompressed_data.size(),
  6186. decompressed_data_chunk,
  6187. decompressed_data_chunk_size);
  6188. return true;
  6189. });
  6190. ASSERT_TRUE(result);
  6191. }
  6192. ASSERT_EQ(original_text, decompressed_data);
  6193. }
  6194. #endif
  6195. // Sends a raw request to a server listening at HOST:PORT.
  6196. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6197. std::string *resp = nullptr) {
  6198. auto error = Error::Success;
  6199. auto client_sock = detail::create_client_socket(
  6200. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6201. /*connection_timeout_sec=*/5, 0,
  6202. /*read_timeout_sec=*/5, 0,
  6203. /*write_timeout_sec=*/5, 0, std::string(), error);
  6204. if (client_sock == INVALID_SOCKET) { return false; }
  6205. auto ret = detail::process_client_socket(
  6206. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6207. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6208. if (req.size() !=
  6209. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6210. return false;
  6211. }
  6212. char buf[512];
  6213. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6214. while (line_reader.getline()) {
  6215. if (resp) { *resp += line_reader.ptr(); }
  6216. }
  6217. return true;
  6218. });
  6219. detail::close_socket(client_sock);
  6220. return ret;
  6221. }
  6222. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6223. Server svr;
  6224. std::string header_value;
  6225. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6226. header_value = req.get_header_value("foo");
  6227. res.set_content("ok", "text/plain");
  6228. });
  6229. thread t = thread([&] { svr.listen(HOST, PORT); });
  6230. auto se = detail::scope_exit([&] {
  6231. svr.stop();
  6232. t.join();
  6233. ASSERT_FALSE(svr.is_running());
  6234. });
  6235. svr.wait_until_ready();
  6236. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6237. // like characters are not treated the same - use vertical tab and escape.
  6238. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6239. "foo: \t \v bar \x1B\t \r\n"
  6240. "Connection: close\r\n"
  6241. "\r\n";
  6242. std::string res;
  6243. ASSERT_TRUE(send_request(5, req, &res));
  6244. EXPECT_EQ(header_value, "");
  6245. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6246. }
  6247. // Sends a raw request and verifies that there isn't a crash or exception.
  6248. static void test_raw_request(const std::string &req,
  6249. std::string *out = nullptr) {
  6250. Server svr;
  6251. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6252. res.set_content("ok", "text/plain");
  6253. });
  6254. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6255. res.set_content("ok", "text/plain");
  6256. });
  6257. svr.Get("/header_field_value_check",
  6258. [&](const Request & /*req*/, Response &res) {
  6259. res.set_content("ok", "text/plain");
  6260. });
  6261. // Server read timeout must be longer than the client read timeout for the
  6262. // bug to reproduce, probably to force the server to process a request
  6263. // without a trailing blank line.
  6264. const time_t client_read_timeout_sec = 1;
  6265. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6266. bool listen_thread_ok = false;
  6267. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6268. auto se = detail::scope_exit([&] {
  6269. svr.stop();
  6270. t.join();
  6271. ASSERT_FALSE(svr.is_running());
  6272. EXPECT_TRUE(listen_thread_ok);
  6273. });
  6274. svr.wait_until_ready();
  6275. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6276. }
  6277. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6278. // A certain header line causes an exception if the header property is parsed
  6279. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6280. test_raw_request(
  6281. "GET /hi HTTP/1.1\r\n"
  6282. " : "
  6283. " "
  6284. " ");
  6285. }
  6286. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6287. // A certain header line causes an exception if the header property *name* is
  6288. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6289. // greedy matcher and requires backtracking when there are a lot of ":"
  6290. // characters.
  6291. // This occurs with libc++ but not libstdc++.
  6292. test_raw_request(
  6293. "GET /hi HTTP/1.1\r\n"
  6294. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6295. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6296. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6297. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6298. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6299. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6300. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6301. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6302. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6303. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6304. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6305. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6306. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6307. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6308. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6309. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6310. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6311. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6312. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6313. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6314. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6315. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6316. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6317. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6318. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6319. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6320. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6321. "&&&%%%");
  6322. }
  6323. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6324. // Make sure this doesn't crash the server.
  6325. // In a previous version of the header line regex, the "\r" rendered the line
  6326. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6327. // a new position where the leading white space ended and the field value
  6328. // began.
  6329. // The crash occurs with libc++ but not libstdc++.
  6330. test_raw_request("GET /hi HTTP/1.1\r\n"
  6331. "a:" +
  6332. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6333. "\r\n"
  6334. "\r\n");
  6335. }
  6336. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6337. std::string out;
  6338. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6339. "Content-Type: text/plain\r\n"
  6340. "Transfer-Encoding: chunked\r\n"
  6341. "\r\n"
  6342. "nothex\r\n",
  6343. &out);
  6344. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6345. }
  6346. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6347. std::string out;
  6348. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6349. "Content-Type: text/plain\r\n"
  6350. "Transfer-Encoding: chunked\r\n"
  6351. "\r\n"
  6352. "3\r\n"
  6353. "xyz\r\n"
  6354. "NaN\r\n",
  6355. &out);
  6356. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6357. }
  6358. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6359. std::string out;
  6360. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6361. "Content-Type: text/plain\r\n"
  6362. "Transfer-Encoding: chunked\r\n"
  6363. "\r\n"
  6364. // Length is too large for 64 bits.
  6365. "1ffffffffffffffff\r\n"
  6366. "xyz\r\n",
  6367. &out);
  6368. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6369. }
  6370. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6371. test_raw_request("GET /hi HTTP/1.1\r\n"
  6372. "Content-Type: text/plain\r\n\r");
  6373. }
  6374. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6375. std::string out;
  6376. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6377. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6378. }
  6379. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6380. Server svr;
  6381. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6382. EXPECT_TRUE(!req.remote_addr.empty());
  6383. });
  6384. thread t = thread([&] { svr.listen(HOST, PORT); });
  6385. auto se = detail::scope_exit([&] {
  6386. svr.stop();
  6387. t.join();
  6388. ASSERT_FALSE(svr.is_running());
  6389. });
  6390. svr.wait_until_ready();
  6391. // Send an invalid request line to trigger Bad Request
  6392. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6393. std::string out;
  6394. ASSERT_TRUE(send_request(5, bad_req, &out));
  6395. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6396. }
  6397. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6398. std::string out;
  6399. std::string request(
  6400. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6401. test_raw_request(request, &out);
  6402. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6403. }
  6404. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6405. std::string out;
  6406. std::string request(
  6407. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6408. test_raw_request(request, &out);
  6409. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6410. }
  6411. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6412. std::string out;
  6413. std::string request(
  6414. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6415. test_raw_request(request, &out);
  6416. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6417. }
  6418. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6419. std::string out;
  6420. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6421. "Test: \r\n\r\n",
  6422. &out);
  6423. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6424. }
  6425. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6426. Server svr;
  6427. std::string x_custom;
  6428. std::string cookie;
  6429. std::string xff;
  6430. std::string x_unicode;
  6431. std::string x_iis;
  6432. svr.Get("/check", [&](const Request &req, Response &res) {
  6433. x_custom = req.get_header_value("X-Custom");
  6434. cookie = req.get_header_value("Cookie");
  6435. xff = req.get_header_value("X-Forwarded-For");
  6436. x_unicode = req.get_header_value("X-Unicode");
  6437. x_iis = req.get_header_value("X-IIS");
  6438. res.set_content("ok", "text/plain");
  6439. });
  6440. thread t = thread([&] { svr.listen(HOST, PORT); });
  6441. auto se = detail::scope_exit([&] {
  6442. svr.stop();
  6443. t.join();
  6444. ASSERT_FALSE(svr.is_running());
  6445. });
  6446. svr.wait_until_ready();
  6447. const std::string req = "GET /check HTTP/1.1\r\n"
  6448. "Host: localhost\r\n"
  6449. "X-Custom: a%0D%0AInjected: b\r\n"
  6450. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6451. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6452. "X-Unicode: %E3%81%82\r\n"
  6453. "X-IIS: %u00E9\r\n"
  6454. "Connection: close\r\n"
  6455. "\r\n";
  6456. std::string res;
  6457. ASSERT_TRUE(send_request(5, req, &res));
  6458. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6459. // Every value must be returned verbatim (wire form), with no decoding.
  6460. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6461. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6462. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6463. EXPECT_EQ("%E3%81%82", x_unicode);
  6464. EXPECT_EQ("%u00E9", x_iis);
  6465. }
  6466. // Applications that previously relied on automatic percent-decoding can
  6467. // reproduce the old behavior by explicitly calling decode_path_component()
  6468. // or, for RFC 3986 conformance, decode_uri_component().
  6469. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6470. Server svr;
  6471. std::string decoded;
  6472. svr.Get("/check", [&](const Request &req, Response &res) {
  6473. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6474. res.set_content("ok", "text/plain");
  6475. });
  6476. thread t = thread([&] { svr.listen(HOST, PORT); });
  6477. auto se = detail::scope_exit([&] {
  6478. svr.stop();
  6479. t.join();
  6480. ASSERT_FALSE(svr.is_running());
  6481. });
  6482. svr.wait_until_ready();
  6483. const std::string req = "GET /check HTTP/1.1\r\n"
  6484. "Host: localhost\r\n"
  6485. "X-Custom: hello%20world\r\n"
  6486. "Connection: close\r\n"
  6487. "\r\n";
  6488. std::string res;
  6489. ASSERT_TRUE(send_request(5, req, &res));
  6490. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6491. EXPECT_EQ("hello world", decoded);
  6492. }
  6493. // Regression test for #2033. Browsers send Referer values that include
  6494. // percent-encoded characters such as %0A inside the URL. Decoding the
  6495. // header value would either trip the post-decode CR/LF/NUL guard (the
  6496. // original bug, returning 400) or, after that guard was relaxed, silently
  6497. // store a literal LF — both unacceptable. The wire form must round-trip.
  6498. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6499. Server svr;
  6500. std::string referer;
  6501. svr.Get("/check", [&](const Request &req, Response &res) {
  6502. referer = req.get_header_value("Referer");
  6503. res.set_content("ok", "text/plain");
  6504. });
  6505. thread t = thread([&] { svr.listen(HOST, PORT); });
  6506. auto se = detail::scope_exit([&] {
  6507. svr.stop();
  6508. t.join();
  6509. ASSERT_FALSE(svr.is_running());
  6510. });
  6511. svr.wait_until_ready();
  6512. const std::string req = "GET /check HTTP/1.1\r\n"
  6513. "Host: localhost\r\n"
  6514. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6515. "Connection: close\r\n"
  6516. "\r\n";
  6517. std::string res;
  6518. ASSERT_TRUE(send_request(5, req, &res));
  6519. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6520. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6521. }
  6522. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6523. Server svr;
  6524. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6525. res.set_header("Cache-Control", "no-cache");
  6526. res.set_chunked_content_provider(
  6527. "text/event-stream", [](size_t offset, DataSink &sink) {
  6528. std::string s = "data:";
  6529. s += std::to_string(offset);
  6530. s += "\n\n";
  6531. auto ret = sink.write(s.data(), s.size());
  6532. EXPECT_TRUE(ret);
  6533. std::this_thread::sleep_for(std::chrono::seconds(1));
  6534. return true;
  6535. });
  6536. });
  6537. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6538. svr.wait_until_ready();
  6539. Client client(HOST, PORT);
  6540. const Headers headers = {{"Accept", "text/event-stream"}};
  6541. auto get_thread = std::thread([&client, &headers]() {
  6542. auto res = client.Get(
  6543. "/events", headers,
  6544. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6545. });
  6546. auto se = detail::scope_exit([&] {
  6547. svr.stop();
  6548. get_thread.join();
  6549. listen_thread.join();
  6550. ASSERT_FALSE(svr.is_running());
  6551. });
  6552. // Give GET time to get a few messages.
  6553. std::this_thread::sleep_for(std::chrono::seconds(2));
  6554. }
  6555. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6556. httplib::Server svr;
  6557. svr.Post("/hi",
  6558. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6559. res.status = StatusCode::OK_200;
  6560. });
  6561. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6562. svr.wait_until_ready();
  6563. Client cli(HOST, PORT);
  6564. auto res = cli.Post("/hi", "data", "text/plain");
  6565. ASSERT_TRUE(res);
  6566. EXPECT_EQ(StatusCode::OK_200, res->status);
  6567. svr.stop();
  6568. thread.join();
  6569. ASSERT_FALSE(svr.is_running());
  6570. res = cli.Post("/hi", "data", "text/plain");
  6571. ASSERT_FALSE(res);
  6572. }
  6573. TEST(ServerStopTest, ListenFailure) {
  6574. Server svr;
  6575. auto t = thread([&]() {
  6576. auto ret = svr.listen("????", PORT);
  6577. EXPECT_FALSE(ret);
  6578. });
  6579. svr.wait_until_ready();
  6580. svr.stop();
  6581. t.join();
  6582. }
  6583. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6584. TEST(ServerStopTest, Decommision) {
  6585. Server svr;
  6586. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6587. for (int i = 0; i < 4; i++) {
  6588. auto is_even = !(i % 2);
  6589. std::thread t{[&] {
  6590. try {
  6591. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6592. if (is_even) {
  6593. throw std::runtime_error("Some thing that happens to go wrong.");
  6594. }
  6595. svr.listen(HOST, PORT);
  6596. } catch (...) { svr.decommission(); }
  6597. }};
  6598. svr.wait_until_ready();
  6599. // Server is up
  6600. {
  6601. Client cli(HOST, PORT);
  6602. auto res = cli.Get("/hi");
  6603. if (is_even) {
  6604. EXPECT_FALSE(res);
  6605. } else {
  6606. EXPECT_TRUE(res);
  6607. EXPECT_EQ("hi...", res->body);
  6608. }
  6609. }
  6610. svr.stop();
  6611. t.join();
  6612. // Server is down...
  6613. {
  6614. Client cli(HOST, PORT);
  6615. auto res = cli.Get("/hi");
  6616. EXPECT_FALSE(res);
  6617. }
  6618. }
  6619. }
  6620. #endif
  6621. // Helper function for string body upload progress tests
  6622. template <typename SetupHandler, typename ClientCall>
  6623. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6624. ClientCall &&client_call,
  6625. const string &body) {
  6626. Server svr;
  6627. setup_handler(svr);
  6628. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6629. auto se = detail::scope_exit([&] {
  6630. svr.stop();
  6631. t.join();
  6632. });
  6633. svr.wait_until_ready();
  6634. Client cli(HOST, PORT);
  6635. vector<uint64_t> progress_values;
  6636. bool progress_called = false;
  6637. auto res =
  6638. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6639. progress_values.push_back(current);
  6640. progress_called = true;
  6641. return true;
  6642. });
  6643. ASSERT_TRUE(res);
  6644. EXPECT_EQ(200, res->status);
  6645. EXPECT_TRUE(progress_called);
  6646. }
  6647. TEST(UploadProgressTest, PostStringBodyBasic) {
  6648. TestStringBodyUploadProgress(
  6649. [](Server &svr) {
  6650. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6651. res.set_content("received", "text/plain");
  6652. });
  6653. },
  6654. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6655. return cli.Post("/test", body, "text/plain", progress_callback);
  6656. },
  6657. "test data for upload progress");
  6658. }
  6659. TEST(UploadProgressTest, PutStringBodyBasic) {
  6660. TestStringBodyUploadProgress(
  6661. [](Server &svr) {
  6662. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6663. res.set_content("put received", "text/plain");
  6664. });
  6665. },
  6666. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6667. return cli.Put("/test", body, "text/plain", progress_callback);
  6668. },
  6669. "put test data for upload progress");
  6670. }
  6671. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6672. TestStringBodyUploadProgress(
  6673. [](Server &svr) {
  6674. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6675. res.set_content("patch received", "text/plain");
  6676. });
  6677. },
  6678. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6679. return cli.Patch("/test", body, "text/plain", progress_callback);
  6680. },
  6681. "patch test data for upload progress");
  6682. }
  6683. // Helper function for content provider upload progress tests
  6684. template <typename SetupHandler, typename ClientCall>
  6685. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6686. ClientCall &&client_call) {
  6687. Server svr;
  6688. setup_handler(svr);
  6689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6690. auto se = detail::scope_exit([&] {
  6691. svr.stop();
  6692. t.join();
  6693. });
  6694. svr.wait_until_ready();
  6695. Client cli(HOST, PORT);
  6696. vector<uint64_t> progress_values;
  6697. auto res =
  6698. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6699. progress_values.push_back(current);
  6700. return true;
  6701. });
  6702. ASSERT_TRUE(res);
  6703. EXPECT_EQ(200, res->status);
  6704. EXPECT_FALSE(progress_values.empty());
  6705. }
  6706. TEST(UploadProgressTest, PostContentProviderProgress) {
  6707. TestContentProviderUploadProgress(
  6708. [](Server &svr) {
  6709. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6710. res.set_content("provider received", "text/plain");
  6711. });
  6712. },
  6713. [](Client &cli, UploadProgress progress_callback) {
  6714. return cli.Post(
  6715. "/test", 10,
  6716. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6717. sink.os << "test data";
  6718. return true;
  6719. },
  6720. "text/plain", progress_callback);
  6721. });
  6722. }
  6723. // Helper function for multipart upload progress tests
  6724. template <typename SetupHandler, typename ClientCall>
  6725. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6726. ClientCall &&client_call,
  6727. const string &endpoint) {
  6728. Server svr;
  6729. setup_handler(svr);
  6730. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6731. auto se = detail::scope_exit([&] {
  6732. svr.stop();
  6733. t.join();
  6734. });
  6735. svr.wait_until_ready();
  6736. Client cli(HOST, PORT);
  6737. vector<uint64_t> progress_values;
  6738. UploadFormDataItems items = {
  6739. {"field1", "value1", "", ""},
  6740. {"field2", "longer value for progress tracking test", "", ""},
  6741. {"file1", "file content data for upload progress", "test.txt",
  6742. "text/plain"}};
  6743. auto res = client_call(cli, endpoint, items,
  6744. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6745. progress_values.push_back(current);
  6746. return true;
  6747. });
  6748. ASSERT_TRUE(res);
  6749. EXPECT_EQ(200, res->status);
  6750. EXPECT_FALSE(progress_values.empty());
  6751. }
  6752. TEST(UploadProgressTest, PostMultipartProgress) {
  6753. TestMultipartUploadProgress(
  6754. [](Server &svr) {
  6755. svr.Post("/multipart", [](const Request &req, Response &res) {
  6756. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6757. res.set_content("multipart received", "text/plain");
  6758. });
  6759. },
  6760. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6761. UploadProgress progress_callback) {
  6762. return cli.Post(endpoint, items, progress_callback);
  6763. },
  6764. "/multipart");
  6765. }
  6766. // Helper function for basic download progress tests
  6767. template <typename SetupHandler, typename ClientCall>
  6768. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6769. ClientCall &&client_call, const string &endpoint,
  6770. size_t expected_content_size) {
  6771. Server svr;
  6772. setup_handler(svr);
  6773. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6774. auto se = detail::scope_exit([&] {
  6775. svr.stop();
  6776. t.join();
  6777. });
  6778. svr.wait_until_ready();
  6779. Client cli(HOST, PORT);
  6780. vector<uint64_t> progress_values;
  6781. auto res = client_call(cli, endpoint,
  6782. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6783. progress_values.push_back(current);
  6784. return true;
  6785. });
  6786. ASSERT_TRUE(res);
  6787. EXPECT_EQ(200, res->status);
  6788. EXPECT_FALSE(progress_values.empty());
  6789. EXPECT_EQ(expected_content_size, res->body.size());
  6790. }
  6791. TEST(DownloadProgressTest, GetBasic) {
  6792. TestBasicDownloadProgress(
  6793. [](Server &svr) {
  6794. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6795. string content(1000, 'D');
  6796. res.set_content(content, "text/plain");
  6797. });
  6798. },
  6799. [](Client &cli, const string &endpoint,
  6800. DownloadProgress progress_callback) {
  6801. return cli.Get(endpoint, progress_callback);
  6802. },
  6803. "/download", 1000u);
  6804. }
  6805. // Helper function for content receiver download progress tests
  6806. template <typename SetupHandler, typename ClientCall>
  6807. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6808. ClientCall &&client_call,
  6809. const string &endpoint,
  6810. size_t expected_content_size) {
  6811. Server svr;
  6812. setup_handler(svr);
  6813. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6814. auto se = detail::scope_exit([&] {
  6815. svr.stop();
  6816. t.join();
  6817. });
  6818. svr.wait_until_ready();
  6819. Client cli(HOST, PORT);
  6820. vector<uint64_t> progress_values;
  6821. string received_body;
  6822. auto res = client_call(
  6823. cli, endpoint,
  6824. [&](const char *data, size_t data_length) -> bool {
  6825. received_body.append(data, data_length);
  6826. return true;
  6827. },
  6828. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6829. progress_values.push_back(current);
  6830. return true;
  6831. });
  6832. ASSERT_TRUE(res);
  6833. EXPECT_EQ(200, res->status);
  6834. EXPECT_FALSE(progress_values.empty());
  6835. EXPECT_EQ(expected_content_size, received_body.size());
  6836. EXPECT_TRUE(res->body.empty());
  6837. }
  6838. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6839. TestContentReceiverDownloadProgress(
  6840. [](Server &svr) {
  6841. svr.Get("/download-receiver",
  6842. [](const Request & /*req*/, Response &res) {
  6843. string content(2000, 'R');
  6844. res.set_content(content, "text/plain");
  6845. });
  6846. },
  6847. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6848. DownloadProgress progress_callback) {
  6849. return cli.Get(endpoint, content_receiver, progress_callback);
  6850. },
  6851. "/download-receiver", 2000u);
  6852. }
  6853. TEST(StreamingTest, NoContentLengthStreaming) {
  6854. Server svr;
  6855. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6856. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6857. if (offset < 6) {
  6858. sink.os << (offset < 3 ? "a" : "b");
  6859. } else {
  6860. sink.done();
  6861. }
  6862. return true;
  6863. });
  6864. });
  6865. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6866. auto listen_se = detail::scope_exit([&] {
  6867. svr.stop();
  6868. listen_thread.join();
  6869. ASSERT_FALSE(svr.is_running());
  6870. });
  6871. svr.wait_until_ready();
  6872. Client client(HOST, PORT);
  6873. auto get_thread = std::thread([&client]() {
  6874. std::string s;
  6875. auto res =
  6876. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6877. s += std::string(data, len);
  6878. return true;
  6879. });
  6880. ASSERT_TRUE(res);
  6881. EXPECT_EQ(StatusCode::OK_200, res->status);
  6882. EXPECT_EQ("aaabbb", s);
  6883. });
  6884. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6885. // Give GET time to get a few messages.
  6886. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6887. }
  6888. TEST(MountTest, Unmount) {
  6889. Server svr;
  6890. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6891. auto se = detail::scope_exit([&] {
  6892. svr.stop();
  6893. listen_thread.join();
  6894. ASSERT_FALSE(svr.is_running());
  6895. });
  6896. svr.wait_until_ready();
  6897. Client cli("localhost", PORT);
  6898. svr.set_mount_point("/mount2", "./www2");
  6899. auto res = cli.Get("/");
  6900. ASSERT_TRUE(res);
  6901. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6902. res = cli.Get("/mount2/dir/test.html");
  6903. ASSERT_TRUE(res);
  6904. EXPECT_EQ(StatusCode::OK_200, res->status);
  6905. svr.set_mount_point("/", "./www");
  6906. res = cli.Get("/dir/");
  6907. ASSERT_TRUE(res);
  6908. EXPECT_EQ(StatusCode::OK_200, res->status);
  6909. svr.remove_mount_point("/");
  6910. res = cli.Get("/dir/");
  6911. ASSERT_TRUE(res);
  6912. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6913. svr.remove_mount_point("/mount2");
  6914. res = cli.Get("/mount2/dir/test.html");
  6915. ASSERT_TRUE(res);
  6916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6917. }
  6918. TEST(MountTest, Redicect) {
  6919. Server svr;
  6920. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6921. auto se = detail::scope_exit([&] {
  6922. svr.stop();
  6923. listen_thread.join();
  6924. ASSERT_FALSE(svr.is_running());
  6925. });
  6926. svr.set_mount_point("/", "./www");
  6927. svr.wait_until_ready();
  6928. Client cli("localhost", PORT);
  6929. auto res = cli.Get("/dir/");
  6930. ASSERT_TRUE(res);
  6931. EXPECT_EQ(StatusCode::OK_200, res->status);
  6932. res = cli.Get("/dir");
  6933. ASSERT_TRUE(res);
  6934. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6935. res = cli.Get("/file");
  6936. ASSERT_TRUE(res);
  6937. EXPECT_EQ(StatusCode::OK_200, res->status);
  6938. res = cli.Get("/file/");
  6939. ASSERT_TRUE(res);
  6940. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6941. cli.set_follow_location(true);
  6942. res = cli.Get("/dir");
  6943. ASSERT_TRUE(res);
  6944. EXPECT_EQ(StatusCode::OK_200, res->status);
  6945. }
  6946. TEST(MountTest, MultibytesPathName) {
  6947. Server svr;
  6948. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6949. auto se = detail::scope_exit([&] {
  6950. svr.stop();
  6951. listen_thread.join();
  6952. ASSERT_FALSE(svr.is_running());
  6953. });
  6954. svr.set_mount_point("/", "./www");
  6955. svr.wait_until_ready();
  6956. Client cli("localhost", PORT);
  6957. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6958. ASSERT_TRUE(res);
  6959. EXPECT_EQ(StatusCode::OK_200, res->status);
  6960. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6961. }
  6962. #ifdef _WIN32
  6963. // Issue #2435: mmap::open() must succeed even when another handle holds
  6964. // the file open for writing (e.g. an active log file).
  6965. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  6966. const char *path = "mmap_concurrent_writer_test.txt";
  6967. const char *content = "hello";
  6968. {
  6969. std::ofstream f(path, std::ios::binary);
  6970. f.write(content, static_cast<std::streamsize>(strlen(content)));
  6971. }
  6972. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  6973. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  6974. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  6975. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  6976. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  6977. detail::mmap m(path);
  6978. ASSERT_TRUE(m.is_open());
  6979. EXPECT_EQ(strlen(content), m.size());
  6980. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  6981. }
  6982. #endif
  6983. TEST(KeepAliveTest, ReadTimeout) {
  6984. Server svr;
  6985. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6986. std::this_thread::sleep_for(std::chrono::seconds(2));
  6987. res.set_content("a", "text/plain");
  6988. });
  6989. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6990. res.set_content("b", "text/plain");
  6991. });
  6992. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6993. auto se = detail::scope_exit([&] {
  6994. svr.stop();
  6995. listen_thread.join();
  6996. ASSERT_FALSE(svr.is_running());
  6997. });
  6998. svr.wait_until_ready();
  6999. Client cli("localhost", PORT);
  7000. cli.set_keep_alive(true);
  7001. cli.set_read_timeout(std::chrono::seconds(1));
  7002. auto resa = cli.Get("/a");
  7003. ASSERT_FALSE(resa);
  7004. EXPECT_EQ(Error::Read, resa.error());
  7005. auto resb = cli.Get("/b");
  7006. ASSERT_TRUE(resb);
  7007. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7008. EXPECT_EQ("b", resb->body);
  7009. }
  7010. TEST(KeepAliveTest, MaxCount) {
  7011. size_t keep_alive_max_count = 3;
  7012. Server svr;
  7013. svr.set_keep_alive_max_count(keep_alive_max_count);
  7014. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7015. res.set_content("Hello World!", "text/plain");
  7016. });
  7017. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7018. auto se = detail::scope_exit([&] {
  7019. svr.stop();
  7020. listen_thread.join();
  7021. ASSERT_FALSE(svr.is_running());
  7022. });
  7023. svr.wait_until_ready();
  7024. Client cli(HOST, PORT);
  7025. cli.set_keep_alive(true);
  7026. for (size_t i = 0; i < 5; i++) {
  7027. auto result = cli.Get("/hi");
  7028. ASSERT_TRUE(result);
  7029. EXPECT_EQ(StatusCode::OK_200, result->status);
  7030. if (i == keep_alive_max_count - 1) {
  7031. EXPECT_EQ("close", result->get_header_value("Connection"));
  7032. } else {
  7033. EXPECT_FALSE(result->has_header("Connection"));
  7034. }
  7035. }
  7036. }
  7037. TEST(KeepAliveTest, Issue1041) {
  7038. Server svr;
  7039. svr.set_keep_alive_timeout(3);
  7040. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7041. res.set_content("Hello World!", "text/plain");
  7042. });
  7043. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7044. auto se = detail::scope_exit([&] {
  7045. svr.stop();
  7046. listen_thread.join();
  7047. ASSERT_FALSE(svr.is_running());
  7048. });
  7049. svr.wait_until_ready();
  7050. Client cli(HOST, PORT);
  7051. cli.set_keep_alive(true);
  7052. auto result = cli.Get("/hi");
  7053. ASSERT_TRUE(result);
  7054. EXPECT_EQ(StatusCode::OK_200, result->status);
  7055. std::this_thread::sleep_for(std::chrono::seconds(5));
  7056. result = cli.Get("/hi");
  7057. ASSERT_TRUE(result);
  7058. EXPECT_EQ(StatusCode::OK_200, result->status);
  7059. }
  7060. TEST(KeepAliveTest, Issue1959) {
  7061. Server svr;
  7062. svr.set_keep_alive_timeout(5);
  7063. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7064. res.set_content("a", "text/plain");
  7065. });
  7066. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7067. auto se = detail::scope_exit([&] {
  7068. if (!svr.is_running()) return;
  7069. svr.stop();
  7070. listen_thread.join();
  7071. ASSERT_FALSE(svr.is_running());
  7072. });
  7073. svr.wait_until_ready();
  7074. Client cli("localhost", PORT);
  7075. cli.set_keep_alive(true);
  7076. using namespace std::chrono;
  7077. auto start = steady_clock::now();
  7078. cli.Get("/a");
  7079. svr.stop();
  7080. listen_thread.join();
  7081. auto end = steady_clock::now();
  7082. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7083. EXPECT_LT(elapsed, 5000);
  7084. }
  7085. #ifdef CPPHTTPLIB_SSL_ENABLED
  7086. TEST(KeepAliveTest, SSLClientReconnection) {
  7087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7088. ASSERT_TRUE(svr.is_valid());
  7089. svr.set_keep_alive_timeout(1);
  7090. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7091. res.set_content("Hello World!", "text/plain");
  7092. });
  7093. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7094. auto se = detail::scope_exit([&] {
  7095. svr.stop();
  7096. listen_thread.join();
  7097. ASSERT_FALSE(svr.is_running());
  7098. });
  7099. svr.wait_until_ready();
  7100. SSLClient cli(HOST, PORT);
  7101. cli.enable_server_certificate_verification(false);
  7102. cli.set_keep_alive(true);
  7103. auto result = cli.Get("/hi");
  7104. ASSERT_TRUE(result);
  7105. EXPECT_EQ(StatusCode::OK_200, result->status);
  7106. result = cli.Get("/hi");
  7107. ASSERT_TRUE(result);
  7108. EXPECT_EQ(StatusCode::OK_200, result->status);
  7109. std::this_thread::sleep_for(std::chrono::seconds(2));
  7110. // Recoonect
  7111. result = cli.Get("/hi");
  7112. ASSERT_TRUE(result);
  7113. EXPECT_EQ(StatusCode::OK_200, result->status);
  7114. result = cli.Get("/hi");
  7115. ASSERT_TRUE(result);
  7116. EXPECT_EQ(StatusCode::OK_200, result->status);
  7117. }
  7118. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7120. ASSERT_TRUE(svr.is_valid());
  7121. svr.set_keep_alive_timeout(1);
  7122. std::string content = "reconnect";
  7123. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7124. res.set_content("Hello World!", "text/plain");
  7125. });
  7126. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7127. auto se = detail::scope_exit([&] {
  7128. svr.stop();
  7129. listen_thread.join();
  7130. ASSERT_FALSE(svr.is_running());
  7131. });
  7132. svr.wait_until_ready();
  7133. SSLClient cli(HOST, PORT);
  7134. cli.enable_server_certificate_verification(false);
  7135. cli.set_keep_alive(true);
  7136. auto result = cli.Post(
  7137. "/hi", content.size(),
  7138. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7139. sink.write(content.c_str(), content.size());
  7140. return true;
  7141. },
  7142. "text/plain");
  7143. ASSERT_TRUE(result);
  7144. EXPECT_EQ(200, result->status);
  7145. std::this_thread::sleep_for(std::chrono::seconds(2));
  7146. // Recoonect
  7147. result = cli.Post(
  7148. "/hi", content.size(),
  7149. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7150. sink.write(content.c_str(), content.size());
  7151. return true;
  7152. },
  7153. "text/plain");
  7154. ASSERT_TRUE(result);
  7155. EXPECT_EQ(200, result->status);
  7156. result = cli.Post(
  7157. "/hi", content.size(),
  7158. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7159. sink.write(content.c_str(), content.size());
  7160. return true;
  7161. },
  7162. "text/plain");
  7163. ASSERT_TRUE(result);
  7164. EXPECT_EQ(200, result->status);
  7165. }
  7166. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7167. using namespace httplib::tls;
  7168. {
  7169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7170. ASSERT_TRUE(svr.is_valid());
  7171. svr.Get("/sni", [&](const Request &req, Response &res) {
  7172. std::string expected = req.sni();
  7173. EXPECT_EQ(expected, req.get_param_value("expected"));
  7174. res.set_content("ok", "text/plain");
  7175. });
  7176. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7177. auto se = detail::scope_exit([&] {
  7178. svr.stop();
  7179. listen_thread.join();
  7180. ASSERT_FALSE(svr.is_running());
  7181. });
  7182. svr.wait_until_ready();
  7183. {
  7184. SSLClient cli("localhost", PORT);
  7185. cli.enable_server_certificate_verification(false);
  7186. auto res = cli.Get("/sni?expected=localhost");
  7187. ASSERT_TRUE(res);
  7188. }
  7189. {
  7190. SSLClient cli("::1", PORT);
  7191. cli.enable_server_certificate_verification(false);
  7192. auto res = cli.Get("/sni?expected=");
  7193. // NOTE: This may fail if the server is listening on IPv4 only
  7194. // (e.g., when localhost resolves to 127.0.0.1 only)
  7195. if (res) {
  7196. EXPECT_EQ(StatusCode::OK_200, res->status);
  7197. } else {
  7198. EXPECT_EQ(Error::Connection, res.error());
  7199. }
  7200. }
  7201. }
  7202. }
  7203. #endif
  7204. TEST(ClientProblemDetectionTest, ContentProvider) {
  7205. Server svr;
  7206. size_t content_length = 1024 * 1024;
  7207. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7208. res.set_content_provider(
  7209. content_length, "text/plain",
  7210. [&](size_t offset, size_t length, DataSink &sink) {
  7211. auto out_len = std::min(length, static_cast<size_t>(1024));
  7212. std::string out(out_len, '@');
  7213. sink.write(out.data(), out_len);
  7214. return offset < 4096;
  7215. },
  7216. [](bool success) { ASSERT_FALSE(success); });
  7217. });
  7218. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7219. res.set_content_provider(
  7220. 0, "text/plain",
  7221. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7222. EXPECT_TRUE(false);
  7223. return true;
  7224. },
  7225. [](bool success) { ASSERT_FALSE(success); });
  7226. });
  7227. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7228. auto se = detail::scope_exit([&] {
  7229. svr.stop();
  7230. listen_thread.join();
  7231. ASSERT_FALSE(svr.is_running());
  7232. });
  7233. svr.wait_until_ready();
  7234. Client cli("localhost", PORT);
  7235. {
  7236. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7237. size_t /*data_length*/) { return false; });
  7238. ASSERT_FALSE(res);
  7239. }
  7240. {
  7241. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7242. size_t /*data_length*/) { return false; });
  7243. ASSERT_TRUE(res);
  7244. }
  7245. }
  7246. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7247. Server svr;
  7248. svr.set_error_handler([](Request const &, Response &res) -> void {
  7249. res.set_chunked_content_provider(
  7250. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7251. sink.os << "hello";
  7252. sink.os << "world";
  7253. sink.done();
  7254. return true;
  7255. });
  7256. });
  7257. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7258. auto se = detail::scope_exit([&] {
  7259. svr.stop();
  7260. listen_thread.join();
  7261. ASSERT_FALSE(svr.is_running());
  7262. });
  7263. svr.wait_until_ready();
  7264. Client cli("localhost", PORT);
  7265. auto res = cli.Get("/");
  7266. ASSERT_TRUE(res);
  7267. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7268. EXPECT_EQ("helloworld", res->body);
  7269. }
  7270. TEST(LongPollingTest, ClientCloseDetection) {
  7271. Server svr;
  7272. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7273. res.set_chunked_content_provider(
  7274. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7275. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7276. sink.os << "hello";
  7277. auto count = 10;
  7278. while (count > 0 && sink.is_writable()) {
  7279. this_thread::sleep_for(chrono::milliseconds(10));
  7280. count--;
  7281. }
  7282. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7283. return true;
  7284. });
  7285. });
  7286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7287. auto se = detail::scope_exit([&] {
  7288. svr.stop();
  7289. listen_thread.join();
  7290. ASSERT_FALSE(svr.is_running());
  7291. });
  7292. svr.wait_until_ready();
  7293. Client cli("localhost", PORT);
  7294. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7295. EXPECT_EQ("hello", string(data, data_length));
  7296. return false; // close the socket immediately.
  7297. });
  7298. ASSERT_FALSE(res);
  7299. }
  7300. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7301. Server svr;
  7302. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7303. res.set_chunked_content_provider(
  7304. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7305. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7306. sink.os << "hello";
  7307. EXPECT_TRUE(sink.os.good());
  7308. // Wait for the client to close the connection
  7309. auto count = 10;
  7310. while (count > 0 && sink.is_writable()) {
  7311. this_thread::sleep_for(chrono::milliseconds(10));
  7312. count--;
  7313. }
  7314. // After client disconnect, write repeatedly until the socket
  7315. // write actually fails (small writes may be absorbed by the
  7316. // kernel buffer)
  7317. std::string chunk(1024, 'x');
  7318. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7319. sink.os << chunk;
  7320. }
  7321. EXPECT_TRUE(sink.os.fail());
  7322. return true;
  7323. });
  7324. });
  7325. auto port = svr.bind_to_any_port("localhost");
  7326. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7327. auto se = detail::scope_exit([&] {
  7328. svr.stop();
  7329. listen_thread.join();
  7330. ASSERT_FALSE(svr.is_running());
  7331. });
  7332. svr.wait_until_ready();
  7333. Client cli("localhost", port);
  7334. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7335. EXPECT_EQ("hello", string(data, data_length));
  7336. return false; // close the socket immediately.
  7337. });
  7338. ASSERT_FALSE(res);
  7339. }
  7340. TEST(GetWithParametersTest, GetWithParameters) {
  7341. Server svr;
  7342. svr.Get("/", [&](const Request &req, Response &) {
  7343. EXPECT_EQ("world", req.get_param_value("hello"));
  7344. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7345. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7346. });
  7347. svr.Get("/params", [&](const Request &req, Response &) {
  7348. EXPECT_EQ("world", req.get_param_value("hello"));
  7349. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7350. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7351. });
  7352. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7353. EXPECT_EQ("resource-id", req.matches[1]);
  7354. EXPECT_EQ("foo", req.get_param_value("param1"));
  7355. EXPECT_EQ("bar", req.get_param_value("param2"));
  7356. });
  7357. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7358. EXPECT_EQ("user-id", req.path_params.at("id"));
  7359. EXPECT_EQ("foo", req.get_param_value("param1"));
  7360. EXPECT_EQ("bar", req.get_param_value("param2"));
  7361. });
  7362. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7363. auto se = detail::scope_exit([&] {
  7364. svr.stop();
  7365. listen_thread.join();
  7366. ASSERT_FALSE(svr.is_running());
  7367. });
  7368. svr.wait_until_ready();
  7369. {
  7370. Client cli(HOST, PORT);
  7371. Params params;
  7372. params.emplace("hello", "world");
  7373. params.emplace("hello2", "world2");
  7374. params.emplace("hello3", "world3");
  7375. auto res = cli.Get("/", params, Headers{});
  7376. ASSERT_TRUE(res);
  7377. EXPECT_EQ(StatusCode::OK_200, res->status);
  7378. }
  7379. {
  7380. Client cli(HOST, PORT);
  7381. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7382. ASSERT_TRUE(res);
  7383. EXPECT_EQ(StatusCode::OK_200, res->status);
  7384. }
  7385. {
  7386. Client cli(HOST, PORT);
  7387. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7388. ASSERT_TRUE(res);
  7389. EXPECT_EQ(StatusCode::OK_200, res->status);
  7390. }
  7391. {
  7392. Client cli(HOST, PORT);
  7393. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7394. ASSERT_TRUE(res);
  7395. EXPECT_EQ(StatusCode::OK_200, res->status);
  7396. }
  7397. }
  7398. TEST(GetWithParametersTest, GetWithParameters2) {
  7399. Server svr;
  7400. svr.Get("/", [&](const Request &req, Response &res) {
  7401. auto text = req.get_param_value("hello");
  7402. res.set_content(text, "text/plain");
  7403. });
  7404. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7405. auto se = detail::scope_exit([&] {
  7406. svr.stop();
  7407. listen_thread.join();
  7408. ASSERT_FALSE(svr.is_running());
  7409. });
  7410. svr.wait_until_ready();
  7411. Client cli("localhost", PORT);
  7412. Params params;
  7413. params.emplace("hello", "world");
  7414. std::string body;
  7415. auto res = cli.Get("/", params, Headers{},
  7416. [&](const char *data, size_t data_length) {
  7417. body.append(data, data_length);
  7418. return true;
  7419. });
  7420. ASSERT_TRUE(res);
  7421. EXPECT_EQ(StatusCode::OK_200, res->status);
  7422. EXPECT_EQ("world", body);
  7423. }
  7424. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7425. auto host = "httpbingo.org";
  7426. auto path = std::string{"/range/32"};
  7427. #ifdef CPPHTTPLIB_SSL_ENABLED
  7428. SSLClient cli(host);
  7429. #else
  7430. Client cli(host);
  7431. #endif
  7432. cli.set_default_headers({make_range_header({{1, 10}})});
  7433. cli.set_connection_timeout(5);
  7434. {
  7435. auto res = cli.Get(path);
  7436. ASSERT_TRUE(res);
  7437. EXPECT_EQ("bcdefghijk", res->body);
  7438. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7439. }
  7440. {
  7441. auto res = cli.Get(path);
  7442. ASSERT_TRUE(res);
  7443. EXPECT_EQ("bcdefghijk", res->body);
  7444. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7445. }
  7446. }
  7447. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7448. Server svr;
  7449. svr.set_default_headers({{"Hello", "World"}});
  7450. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7451. res.set_content("ok", "text/plain");
  7452. });
  7453. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7454. auto se = detail::scope_exit([&] {
  7455. svr.stop();
  7456. listen_thread.join();
  7457. ASSERT_FALSE(svr.is_running());
  7458. });
  7459. svr.wait_until_ready();
  7460. Client cli("localhost", PORT);
  7461. auto res = cli.Get("/");
  7462. ASSERT_TRUE(res);
  7463. EXPECT_EQ(StatusCode::OK_200, res->status);
  7464. EXPECT_EQ("ok", res->body);
  7465. EXPECT_EQ("World", res->get_header_value("Hello"));
  7466. }
  7467. #ifdef CPPHTTPLIB_SSL_ENABLED
  7468. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7469. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7470. ASSERT_TRUE(svr.is_valid());
  7471. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7472. std::this_thread::sleep_for(std::chrono::seconds(2));
  7473. res.set_content("a", "text/plain");
  7474. });
  7475. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7476. res.set_content("b", "text/plain");
  7477. });
  7478. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7479. auto se = detail::scope_exit([&] {
  7480. svr.stop();
  7481. listen_thread.join();
  7482. ASSERT_FALSE(svr.is_running());
  7483. });
  7484. svr.wait_until_ready();
  7485. SSLClient cli("localhost", PORT);
  7486. cli.enable_server_certificate_verification(false);
  7487. cli.set_keep_alive(true);
  7488. cli.set_read_timeout(std::chrono::seconds(1));
  7489. auto resa = cli.Get("/a");
  7490. ASSERT_TRUE(!resa);
  7491. EXPECT_EQ(Error::Read, resa.error());
  7492. auto resb = cli.Get("/b");
  7493. ASSERT_TRUE(resb);
  7494. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7495. EXPECT_EQ("b", resb->body);
  7496. }
  7497. #endif
  7498. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7499. protected:
  7500. ServerTestWithAI_PASSIVE()
  7501. : cli_(HOST, PORT)
  7502. #ifdef CPPHTTPLIB_SSL_ENABLED
  7503. ,
  7504. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7505. #endif
  7506. {
  7507. #ifdef CPPHTTPLIB_SSL_ENABLED
  7508. cli_.enable_server_certificate_verification(false);
  7509. #endif
  7510. }
  7511. virtual void SetUp() {
  7512. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7513. res.set_content("Hello World!", "text/plain");
  7514. });
  7515. t_ = thread(
  7516. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7517. svr_.wait_until_ready();
  7518. }
  7519. virtual void TearDown() {
  7520. svr_.stop();
  7521. t_.join();
  7522. }
  7523. #ifdef CPPHTTPLIB_SSL_ENABLED
  7524. SSLClient cli_;
  7525. SSLServer svr_;
  7526. #else
  7527. Client cli_;
  7528. Server svr_;
  7529. #endif
  7530. thread t_;
  7531. };
  7532. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7533. auto res = cli_.Get("/hi");
  7534. ASSERT_TRUE(res);
  7535. EXPECT_EQ(StatusCode::OK_200, res->status);
  7536. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7537. EXPECT_EQ("Hello World!", res->body);
  7538. }
  7539. class ServerUpDownTest : public ::testing::Test {
  7540. protected:
  7541. ServerUpDownTest() : cli_(HOST, PORT) {}
  7542. virtual void SetUp() {
  7543. t_ = thread([&]() {
  7544. svr_.bind_to_any_port(HOST);
  7545. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7546. ASSERT_TRUE(svr_.listen_after_bind());
  7547. });
  7548. svr_.wait_until_ready();
  7549. }
  7550. virtual void TearDown() {
  7551. svr_.stop();
  7552. t_.join();
  7553. }
  7554. Client cli_;
  7555. Server svr_;
  7556. thread t_;
  7557. };
  7558. TEST_F(ServerUpDownTest, QuickStartStop) {
  7559. // Should not crash, especially when run with
  7560. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7561. }
  7562. class PayloadMaxLengthTest : public ::testing::Test {
  7563. protected:
  7564. PayloadMaxLengthTest()
  7565. : cli_(HOST, PORT)
  7566. #ifdef CPPHTTPLIB_SSL_ENABLED
  7567. ,
  7568. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7569. #endif
  7570. {
  7571. #ifdef CPPHTTPLIB_SSL_ENABLED
  7572. cli_.enable_server_certificate_verification(false);
  7573. #endif
  7574. }
  7575. virtual void SetUp() {
  7576. svr_.set_payload_max_length(8);
  7577. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7578. res.set_content("test", "text/plain");
  7579. });
  7580. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7581. svr_.wait_until_ready();
  7582. }
  7583. virtual void TearDown() {
  7584. svr_.stop();
  7585. t_.join();
  7586. }
  7587. #ifdef CPPHTTPLIB_SSL_ENABLED
  7588. SSLClient cli_;
  7589. SSLServer svr_;
  7590. #else
  7591. Client cli_;
  7592. Server svr_;
  7593. #endif
  7594. thread t_;
  7595. };
  7596. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7597. auto res = cli_.Post("/test", "123456789", "text/plain");
  7598. ASSERT_TRUE(res);
  7599. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7600. res = cli_.Post("/test", "12345678", "text/plain");
  7601. ASSERT_TRUE(res);
  7602. EXPECT_EQ(StatusCode::OK_200, res->status);
  7603. }
  7604. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7605. // Test chunked encoding with payload exceeding the 8-byte limit
  7606. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7607. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7608. ASSERT_TRUE(res);
  7609. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7610. }
  7611. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7612. // Test chunked encoding with payload within the 8-byte limit
  7613. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7614. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7615. ASSERT_TRUE(res);
  7616. EXPECT_EQ(StatusCode::OK_200, res->status);
  7617. }
  7618. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7619. // Test using send_request to send chunked data exceeding payload limit
  7620. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7621. "Host: " +
  7622. std::string(HOST) + ":" + std::to_string(PORT) +
  7623. "\r\n"
  7624. "Transfer-Encoding: chunked\r\n"
  7625. "Connection: close\r\n"
  7626. "\r\n"
  7627. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7628. "0123456789\r\n"
  7629. "0\r\n" // End chunk
  7630. "\r\n";
  7631. std::string response;
  7632. bool result = send_request(1, chunked_request, &response);
  7633. if (!result) {
  7634. // If send_request fails, it might be because the server closed the
  7635. // connection due to payload limit enforcement, which is acceptable
  7636. SUCCEED()
  7637. << "Server rejected oversized chunked request (connection closed)";
  7638. } else {
  7639. // If we got a response, check if it's an error response or connection was
  7640. // closed early Short response length indicates connection was closed due to
  7641. // payload limit
  7642. if (response.length() <= 10) {
  7643. SUCCEED() << "Server closed connection for oversized chunked request";
  7644. } else {
  7645. // Check for error status codes
  7646. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7647. response.find("Payload Too Large") != std::string::npos ||
  7648. response.find("400") != std::string::npos);
  7649. }
  7650. }
  7651. }
  7652. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7653. // Test request without Content-Length header exceeding payload limit
  7654. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7655. "Host: " +
  7656. std::string(HOST) + ":" +
  7657. std::to_string(PORT) +
  7658. "\r\n"
  7659. "Connection: close\r\n"
  7660. "\r\n";
  7661. // Add payload exceeding the 8-byte limit
  7662. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7663. request_without_content_length += large_payload;
  7664. std::string response;
  7665. bool result = send_request(1, request_without_content_length, &response);
  7666. if (!result) {
  7667. // If send_request fails, server likely closed connection due to payload
  7668. // limit
  7669. SUCCEED() << "Server rejected oversized request without Content-Length "
  7670. "(connection closed)";
  7671. } else {
  7672. // Check if server responded with error or closed connection early
  7673. if (response.length() <= 10) {
  7674. SUCCEED() << "Server closed connection for oversized request without "
  7675. "Content-Length";
  7676. } else {
  7677. // Check for error status codes
  7678. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7679. response.find("Payload Too Large") != std::string::npos ||
  7680. response.find("400") != std::string::npos);
  7681. }
  7682. }
  7683. }
  7684. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7685. // Test request without Content-Length header within payload limit
  7686. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7687. "Host: " +
  7688. std::string(HOST) + ":" +
  7689. std::to_string(PORT) +
  7690. "\r\n"
  7691. "Connection: close\r\n"
  7692. "\r\n";
  7693. // Add payload within the 8-byte limit
  7694. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7695. request_without_content_length += small_payload;
  7696. std::string response;
  7697. bool result = send_request(1, request_without_content_length, &response);
  7698. // For requests without Content-Length, the server may have different behavior
  7699. // The key is that it should not reject due to payload limit for small
  7700. // payloads
  7701. if (result) {
  7702. // Check for any HTTP response (success or error, but not connection closed)
  7703. if (response.length() > 10) {
  7704. SUCCEED()
  7705. << "Server processed request without Content-Length within limit";
  7706. } else {
  7707. // Short response might indicate connection closed, which is acceptable
  7708. SUCCEED() << "Server closed connection for request without "
  7709. "Content-Length (acceptable behavior)";
  7710. }
  7711. } else {
  7712. // Connection failure might be due to protocol requirements
  7713. SUCCEED() << "Connection issue with request without Content-Length "
  7714. "(environment-specific)";
  7715. }
  7716. }
  7717. class LargePayloadMaxLengthTest : public ::testing::Test {
  7718. protected:
  7719. LargePayloadMaxLengthTest()
  7720. : cli_(HOST, PORT)
  7721. #ifdef CPPHTTPLIB_SSL_ENABLED
  7722. ,
  7723. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7724. #endif
  7725. {
  7726. #ifdef CPPHTTPLIB_SSL_ENABLED
  7727. cli_.enable_server_certificate_verification(false);
  7728. #endif
  7729. }
  7730. virtual void SetUp() {
  7731. // Set 10MB payload limit
  7732. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7733. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7734. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7735. res.set_content("Large payload test", "text/plain");
  7736. });
  7737. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7738. svr_.wait_until_ready();
  7739. }
  7740. virtual void TearDown() {
  7741. svr_.stop();
  7742. t_.join();
  7743. }
  7744. #ifdef CPPHTTPLIB_SSL_ENABLED
  7745. SSLClient cli_;
  7746. SSLServer svr_;
  7747. #else
  7748. Client cli_;
  7749. Server svr_;
  7750. #endif
  7751. thread t_;
  7752. };
  7753. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7754. // Test chunked encoding with payload within 10MB limit
  7755. std::string medium_payload(5 * 1024 * 1024,
  7756. 'A'); // 5MB payload, within 10MB limit
  7757. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7758. ASSERT_TRUE(res);
  7759. EXPECT_EQ(StatusCode::OK_200, res->status);
  7760. }
  7761. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7762. // Test chunked encoding with payload exceeding 10MB limit
  7763. std::string large_payload(12 * 1024 * 1024,
  7764. 'B'); // 12MB payload, exceeds 10MB limit
  7765. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7766. // Server may either return 413 or close the connection
  7767. if (res) {
  7768. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7769. } else {
  7770. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7771. }
  7772. }
  7773. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7774. // Test request without Content-Length header within 10MB limit
  7775. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7776. "Host: " +
  7777. std::string(HOST) + ":" +
  7778. std::to_string(PORT) +
  7779. "\r\n"
  7780. "Connection: close\r\n"
  7781. "\r\n";
  7782. // Add 1MB payload (within 10MB limit)
  7783. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7784. request_without_content_length += medium_payload;
  7785. std::string response;
  7786. bool result = send_request(5, request_without_content_length, &response);
  7787. if (result) {
  7788. // Should get a proper HTTP response for payloads within limit
  7789. if (response.length() > 10) {
  7790. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7791. "10MB limit";
  7792. } else {
  7793. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7794. "Content-Length)";
  7795. }
  7796. } else {
  7797. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7798. }
  7799. }
  7800. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7801. // Test request without Content-Length header exceeding 10MB limit
  7802. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7803. "Host: " +
  7804. std::string(HOST) + ":" +
  7805. std::to_string(PORT) +
  7806. "\r\n"
  7807. "Connection: close\r\n"
  7808. "\r\n";
  7809. // Add 12MB payload (exceeds 10MB limit)
  7810. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7811. request_without_content_length += large_payload;
  7812. std::string response;
  7813. bool result = send_request(10, request_without_content_length, &response);
  7814. if (!result) {
  7815. // Server should close connection due to payload limit
  7816. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7817. "(connection closed)";
  7818. } else {
  7819. // Check for error response
  7820. if (response.length() <= 10) {
  7821. SUCCEED()
  7822. << "Server closed connection for 12MB request exceeding 10MB limit";
  7823. } else {
  7824. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7825. response.find("Payload Too Large") != std::string::npos ||
  7826. response.find("400") != std::string::npos);
  7827. }
  7828. }
  7829. }
  7830. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7831. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7832. // path.
  7833. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7834. Server svr;
  7835. const size_t LIMIT = 64 * 1024; // 64KB
  7836. svr.set_payload_max_length(LIMIT);
  7837. size_t total = 0;
  7838. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7839. const ContentReader &content_reader) {
  7840. content_reader([&](const char * /*data*/, size_t len) {
  7841. total += len;
  7842. return true;
  7843. });
  7844. res.status = 200;
  7845. res.set_content("stream_ok", "text/plain");
  7846. });
  7847. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7848. auto se = detail::scope_exit([&] {
  7849. svr.stop();
  7850. thread.join();
  7851. ASSERT_FALSE(svr.is_running());
  7852. });
  7853. svr.wait_until_ready();
  7854. // Prepare 256KB raw data and gzip-compress it
  7855. std::string raw(256 * 1024, 'A');
  7856. std::string gz;
  7857. {
  7858. z_stream zs{};
  7859. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7860. Z_DEFAULT_STRATEGY);
  7861. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7862. zs.avail_in = static_cast<uInt>(raw.size());
  7863. char outbuf[4096];
  7864. int ret;
  7865. do {
  7866. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7867. zs.avail_out = sizeof(outbuf);
  7868. ret = deflate(&zs, Z_FINISH);
  7869. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7870. } while (ret != Z_STREAM_END);
  7871. deflateEnd(&zs);
  7872. }
  7873. Client cli(HOST, PORT);
  7874. cli.set_connection_timeout(std::chrono::seconds(5));
  7875. Headers headers = {{"Content-Encoding", "gzip"}};
  7876. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7877. "application/octet-stream");
  7878. ASSERT_TRUE(res);
  7879. // Server must reject oversized decompressed payloads with 413.
  7880. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7881. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7882. EXPECT_LE(total, LIMIT);
  7883. }
  7884. #endif
  7885. // Regression test for DoS vulnerability: a malicious server sending a response
  7886. // without Content-Length header must not cause unbounded memory consumption on
  7887. // the client side. The client should stop reading after a reasonable limit,
  7888. // similar to the server-side set_payload_max_length protection.
  7889. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7890. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7891. #ifndef _WIN32
  7892. signal(SIGPIPE, SIG_IGN);
  7893. #endif
  7894. auto server_thread = std::thread([] {
  7895. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7896. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7897. default_socket_options(srv);
  7898. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7899. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7900. sockaddr_in addr{};
  7901. addr.sin_family = AF_INET;
  7902. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7903. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7904. int opt = 1;
  7905. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7906. #ifdef _WIN32
  7907. reinterpret_cast<const char *>(&opt),
  7908. #else
  7909. &opt,
  7910. #endif
  7911. sizeof(opt));
  7912. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7913. ::listen(srv, 1);
  7914. sockaddr_in cli_addr{};
  7915. socklen_t cli_len = sizeof(cli_addr);
  7916. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7917. if (cli != INVALID_SOCKET) {
  7918. char buf[4096];
  7919. ::recv(cli, buf, sizeof(buf), 0);
  7920. // Malicious response: no Content-Length, no chunked encoding
  7921. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7922. "Connection: close\r\n"
  7923. "\r\n";
  7924. ::send(cli,
  7925. #ifdef _WIN32
  7926. static_cast<const char *>(response_header.c_str()),
  7927. static_cast<int>(response_header.size()),
  7928. #else
  7929. response_header.c_str(), response_header.size(),
  7930. #endif
  7931. 0);
  7932. // Send 10MB of data
  7933. std::string chunk(64 * 1024, 'A');
  7934. size_t total_sent = 0;
  7935. while (total_sent < MALICIOUS_DATA_SIZE) {
  7936. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7937. auto sent = ::send(cli,
  7938. #ifdef _WIN32
  7939. static_cast<const char *>(chunk.c_str()),
  7940. static_cast<int>(to_send),
  7941. #else
  7942. chunk.c_str(), 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. detail::close_socket(srv);
  7951. });
  7952. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7953. size_t total_read = 0;
  7954. {
  7955. Client cli("127.0.0.1", PORT + 2);
  7956. cli.set_read_timeout(5, 0);
  7957. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7958. auto stream = cli.open_stream("GET", "/malicious");
  7959. ASSERT_TRUE(stream.is_valid());
  7960. char buffer[64 * 1024];
  7961. ssize_t n;
  7962. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7963. total_read += static_cast<size_t>(n);
  7964. }
  7965. } // StreamHandle and Client destroyed here, closing the socket
  7966. server_thread.join();
  7967. // With set_payload_max_length, the client must stop reading before consuming
  7968. // all 10MB. The read loop should be cut off at or near the configured limit.
  7969. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7970. << "Client read " << total_read << " bytes, exceeding the configured "
  7971. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7972. }
  7973. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7974. // the entire response body without truncation.
  7975. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7976. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7977. #ifndef _WIN32
  7978. signal(SIGPIPE, SIG_IGN);
  7979. #endif
  7980. auto server_thread = std::thread([] {
  7981. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7982. default_socket_options(srv);
  7983. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7984. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7985. sockaddr_in addr{};
  7986. addr.sin_family = AF_INET;
  7987. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7988. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7989. int opt = 1;
  7990. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7991. #ifdef _WIN32
  7992. reinterpret_cast<const char *>(&opt),
  7993. #else
  7994. &opt,
  7995. #endif
  7996. sizeof(opt));
  7997. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7998. ::listen(srv, 1);
  7999. sockaddr_in cli_addr{};
  8000. socklen_t cli_len = sizeof(cli_addr);
  8001. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8002. if (cli != INVALID_SOCKET) {
  8003. char buf[4096];
  8004. ::recv(cli, buf, sizeof(buf), 0);
  8005. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8006. "Connection: close\r\n"
  8007. "\r\n";
  8008. ::send(cli,
  8009. #ifdef _WIN32
  8010. static_cast<const char *>(response_header.c_str()),
  8011. static_cast<int>(response_header.size()),
  8012. #else
  8013. response_header.c_str(), response_header.size(),
  8014. #endif
  8015. 0);
  8016. std::string chunk(64 * 1024, 'A');
  8017. size_t total_sent = 0;
  8018. while (total_sent < DATA_SIZE) {
  8019. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8020. auto sent = ::send(cli,
  8021. #ifdef _WIN32
  8022. static_cast<const char *>(chunk.c_str()),
  8023. static_cast<int>(to_send),
  8024. #else
  8025. chunk.c_str(), to_send,
  8026. #endif
  8027. 0);
  8028. if (sent <= 0) break;
  8029. total_sent += static_cast<size_t>(sent);
  8030. }
  8031. #ifdef _WIN32
  8032. ::shutdown(cli, SD_SEND);
  8033. #else
  8034. ::shutdown(cli, SHUT_WR);
  8035. #endif
  8036. // Drain until the client closes its end, ensuring all data is delivered
  8037. char drain[1024];
  8038. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8039. detail::close_socket(cli);
  8040. }
  8041. detail::close_socket(srv);
  8042. });
  8043. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8044. size_t total_read = 0;
  8045. {
  8046. Client cli("127.0.0.1", PORT + 2);
  8047. cli.set_read_timeout(5, 0);
  8048. cli.set_payload_max_length(0); // 0 means no limit
  8049. auto stream = cli.open_stream("GET", "/data");
  8050. ASSERT_TRUE(stream.is_valid());
  8051. char buffer[64 * 1024];
  8052. ssize_t n;
  8053. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8054. total_read += static_cast<size_t>(n);
  8055. }
  8056. }
  8057. server_thread.join();
  8058. EXPECT_EQ(total_read, DATA_SIZE)
  8059. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8060. << " bytes without truncation, but only read " << total_read << " bytes.";
  8061. }
  8062. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8063. // enormous Content-Length must not cause the client to pre-allocate a huge
  8064. // response body buffer. The reservation is capped at payload_max_length_, and
  8065. // the read itself fails when the body exceeds the limit.
  8066. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8067. #ifndef _WIN32
  8068. signal(SIGPIPE, SIG_IGN);
  8069. #endif
  8070. auto server_thread = std::thread([] {
  8071. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8072. default_socket_options(srv);
  8073. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8074. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8075. sockaddr_in addr{};
  8076. addr.sin_family = AF_INET;
  8077. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8078. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8079. int opt = 1;
  8080. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8081. #ifdef _WIN32
  8082. reinterpret_cast<const char *>(&opt),
  8083. #else
  8084. &opt,
  8085. #endif
  8086. sizeof(opt));
  8087. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8088. ::listen(srv, 1);
  8089. sockaddr_in cli_addr{};
  8090. socklen_t cli_len = sizeof(cli_addr);
  8091. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8092. if (cli != INVALID_SOCKET) {
  8093. char buf[4096];
  8094. ::recv(cli, buf, sizeof(buf), 0);
  8095. // Malicious response: claim a 20GB body but send only a tiny payload.
  8096. std::string response = "HTTP/1.1 200 OK\r\n"
  8097. "Content-Length: 20000000000\r\n"
  8098. "\r\n"
  8099. "abc";
  8100. ::send(cli,
  8101. #ifdef _WIN32
  8102. static_cast<const char *>(response.c_str()),
  8103. static_cast<int>(response.size()),
  8104. #else
  8105. response.c_str(), response.size(),
  8106. #endif
  8107. 0);
  8108. detail::close_socket(cli);
  8109. }
  8110. detail::close_socket(srv);
  8111. });
  8112. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8113. {
  8114. Client cli("127.0.0.1", PORT + 2);
  8115. cli.set_read_timeout(5, 0);
  8116. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8117. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8118. // (server claims more bytes than payload_max_length permits), but it must
  8119. // not exhaust memory before getting there.
  8120. auto res = cli.Get("/malicious");
  8121. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8122. }
  8123. server_thread.join();
  8124. }
  8125. // Verify that content_receiver bypasses the default payload_max_length,
  8126. // allowing streaming downloads larger than 100MB without requiring an explicit
  8127. // set_payload_max_length call.
  8128. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8129. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8130. #ifndef _WIN32
  8131. signal(SIGPIPE, SIG_IGN);
  8132. #endif
  8133. auto server_thread = std::thread([] {
  8134. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8135. default_socket_options(srv);
  8136. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8137. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8138. sockaddr_in addr{};
  8139. addr.sin_family = AF_INET;
  8140. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8141. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8142. int opt = 1;
  8143. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8144. #ifdef _WIN32
  8145. reinterpret_cast<const char *>(&opt),
  8146. #else
  8147. &opt,
  8148. #endif
  8149. sizeof(opt));
  8150. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8151. ::listen(srv, 1);
  8152. sockaddr_in cli_addr{};
  8153. socklen_t cli_len = sizeof(cli_addr);
  8154. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8155. if (cli != INVALID_SOCKET) {
  8156. char buf[4096];
  8157. ::recv(cli, buf, sizeof(buf), 0);
  8158. // Response with Content-Length larger than default 100MB limit
  8159. auto content_length = std::to_string(DATA_SIZE);
  8160. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8161. "Content-Length: " +
  8162. content_length +
  8163. "\r\n"
  8164. "Connection: close\r\n"
  8165. "\r\n";
  8166. ::send(cli,
  8167. #ifdef _WIN32
  8168. static_cast<const char *>(response_header.c_str()),
  8169. static_cast<int>(response_header.size()),
  8170. #else
  8171. response_header.c_str(), response_header.size(),
  8172. #endif
  8173. 0);
  8174. std::string chunk(64 * 1024, 'A');
  8175. size_t total_sent = 0;
  8176. while (total_sent < DATA_SIZE) {
  8177. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8178. auto sent = ::send(cli,
  8179. #ifdef _WIN32
  8180. static_cast<const char *>(chunk.c_str()),
  8181. static_cast<int>(to_send),
  8182. #else
  8183. chunk.c_str(), to_send,
  8184. #endif
  8185. 0);
  8186. if (sent <= 0) break;
  8187. total_sent += static_cast<size_t>(sent);
  8188. }
  8189. detail::close_socket(cli);
  8190. }
  8191. detail::close_socket(srv);
  8192. });
  8193. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8194. size_t total_received = 0;
  8195. {
  8196. Client cli("127.0.0.1", PORT + 2);
  8197. cli.set_read_timeout(10, 0);
  8198. // Do NOT call set_payload_max_length — use the default 100MB limit
  8199. auto res =
  8200. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8201. total_received += data_length;
  8202. return true;
  8203. });
  8204. ASSERT_TRUE(res);
  8205. EXPECT_EQ(StatusCode::OK_200, res->status);
  8206. }
  8207. server_thread.join();
  8208. EXPECT_EQ(total_received, DATA_SIZE)
  8209. << "With content_receiver, the client should read all " << DATA_SIZE
  8210. << " bytes despite the default 100MB payload_max_length, but only read "
  8211. << total_received << " bytes.";
  8212. }
  8213. // Verify that an explicit set_payload_max_length smaller than the response is
  8214. // enforced even when a content_receiver is used.
  8215. TEST(ClientVulnerabilityTest,
  8216. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8217. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8218. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8219. #ifndef _WIN32
  8220. signal(SIGPIPE, SIG_IGN);
  8221. #endif
  8222. auto server_thread = std::thread([] {
  8223. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8224. default_socket_options(srv);
  8225. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8226. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8227. sockaddr_in addr{};
  8228. addr.sin_family = AF_INET;
  8229. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8230. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8231. int opt = 1;
  8232. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8233. #ifdef _WIN32
  8234. reinterpret_cast<const char *>(&opt),
  8235. #else
  8236. &opt,
  8237. #endif
  8238. sizeof(opt));
  8239. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8240. ::listen(srv, 1);
  8241. sockaddr_in cli_addr{};
  8242. socklen_t cli_len = sizeof(cli_addr);
  8243. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8244. if (cli != INVALID_SOCKET) {
  8245. char buf[4096];
  8246. ::recv(cli, buf, sizeof(buf), 0);
  8247. auto content_length = std::to_string(DATA_SIZE);
  8248. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8249. "Content-Length: " +
  8250. content_length +
  8251. "\r\n"
  8252. "Connection: close\r\n"
  8253. "\r\n";
  8254. ::send(cli,
  8255. #ifdef _WIN32
  8256. static_cast<const char *>(response_header.c_str()),
  8257. static_cast<int>(response_header.size()),
  8258. #else
  8259. response_header.c_str(), response_header.size(),
  8260. #endif
  8261. 0);
  8262. std::string chunk(64 * 1024, 'A');
  8263. size_t total_sent = 0;
  8264. while (total_sent < DATA_SIZE) {
  8265. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8266. auto sent = ::send(cli,
  8267. #ifdef _WIN32
  8268. static_cast<const char *>(chunk.c_str()),
  8269. static_cast<int>(to_send),
  8270. #else
  8271. chunk.c_str(), to_send,
  8272. #endif
  8273. 0);
  8274. if (sent <= 0) break;
  8275. total_sent += static_cast<size_t>(sent);
  8276. }
  8277. detail::close_socket(cli);
  8278. }
  8279. detail::close_socket(srv);
  8280. });
  8281. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8282. size_t total_received = 0;
  8283. {
  8284. Client cli("127.0.0.1", PORT + 2);
  8285. cli.set_read_timeout(10, 0);
  8286. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8287. auto res =
  8288. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8289. total_received += data_length;
  8290. return true;
  8291. });
  8292. // Should fail because 200MB exceeds the explicit 150MB limit
  8293. EXPECT_FALSE(res);
  8294. }
  8295. server_thread.join();
  8296. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8297. << "Client with content_receiver should respect the explicit "
  8298. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8299. << total_received << " bytes.";
  8300. }
  8301. // Verify that an explicit set_payload_max_length larger than the response
  8302. // allows the content_receiver to read all data successfully.
  8303. TEST(ClientVulnerabilityTest,
  8304. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8305. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8306. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8307. #ifndef _WIN32
  8308. signal(SIGPIPE, SIG_IGN);
  8309. #endif
  8310. auto server_thread = std::thread([] {
  8311. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8312. default_socket_options(srv);
  8313. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8314. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8315. sockaddr_in addr{};
  8316. addr.sin_family = AF_INET;
  8317. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8318. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8319. int opt = 1;
  8320. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8321. #ifdef _WIN32
  8322. reinterpret_cast<const char *>(&opt),
  8323. #else
  8324. &opt,
  8325. #endif
  8326. sizeof(opt));
  8327. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8328. ::listen(srv, 1);
  8329. sockaddr_in cli_addr{};
  8330. socklen_t cli_len = sizeof(cli_addr);
  8331. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8332. if (cli != INVALID_SOCKET) {
  8333. char buf[4096];
  8334. ::recv(cli, buf, sizeof(buf), 0);
  8335. auto content_length = std::to_string(DATA_SIZE);
  8336. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8337. "Content-Length: " +
  8338. content_length +
  8339. "\r\n"
  8340. "Connection: close\r\n"
  8341. "\r\n";
  8342. ::send(cli,
  8343. #ifdef _WIN32
  8344. static_cast<const char *>(response_header.c_str()),
  8345. static_cast<int>(response_header.size()),
  8346. #else
  8347. response_header.c_str(), response_header.size(),
  8348. #endif
  8349. 0);
  8350. std::string chunk(64 * 1024, 'A');
  8351. size_t total_sent = 0;
  8352. while (total_sent < DATA_SIZE) {
  8353. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8354. auto sent = ::send(cli,
  8355. #ifdef _WIN32
  8356. static_cast<const char *>(chunk.c_str()),
  8357. static_cast<int>(to_send),
  8358. #else
  8359. chunk.c_str(), to_send,
  8360. #endif
  8361. 0);
  8362. if (sent <= 0) break;
  8363. total_sent += static_cast<size_t>(sent);
  8364. }
  8365. #ifdef _WIN32
  8366. ::shutdown(cli, SD_SEND);
  8367. #else
  8368. ::shutdown(cli, SHUT_WR);
  8369. #endif
  8370. char drain[1024];
  8371. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8372. detail::close_socket(cli);
  8373. }
  8374. detail::close_socket(srv);
  8375. });
  8376. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8377. size_t total_received = 0;
  8378. {
  8379. Client cli("127.0.0.1", PORT + 2);
  8380. cli.set_read_timeout(10, 0);
  8381. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8382. auto res =
  8383. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8384. total_received += data_length;
  8385. return true;
  8386. });
  8387. ASSERT_TRUE(res);
  8388. EXPECT_EQ(StatusCode::OK_200, res->status);
  8389. }
  8390. server_thread.join();
  8391. EXPECT_EQ(total_received, DATA_SIZE)
  8392. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8393. << " bytes (larger than " << DATA_SIZE
  8394. << " bytes response), content_receiver should read all data, but only "
  8395. "read "
  8396. << total_received << " bytes.";
  8397. }
  8398. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8399. // Regression test for "zip bomb" attack on the client side: a malicious server
  8400. // sends a small gzip-compressed response that decompresses to a huge payload.
  8401. // The client must enforce payload_max_length on the decompressed size.
  8402. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8403. constexpr size_t DECOMPRESSED_SIZE =
  8404. 10 * 1024 * 1024; // 10MB after decompression
  8405. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8406. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8407. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8408. std::string compressed;
  8409. {
  8410. httplib::detail::gzip_compressor compressor;
  8411. bool ok =
  8412. compressor.compress(uncompressed.data(), uncompressed.size(),
  8413. /*last=*/true, [&](const char *buf, size_t len) {
  8414. compressed.append(buf, len);
  8415. return true;
  8416. });
  8417. ASSERT_TRUE(ok);
  8418. }
  8419. // Sanity: compressed data should be much smaller than the decompressed size
  8420. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8421. #ifndef _WIN32
  8422. signal(SIGPIPE, SIG_IGN);
  8423. #endif
  8424. // Set up the listening socket in the main thread so the server is guaranteed
  8425. // to be ready before the client connects (eliminates race condition).
  8426. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8427. default_socket_options(srv);
  8428. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8429. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8430. sockaddr_in addr{};
  8431. addr.sin_family = AF_INET;
  8432. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8433. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8434. int opt = 1;
  8435. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8436. #ifdef _WIN32
  8437. reinterpret_cast<const char *>(&opt),
  8438. #else
  8439. &opt,
  8440. #endif
  8441. sizeof(opt));
  8442. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8443. ASSERT_EQ(0, ::listen(srv, 1));
  8444. auto server_thread = std::thread([&compressed, srv] {
  8445. sockaddr_in cli_addr{};
  8446. socklen_t cli_len = sizeof(cli_addr);
  8447. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8448. if (cli != INVALID_SOCKET) {
  8449. // Read the full HTTP request (until \r\n\r\n)
  8450. char buf[4096];
  8451. size_t total = 0;
  8452. while (total < sizeof(buf)) {
  8453. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8454. if (n <= 0) break;
  8455. total += static_cast<size_t>(n);
  8456. // Check for end of headers
  8457. if (total >= 4) {
  8458. std::string req(buf, total);
  8459. if (req.find("\r\n\r\n") != std::string::npos) break;
  8460. }
  8461. }
  8462. // Malicious response: gzip-compressed body, no Content-Length
  8463. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8464. "Content-Encoding: gzip\r\n"
  8465. "Connection: close\r\n"
  8466. "\r\n";
  8467. ::send(cli,
  8468. #ifdef _WIN32
  8469. static_cast<const char *>(response_header.c_str()),
  8470. static_cast<int>(response_header.size()),
  8471. #else
  8472. response_header.c_str(), response_header.size(),
  8473. #endif
  8474. 0);
  8475. // Send the compressed payload (small on the wire, huge when decompressed)
  8476. size_t total_sent = 0;
  8477. while (total_sent < compressed.size()) {
  8478. auto to_send = std::min(compressed.size() - total_sent,
  8479. static_cast<size_t>(64 * 1024));
  8480. auto sent =
  8481. ::send(cli,
  8482. #ifdef _WIN32
  8483. static_cast<const char *>(compressed.c_str() + total_sent),
  8484. static_cast<int>(to_send),
  8485. #else
  8486. compressed.c_str() + total_sent, to_send,
  8487. #endif
  8488. 0);
  8489. if (sent <= 0) break;
  8490. total_sent += static_cast<size_t>(sent);
  8491. }
  8492. detail::close_socket(cli);
  8493. }
  8494. });
  8495. auto se = detail::scope_exit([&] {
  8496. detail::close_socket(srv);
  8497. server_thread.join();
  8498. });
  8499. size_t total_decompressed = 0;
  8500. {
  8501. Client cli("127.0.0.1", PORT + 3);
  8502. cli.set_read_timeout(5, 0);
  8503. cli.set_decompress(true);
  8504. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8505. auto stream = cli.open_stream("GET", "/zipbomb");
  8506. ASSERT_TRUE(stream.is_valid());
  8507. char buffer[64 * 1024];
  8508. ssize_t n;
  8509. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8510. total_decompressed += static_cast<size_t>(n);
  8511. }
  8512. }
  8513. // The decompressed size must be capped by payload_max_length. Without
  8514. // protection, the client would decompress the full 10MB from a tiny
  8515. // compressed payload, enabling a zip bomb DoS attack.
  8516. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8517. << "Client decompressed " << total_decompressed
  8518. << " bytes from a gzip response. The decompressed size should be "
  8519. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8520. }
  8521. #endif
  8522. TEST(HostAndPortPropertiesTest, NoSSL) {
  8523. httplib::Client cli("www.google.com", 1234);
  8524. ASSERT_EQ("www.google.com", cli.host());
  8525. ASSERT_EQ(1234, cli.port());
  8526. }
  8527. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8528. httplib::Client cli("www.google.com:1234");
  8529. ASSERT_EQ("www.google.com", cli.host());
  8530. ASSERT_EQ(1234, cli.port());
  8531. }
  8532. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8533. // Port number that overflows int — should not crash, client becomes invalid
  8534. httplib::Client cli("http://www.google.com:99999999999999999999");
  8535. ASSERT_FALSE(cli.is_valid());
  8536. }
  8537. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8538. // Port 99999 exceeds valid range (1-65535) — should not crash
  8539. httplib::Client cli("http://www.google.com:99999");
  8540. ASSERT_FALSE(cli.is_valid());
  8541. }
  8542. #ifdef CPPHTTPLIB_SSL_ENABLED
  8543. TEST(HostAndPortPropertiesTest, SSL) {
  8544. httplib::SSLClient cli("www.google.com");
  8545. ASSERT_EQ("www.google.com", cli.host());
  8546. ASSERT_EQ(443, cli.port());
  8547. }
  8548. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8549. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8550. std::string cert;
  8551. read_file(CA_CERT_FILE, cert);
  8552. httplib::SSLClient httplib_client("www.google.com");
  8553. // Load CA store first time
  8554. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8555. // Load CA store second time (update)
  8556. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8557. // Verify client is still valid and can make connections
  8558. httplib_client.enable_server_certificate_verification(true);
  8559. auto res = httplib_client.Get("/");
  8560. ASSERT_TRUE(res);
  8561. // Google may return 200 or 301 depending on various factors
  8562. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8563. res->status == StatusCode::MovedPermanently_301);
  8564. }
  8565. TEST(SSLClientTest, ServerNameIndication_Online) {
  8566. auto host = "httpbingo.org";
  8567. auto path = std::string{"/get"};
  8568. SSLClient cli(host, 443);
  8569. auto res = cli.Get(path);
  8570. ASSERT_TRUE(res);
  8571. ASSERT_EQ(StatusCode::OK_200, res->status);
  8572. }
  8573. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8574. // Use a site that will cause SSL verification failure due to self-signed cert
  8575. SSLClient cli("self-signed.badssl.com", 443);
  8576. cli.enable_server_certificate_verification(true);
  8577. auto res = cli.Get("/");
  8578. ASSERT_TRUE(!res);
  8579. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8580. // Verify backend error is captured for SSLServerVerification
  8581. // This occurs when certificate verification fails
  8582. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8583. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8584. EXPECT_NE(0UL, res.ssl_backend_error());
  8585. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8586. // For OpenSSL, ssl_error is 0 for verification errors
  8587. EXPECT_EQ(0, res.ssl_error());
  8588. #if !defined(_WIN32) || \
  8589. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8590. // On non-Windows or when Windows Schannel is disabled, the error comes
  8591. // from OpenSSL's verification
  8592. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8593. res.ssl_backend_error());
  8594. #endif
  8595. #endif
  8596. }
  8597. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8598. // Use a site where hostname doesn't match the certificate
  8599. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8600. SSLClient cli("wrong.host.badssl.com", 443);
  8601. cli.enable_server_certificate_verification(true);
  8602. cli.enable_server_hostname_verification(true);
  8603. auto res = cli.Get("/");
  8604. ASSERT_TRUE(!res);
  8605. // The error type depends on when hostname verification occurs:
  8606. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8607. // - Mbed TLS: SSLServerVerification (during handshake)
  8608. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8609. res.error() == Error::SSLServerVerification);
  8610. // Verify backend error is captured for hostname verification failure
  8611. EXPECT_NE(0UL, res.ssl_backend_error());
  8612. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8613. // For OpenSSL, ssl_error is 0 for verification errors
  8614. EXPECT_EQ(0, res.ssl_error());
  8615. #if !defined(_WIN32) || \
  8616. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8617. // On non-Windows or when Windows Schannel is disabled, the error comes
  8618. // from OpenSSL's hostname verification
  8619. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8620. res.ssl_backend_error());
  8621. #endif
  8622. #endif
  8623. }
  8624. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8625. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8626. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8627. SSLClient cli("www.google.com", 443);
  8628. cli.enable_server_certificate_verification(true);
  8629. auto res = cli.Get("/");
  8630. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8631. }
  8632. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8633. SSLClient cli("www.google.com", 443);
  8634. cli.enable_server_certificate_verification(true);
  8635. cli.enable_windows_certificate_verification(false);
  8636. auto res = cli.Get("/");
  8637. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8638. }
  8639. #endif
  8640. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8641. Client cli("https://google.com");
  8642. auto res = cli.Get("/");
  8643. ASSERT_TRUE(res);
  8644. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8645. }
  8646. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8647. SSLClient cli("google.com");
  8648. cli.set_ca_cert_path(CA_CERT_FILE);
  8649. auto res = cli.Get("/");
  8650. ASSERT_TRUE(res);
  8651. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8652. }
  8653. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8654. SSLClient cli("google.com");
  8655. cli.enable_server_certificate_verification(true);
  8656. cli.set_ca_cert_path("hello");
  8657. auto res = cli.Get("/");
  8658. ASSERT_TRUE(!res);
  8659. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8660. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8661. // should be set
  8662. EXPECT_EQ(0, res.ssl_error());
  8663. // Verify backend error is captured for SSLLoadingCerts
  8664. // This error occurs when loading CA certificates fails
  8665. EXPECT_NE(0UL, res.ssl_backend_error());
  8666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8667. // OpenSSL specific error codes:
  8668. // > openssl errstr 0x80000002
  8669. // error:80000002:system library::No such file or directory
  8670. // > openssl errstr 0xA000126
  8671. // error:0A000126:SSL routines::unexpected eof while reading
  8672. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8673. res.ssl_backend_error() == 0xA000126);
  8674. #endif
  8675. }
  8676. TEST(SSLClientTest, ServerCertificateVerification4) {
  8677. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8678. ASSERT_TRUE(svr.is_valid());
  8679. svr.Get("/test", [&](const Request &, Response &res) {
  8680. res.set_content("test", "text/plain");
  8681. svr.stop();
  8682. ASSERT_TRUE(true);
  8683. });
  8684. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8685. auto se = detail::scope_exit([&] {
  8686. t.join();
  8687. ASSERT_FALSE(svr.is_running());
  8688. });
  8689. svr.wait_until_ready();
  8690. SSLClient cli("127.0.0.1", PORT);
  8691. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8692. cli.enable_server_certificate_verification(true);
  8693. cli.set_connection_timeout(30);
  8694. auto res = cli.Get("/test");
  8695. ASSERT_TRUE(res);
  8696. ASSERT_EQ(StatusCode::OK_200, res->status);
  8697. }
  8698. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8699. std::string cert;
  8700. read_file(CA_CERT_FILE, cert);
  8701. SSLClient cli("google.com");
  8702. cli.load_ca_cert_store(cert.data(), cert.size());
  8703. const auto res = cli.Get("/");
  8704. ASSERT_TRUE(res);
  8705. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8706. }
  8707. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8708. // clang-format off
  8709. static constexpr char cert[] =
  8710. "GlobalSign Root CA\n"
  8711. "==================\n"
  8712. "-----BEGIN CERTIFICATE-----\n"
  8713. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8714. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8715. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8716. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8717. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8718. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8719. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8720. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8721. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8722. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8723. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8724. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8725. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8726. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8727. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8728. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8729. "-----END CERTIFICATE-----\n";
  8730. // clang-format on
  8731. SSLClient cli("google.com");
  8732. cli.load_ca_cert_store(cert, sizeof(cert));
  8733. const auto res = cli.Get("/");
  8734. ASSERT_TRUE(res);
  8735. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8736. }
  8737. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8738. SSLClient cli("www.youtube.com");
  8739. cli.set_ca_cert_path(CA_CERT_FILE);
  8740. cli.enable_server_certificate_verification(true);
  8741. cli.set_follow_location(true);
  8742. auto res = cli.Get("/");
  8743. ASSERT_TRUE(res);
  8744. ASSERT_EQ(StatusCode::OK_200, res->status);
  8745. }
  8746. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8747. SSLClient cli("wWw.YouTube.Com");
  8748. cli.set_ca_cert_path(CA_CERT_FILE);
  8749. cli.enable_server_certificate_verification(true);
  8750. cli.enable_server_hostname_verification(true);
  8751. cli.set_follow_location(true);
  8752. auto res = cli.Get("/");
  8753. ASSERT_TRUE(res);
  8754. ASSERT_EQ(StatusCode::OK_200, res->status);
  8755. }
  8756. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8757. SSLClient cli("gOoGlE.COm");
  8758. cli.enable_server_certificate_verification(true);
  8759. cli.enable_server_hostname_verification(true);
  8760. cli.set_follow_location(true);
  8761. auto res = cli.Get("/");
  8762. ASSERT_TRUE(res);
  8763. ASSERT_EQ(StatusCode::OK_200, res->status);
  8764. }
  8765. TEST(SSLClientTest, Issue2004_Online) {
  8766. Client client("https://google.com");
  8767. client.set_follow_location(true);
  8768. auto res = client.Get("/");
  8769. ASSERT_TRUE(res);
  8770. ASSERT_EQ(StatusCode::OK_200, res->status);
  8771. auto body = res->body;
  8772. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8773. }
  8774. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8775. // Create SSLClient with invalid cert/key to make is_valid() return false
  8776. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8777. "nonexistent_key.pem");
  8778. // is_valid() should be false due to cert loading failure
  8779. ASSERT_FALSE(cli.is_valid());
  8780. auto res = cli.Get("/");
  8781. ASSERT_FALSE(res);
  8782. EXPECT_EQ(Error::SSLConnection, res.error());
  8783. }
  8784. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8785. // Test for Issue #2251: SSL error not properly reported when client cert
  8786. // and key paths are swapped or mismatched
  8787. // This simulates the scenario where user accidentally swaps the cert and key
  8788. // files
  8789. // Using client cert file as private key and vice versa (completely wrong)
  8790. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8791. // Should fail validation due to cert/key mismatch
  8792. ASSERT_FALSE(cli.is_valid());
  8793. // Attempt to make a request should fail with proper error
  8794. auto res = cli.Get("/");
  8795. ASSERT_FALSE(res);
  8796. EXPECT_EQ(Error::SSLConnection, res.error());
  8797. // SSL error should be recorded in the Result object (this is the key fix for
  8798. // Issue #2251)
  8799. auto backend_error = res.ssl_backend_error();
  8800. EXPECT_NE(0u, backend_error);
  8801. }
  8802. // Tests cert/key mismatch detection at the TLS context level
  8803. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8804. // Test that using mismatched cert/key causes connection failure.
  8805. // We verify this at the SSLClient level rather than through internal
  8806. // TLS API functions.
  8807. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8808. cli.enable_server_certificate_verification(false);
  8809. cli.set_connection_timeout(2);
  8810. // The mismatch should cause a connection or handshake error
  8811. auto res = cli.Get("/test");
  8812. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8813. // Either way, the request should fail
  8814. EXPECT_FALSE(res);
  8815. }
  8816. #endif
  8817. #if 0
  8818. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8819. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8820. ASSERT_TRUE(cli != nullptr);
  8821. cli->set_address_family(AF_INET6);
  8822. cli->set_interface("en0");
  8823. auto res = cli->Get("/get");
  8824. ASSERT_TRUE(res);
  8825. ASSERT_EQ(StatusCode::OK_200, res->status);
  8826. }
  8827. #endif
  8828. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8829. #ifdef CPPHTTPLIB_SSL_ENABLED
  8830. void ClientCertPresent(
  8831. const std::string &client_cert_file,
  8832. const std::string &client_private_key_file,
  8833. const std::string &client_encrypted_private_key_pass = std::string()) {
  8834. using namespace httplib::tls;
  8835. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8836. CLIENT_CA_CERT_DIR);
  8837. ASSERT_TRUE(svr.is_valid());
  8838. svr.Get("/test", [&](const Request &req, Response &res) {
  8839. res.set_content("test", "text/plain");
  8840. auto cert = req.peer_cert();
  8841. ASSERT_TRUE(static_cast<bool>(cert));
  8842. std::string common_name = cert.subject_cn();
  8843. EXPECT_EQ("Common Name", common_name);
  8844. });
  8845. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8846. auto se = detail::scope_exit([&] {
  8847. svr.stop();
  8848. t.join();
  8849. ASSERT_FALSE(svr.is_running());
  8850. });
  8851. svr.wait_until_ready();
  8852. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8853. client_encrypted_private_key_pass);
  8854. cli.enable_server_certificate_verification(false);
  8855. cli.set_connection_timeout(30);
  8856. auto res = cli.Get("/test");
  8857. ASSERT_TRUE(res);
  8858. ASSERT_EQ(StatusCode::OK_200, res->status);
  8859. }
  8860. TEST(SSLClientServerTest, ClientCertPresent) {
  8861. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8862. }
  8863. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8864. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8865. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8866. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8867. }
  8868. // PEM memory-based constructor tests (works with all TLS backends)
  8869. void PemMemoryClientCertPresent(
  8870. const std::string &client_cert_file,
  8871. const std::string &client_private_key_file,
  8872. const std::string &client_encrypted_private_key_pass = std::string()) {
  8873. // Read PEM files into memory
  8874. std::string server_cert_pem, server_key_pem;
  8875. std::string client_ca_pem;
  8876. std::string client_cert_pem, client_key_pem;
  8877. read_file(SERVER_CERT_FILE, server_cert_pem);
  8878. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8879. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8880. read_file(client_cert_file, client_cert_pem);
  8881. read_file(client_private_key_file, client_key_pem);
  8882. // Create server with PEM memory
  8883. SSLServer::PemMemory server_pem = {
  8884. server_cert_pem.c_str(),
  8885. server_cert_pem.size(),
  8886. server_key_pem.c_str(),
  8887. server_key_pem.size(),
  8888. client_ca_pem.c_str(),
  8889. client_ca_pem.size(),
  8890. nullptr // no password for server key
  8891. };
  8892. SSLServer svr(server_pem);
  8893. ASSERT_TRUE(svr.is_valid());
  8894. svr.Get("/test", [&](const Request &, Response &res) {
  8895. res.set_content("test", "text/plain");
  8896. });
  8897. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8898. auto se = detail::scope_exit([&] {
  8899. svr.stop();
  8900. t.join();
  8901. ASSERT_FALSE(svr.is_running());
  8902. });
  8903. svr.wait_until_ready();
  8904. // Create client with PEM memory
  8905. const char *password = client_encrypted_private_key_pass.empty()
  8906. ? nullptr
  8907. : client_encrypted_private_key_pass.c_str();
  8908. SSLClient::PemMemory client_pem = {
  8909. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8910. client_key_pem.size(), password};
  8911. SSLClient cli(HOST, PORT, client_pem);
  8912. cli.enable_server_certificate_verification(false);
  8913. cli.set_connection_timeout(30);
  8914. auto res = cli.Get("/test");
  8915. ASSERT_TRUE(res);
  8916. ASSERT_EQ(StatusCode::OK_200, res->status);
  8917. }
  8918. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8919. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8920. }
  8921. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8922. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8923. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8924. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8925. }
  8926. TEST(SSLClientServerTest, ClientCertMissing) {
  8927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8928. CLIENT_CA_CERT_DIR);
  8929. ASSERT_TRUE(svr.is_valid());
  8930. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8931. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8932. auto se = detail::scope_exit([&] {
  8933. svr.stop();
  8934. t.join();
  8935. ASSERT_FALSE(svr.is_running());
  8936. });
  8937. svr.wait_until_ready();
  8938. SSLClient cli(HOST, PORT);
  8939. cli.set_connection_timeout(30);
  8940. auto res = cli.Get("/test");
  8941. ASSERT_TRUE(!res);
  8942. // When client cert is missing and server requires it, connection fails
  8943. // Error type depends on backend implementation
  8944. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8945. res.error() == Error::SSLConnection);
  8946. // Verify backend error is captured
  8947. // Note: This test may have different error codes depending on the exact
  8948. // verification failure
  8949. EXPECT_NE(0UL, res.ssl_backend_error());
  8950. }
  8951. TEST(SSLClientServerTest, TrustDirOptional) {
  8952. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8953. ASSERT_TRUE(svr.is_valid());
  8954. svr.Get("/test", [&](const Request &, Response &res) {
  8955. res.set_content("test", "text/plain");
  8956. });
  8957. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8958. auto se = detail::scope_exit([&] {
  8959. svr.stop();
  8960. t.join();
  8961. ASSERT_FALSE(svr.is_running());
  8962. });
  8963. svr.wait_until_ready();
  8964. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8965. cli.enable_server_certificate_verification(false);
  8966. cli.set_connection_timeout(30);
  8967. auto res = cli.Get("/test");
  8968. ASSERT_TRUE(res);
  8969. ASSERT_EQ(StatusCode::OK_200, res->status);
  8970. }
  8971. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8972. class NoListenSSLServer : public SSLServer {
  8973. public:
  8974. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8975. const char *client_ca_cert_file_path,
  8976. const char *client_ca_cert_dir_path = nullptr)
  8977. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8978. client_ca_cert_dir_path),
  8979. stop_(false) {}
  8980. std::atomic_bool stop_;
  8981. private:
  8982. bool process_and_close_socket(socket_t /*sock*/) override {
  8983. // Don't create SSL context
  8984. while (!stop_.load()) {
  8985. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8986. }
  8987. return true;
  8988. }
  8989. };
  8990. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8991. CLIENT_CA_CERT_FILE);
  8992. ASSERT_TRUE(svr.is_valid());
  8993. svr.Get("/test", [&](const Request &, Response &res) {
  8994. res.set_content("test", "text/plain");
  8995. });
  8996. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8997. auto se = detail::scope_exit([&] {
  8998. svr.stop_ = true;
  8999. svr.stop();
  9000. t.join();
  9001. ASSERT_FALSE(svr.is_running());
  9002. });
  9003. svr.wait_until_ready();
  9004. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9005. cli.enable_server_certificate_verification(false);
  9006. cli.set_connection_timeout(1);
  9007. auto res = cli.Get("/test");
  9008. ASSERT_TRUE(!res);
  9009. EXPECT_EQ(Error::SSLConnection, res.error());
  9010. // Timeout results in WantRead error code (maps to backend-specific value)
  9011. EXPECT_NE(0, res.ssl_error());
  9012. }
  9013. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9014. // Test SSLServer with client certificate verification using the standard
  9015. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9016. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9017. CLIENT_CA_CERT_DIR);
  9018. ASSERT_TRUE(svr.is_valid());
  9019. svr.Get("/test", [&](const Request &req, Response &res) {
  9020. res.set_content("test", "text/plain");
  9021. auto cert = req.peer_cert();
  9022. ASSERT_TRUE(static_cast<bool>(cert));
  9023. auto common_name = cert.subject_cn();
  9024. EXPECT_EQ("Common Name", common_name);
  9025. });
  9026. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9027. auto se = detail::scope_exit([&] {
  9028. svr.stop();
  9029. t.join();
  9030. ASSERT_FALSE(svr.is_running());
  9031. });
  9032. svr.wait_until_ready();
  9033. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9034. cli.enable_server_certificate_verification(false);
  9035. cli.set_connection_timeout(30);
  9036. auto res = cli.Get("/test");
  9037. ASSERT_TRUE(res);
  9038. ASSERT_EQ(StatusCode::OK_200, res->status);
  9039. }
  9040. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9041. // Verifies that wildcard matching and exact matching work consistently
  9042. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9043. using namespace httplib::tls;
  9044. // We need a running server to test against
  9045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9046. ASSERT_TRUE(svr.is_valid());
  9047. svr.Get("/test", [](const Request &, Response &res) {
  9048. res.set_content("ok", "text/plain");
  9049. });
  9050. thread t([&]() { svr.listen(HOST, PORT); });
  9051. auto se = detail::scope_exit([&] {
  9052. svr.stop();
  9053. t.join();
  9054. });
  9055. svr.wait_until_ready();
  9056. bool verify_callback_called = false;
  9057. bool verify_result_wrong = false;
  9058. SSLClient cli(HOST, PORT);
  9059. cli.enable_server_certificate_verification(true);
  9060. cli.set_ca_cert_path(CA_CERT_FILE);
  9061. cli.set_connection_timeout(5);
  9062. // Note: Test certificate has CN="Common Name", not "localhost"
  9063. bool verify_result_cn = false;
  9064. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9065. verify_callback_called = true;
  9066. if (!ctx.cert) return false;
  9067. // Test 1: "Common Name" should match (our test server cert CN)
  9068. verify_result_cn = ctx.check_hostname("Common Name");
  9069. // Test 2: wrong hostname should not match
  9070. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9071. return true; // Accept for the purpose of this test
  9072. });
  9073. auto res = cli.Get("/test");
  9074. // The request may succeed or fail depending on cert configuration
  9075. // but the callback should have been called
  9076. ASSERT_TRUE(verify_callback_called)
  9077. << "Verify callback should have been called";
  9078. // CN="Common Name" should match our test certificate
  9079. //
  9080. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9081. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9082. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9083. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9084. // <openssl/base.h>, which is included transitively when
  9085. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9086. #if defined(OPENSSL_IS_BORINGSSL)
  9087. EXPECT_FALSE(verify_result_cn)
  9088. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9089. #else
  9090. EXPECT_TRUE(verify_result_cn)
  9091. << "verify_hostname should match 'Common Name' (certificate CN)";
  9092. #endif
  9093. // Wrong hostname should not match
  9094. EXPECT_FALSE(verify_result_wrong)
  9095. << "verify_hostname should not match 'wronghost.example.com'";
  9096. }
  9097. #endif
  9098. // mbedTLS-specific callback constructor test
  9099. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9100. #ifdef CPPHTTPLIB_SSL_ENABLED
  9101. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9103. ASSERT_TRUE(svr.is_valid());
  9104. // Set up a handler to verify client certificate is present
  9105. bool client_cert_verified = false;
  9106. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9107. // Verify that client certificate was provided
  9108. client_cert_verified = true;
  9109. res.set_content("success", "text/plain");
  9110. });
  9111. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9112. auto se = detail::scope_exit([&] {
  9113. svr.stop();
  9114. t.join();
  9115. ASSERT_FALSE(svr.is_running());
  9116. });
  9117. svr.wait_until_ready();
  9118. // Client with certificate
  9119. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9120. cli.enable_server_certificate_verification(false);
  9121. cli.set_connection_timeout(30);
  9122. auto res = cli.Get("/test");
  9123. ASSERT_TRUE(res);
  9124. ASSERT_EQ(StatusCode::OK_200, res->status);
  9125. ASSERT_TRUE(client_cert_verified);
  9126. EXPECT_EQ("success", res->body);
  9127. }
  9128. #endif
  9129. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9130. // backends
  9131. #ifdef CPPHTTPLIB_SSL_ENABLED
  9132. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9133. using namespace httplib::tls;
  9134. // Test that when client CA cert file is provided,
  9135. // the server properly requests and validates client certificates
  9136. // Create a server with client authentication
  9137. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9138. ASSERT_TRUE(svr.is_valid());
  9139. bool handler_called = false;
  9140. svr.Get("/test", [&](const Request &req, Response &res) {
  9141. handler_called = true;
  9142. // Verify that a client certificate was provided
  9143. auto cert = req.peer_cert();
  9144. ASSERT_TRUE(static_cast<bool>(cert));
  9145. // Get the issuer name
  9146. std::string issuer_str = cert.issuer_name();
  9147. ASSERT_FALSE(issuer_str.empty());
  9148. // The client certificate should be issued by our test CA
  9149. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9150. res.set_content("authenticated", "text/plain");
  9151. });
  9152. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9153. auto se = detail::scope_exit([&] {
  9154. svr.stop();
  9155. t.join();
  9156. ASSERT_FALSE(svr.is_running());
  9157. });
  9158. svr.wait_until_ready();
  9159. // Connect with a client certificate issued by the CA
  9160. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9161. cli.enable_server_certificate_verification(false);
  9162. cli.set_connection_timeout(30);
  9163. auto res = cli.Get("/test");
  9164. ASSERT_TRUE(res);
  9165. ASSERT_EQ(StatusCode::OK_200, res->status);
  9166. ASSERT_TRUE(handler_called);
  9167. EXPECT_EQ("authenticated", res->body);
  9168. }
  9169. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9170. using namespace httplib::tls;
  9171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9172. ASSERT_TRUE(svr.is_valid());
  9173. svr.Get("/test", [](const Request &, Response &res) {
  9174. res.set_content("ok", "text/plain");
  9175. });
  9176. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9177. auto se = detail::scope_exit([&] {
  9178. svr.stop();
  9179. t.join();
  9180. });
  9181. svr.wait_until_ready();
  9182. SSLClient cli(HOST, PORT);
  9183. cli.enable_server_certificate_verification(false);
  9184. cli.set_connection_timeout(30);
  9185. bool cert_checked = false;
  9186. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9187. if (ctx.cert) {
  9188. auto sans = ctx.sans();
  9189. // Test certificate may or may not have SANs - just verify the API
  9190. // works If SANs exist, verify the types are valid
  9191. for (const auto &san : sans) {
  9192. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9193. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9194. san.type == SanType::OTHER);
  9195. EXPECT_FALSE(san.value.empty());
  9196. }
  9197. cert_checked = true;
  9198. }
  9199. return true;
  9200. });
  9201. auto res = cli.Get("/test");
  9202. ASSERT_TRUE(res);
  9203. EXPECT_TRUE(cert_checked);
  9204. }
  9205. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9206. using namespace httplib::tls;
  9207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9208. ASSERT_TRUE(svr.is_valid());
  9209. svr.Get("/test", [](const Request &, Response &res) {
  9210. res.set_content("ok", "text/plain");
  9211. });
  9212. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9213. auto se = detail::scope_exit([&] {
  9214. svr.stop();
  9215. t.join();
  9216. });
  9217. svr.wait_until_ready();
  9218. SSLClient cli(HOST, PORT);
  9219. cli.enable_server_certificate_verification(false);
  9220. cli.set_connection_timeout(30);
  9221. bool validity_checked = false;
  9222. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9223. if (ctx.cert) {
  9224. time_t not_before = 0, not_after = 0;
  9225. bool result = ctx.validity(not_before, not_after);
  9226. EXPECT_TRUE(result);
  9227. // Verify that not_before < now < not_after for a valid cert
  9228. time_t now = time(nullptr);
  9229. EXPECT_LT(not_before, now);
  9230. EXPECT_GT(not_after, now);
  9231. validity_checked = true;
  9232. }
  9233. return true;
  9234. });
  9235. auto res = cli.Get("/test");
  9236. ASSERT_TRUE(res);
  9237. EXPECT_TRUE(validity_checked);
  9238. }
  9239. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9240. using namespace httplib::tls;
  9241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9242. ASSERT_TRUE(svr.is_valid());
  9243. svr.Get("/test", [](const Request &, Response &res) {
  9244. res.set_content("ok", "text/plain");
  9245. });
  9246. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9247. auto se = detail::scope_exit([&] {
  9248. svr.stop();
  9249. t.join();
  9250. });
  9251. svr.wait_until_ready();
  9252. SSLClient cli(HOST, PORT);
  9253. cli.enable_server_certificate_verification(false);
  9254. cli.set_connection_timeout(30);
  9255. bool serial_checked = false;
  9256. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9257. if (ctx.cert) {
  9258. std::string serial = ctx.serial();
  9259. EXPECT_FALSE(serial.empty());
  9260. // Serial should be a hex string
  9261. for (char c : serial) {
  9262. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9263. (c >= 'a' && c <= 'f'));
  9264. }
  9265. serial_checked = true;
  9266. }
  9267. return true;
  9268. });
  9269. auto res = cli.Get("/test");
  9270. ASSERT_TRUE(res);
  9271. EXPECT_TRUE(serial_checked);
  9272. }
  9273. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9274. // Test 1: Valid CA file - no error should be recorded
  9275. {
  9276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9277. CLIENT_CA_CERT_FILE);
  9278. ASSERT_TRUE(svr.is_valid());
  9279. // With valid setup, last_ssl_error should be 0
  9280. EXPECT_EQ(0, svr.ssl_last_error());
  9281. }
  9282. // Test 2: Invalid CA file content
  9283. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9284. {
  9285. // Create a temporary file with completely invalid content
  9286. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9287. {
  9288. std::ofstream ofs(temp_invalid_ca);
  9289. ofs << "This is not a certificate file at all\n";
  9290. ofs << "Just plain text content\n";
  9291. }
  9292. // Create server with invalid CA file
  9293. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9294. // Clean up temporary file
  9295. std::remove(temp_invalid_ca);
  9296. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9297. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9298. // Note: SSL_CTX_load_verify_locations typically fails first,
  9299. // but our error handling code path is still exercised
  9300. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9301. }
  9302. }
  9303. TEST(VerifyCallbackTest, VerifyContextFields) {
  9304. using namespace httplib::tls;
  9305. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9306. ASSERT_TRUE(svr.is_valid());
  9307. svr.Get("/test", [](const Request &, Response &res) {
  9308. res.set_content("ok", "text/plain");
  9309. });
  9310. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9311. auto se = detail::scope_exit([&] {
  9312. svr.stop();
  9313. t.join();
  9314. });
  9315. svr.wait_until_ready();
  9316. SSLClient cli(HOST, PORT);
  9317. cli.enable_server_certificate_verification(false);
  9318. cli.set_connection_timeout(30);
  9319. int callback_count = 0;
  9320. bool saw_leaf_cert = false;
  9321. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9322. if (ctx.cert) {
  9323. callback_count++;
  9324. // We should see at least one certificate (the leaf)
  9325. std::string cn = ctx.subject_cn();
  9326. if (!cn.empty()) { saw_leaf_cert = true; }
  9327. // Verify context fields are populated
  9328. EXPECT_NE(ctx.session, nullptr);
  9329. EXPECT_GE(ctx.depth, 0);
  9330. }
  9331. return true;
  9332. });
  9333. auto res = cli.Get("/test");
  9334. ASSERT_TRUE(res);
  9335. EXPECT_GT(callback_count, 0);
  9336. EXPECT_TRUE(saw_leaf_cert);
  9337. }
  9338. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9339. using httplib::tls::TlsError;
  9340. // Test that verify_error_to_string returns empty for success
  9341. std::string success_str = TlsError::verify_error_to_string(0);
  9342. EXPECT_TRUE(success_str.empty());
  9343. // Test that verify_error_to_string returns non-empty for error codes
  9344. // Using a common error code (certificate expired)
  9345. std::string error_str =
  9346. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9347. EXPECT_FALSE(error_str.empty());
  9348. }
  9349. TEST(SessionVerifierTest, CertificateAccepted) {
  9350. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9351. ASSERT_TRUE(svr.is_valid());
  9352. svr.Get("/test", [](const Request &, Response &res) {
  9353. res.set_content("ok", "text/plain");
  9354. });
  9355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9356. auto se = detail::scope_exit([&] {
  9357. svr.stop();
  9358. t.join();
  9359. });
  9360. svr.wait_until_ready();
  9361. SSLClient cli(HOST, PORT);
  9362. cli.enable_server_certificate_verification(false);
  9363. cli.set_connection_timeout(30);
  9364. bool callback_called = false;
  9365. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9366. EXPECT_NE(session, nullptr);
  9367. callback_called = true;
  9368. return SSLVerifierResponse::CertificateAccepted;
  9369. });
  9370. auto res = cli.Get("/test");
  9371. ASSERT_TRUE(res);
  9372. EXPECT_EQ(200, res->status);
  9373. EXPECT_TRUE(callback_called);
  9374. }
  9375. TEST(SessionVerifierTest, CertificateRejected) {
  9376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9377. ASSERT_TRUE(svr.is_valid());
  9378. svr.Get("/test", [](const Request &, Response &res) {
  9379. res.set_content("ok", "text/plain");
  9380. });
  9381. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9382. auto se = detail::scope_exit([&] {
  9383. svr.stop();
  9384. t.join();
  9385. });
  9386. svr.wait_until_ready();
  9387. SSLClient cli(HOST, PORT);
  9388. cli.enable_server_certificate_verification(false);
  9389. cli.set_connection_timeout(30);
  9390. bool callback_called = false;
  9391. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9392. EXPECT_NE(session, nullptr);
  9393. callback_called = true;
  9394. return SSLVerifierResponse::CertificateRejected;
  9395. });
  9396. auto res = cli.Get("/test");
  9397. EXPECT_FALSE(res);
  9398. EXPECT_TRUE(callback_called);
  9399. }
  9400. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9402. ASSERT_TRUE(svr.is_valid());
  9403. svr.Get("/test", [](const Request &, Response &res) {
  9404. res.set_content("ok", "text/plain");
  9405. });
  9406. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9407. auto se = detail::scope_exit([&] {
  9408. svr.stop();
  9409. t.join();
  9410. });
  9411. svr.wait_until_ready();
  9412. // NoDecisionMade with verification disabled should succeed (no default check)
  9413. SSLClient cli(HOST, PORT);
  9414. cli.enable_server_certificate_verification(false);
  9415. cli.set_connection_timeout(30);
  9416. bool callback_called = false;
  9417. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9418. EXPECT_NE(session, nullptr);
  9419. callback_called = true;
  9420. return SSLVerifierResponse::NoDecisionMade;
  9421. });
  9422. auto res = cli.Get("/test");
  9423. ASSERT_TRUE(res);
  9424. EXPECT_EQ(200, res->status);
  9425. EXPECT_TRUE(callback_called);
  9426. }
  9427. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9428. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9429. ASSERT_TRUE(svr.is_valid());
  9430. svr.Get("/test", [](const Request &, Response &res) {
  9431. res.set_content("ok", "text/plain");
  9432. });
  9433. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9434. auto se = detail::scope_exit([&] {
  9435. svr.stop();
  9436. t.join();
  9437. });
  9438. svr.wait_until_ready();
  9439. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9440. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9441. // so we only check that the request fails, not whether the callback was
  9442. // called.
  9443. SSLClient cli(HOST, PORT);
  9444. cli.enable_server_certificate_verification(true);
  9445. cli.set_connection_timeout(30);
  9446. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9447. EXPECT_NE(session, nullptr);
  9448. return SSLVerifierResponse::NoDecisionMade;
  9449. });
  9450. auto res = cli.Get("/test");
  9451. EXPECT_FALSE(res);
  9452. }
  9453. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9454. // Test SSL server using PemMemory constructor with client CA certificates
  9455. // Read PEM files
  9456. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9457. read_file(SERVER_CERT_FILE, server_cert_pem);
  9458. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9459. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9460. // Create SSLServer with PemMemory constructor including client CA
  9461. SSLServer::PemMemory server_pem = {
  9462. server_cert_pem.c_str(),
  9463. server_cert_pem.size(),
  9464. server_key_pem.c_str(),
  9465. server_key_pem.size(),
  9466. client_ca_pem.c_str(),
  9467. client_ca_pem.size(),
  9468. nullptr // no password for server key
  9469. };
  9470. SSLServer svr(server_pem);
  9471. ASSERT_TRUE(svr.is_valid());
  9472. // No SSL error should be recorded for valid setup
  9473. EXPECT_EQ(0, svr.ssl_last_error());
  9474. // Set up server endpoints
  9475. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9476. res.set_content("ok", "text/plain");
  9477. });
  9478. // Start server in a thread
  9479. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9480. svr.wait_until_ready();
  9481. // Connect with client certificate (using constructor with paths)
  9482. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9483. cli.enable_server_certificate_verification(false);
  9484. auto res = cli.Get("/test-pem-ca");
  9485. ASSERT_TRUE(res);
  9486. EXPECT_EQ(200, res->status);
  9487. EXPECT_EQ("ok", res->body);
  9488. svr.stop();
  9489. server_thread.join();
  9490. }
  9491. #endif
  9492. #ifdef _WIN32
  9493. TEST(CleanupTest, WSACleanup) {
  9494. int ret = WSACleanup();
  9495. ASSERT_EQ(0, ret);
  9496. }
  9497. #endif
  9498. #ifndef CPPHTTPLIB_SSL_ENABLED
  9499. TEST(NoSSLSupport, SimpleInterface) {
  9500. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9501. }
  9502. #endif
  9503. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9504. TEST(InvalidScheme, SimpleInterface) {
  9505. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9506. }
  9507. #endif
  9508. TEST(NoScheme, SimpleInterface) {
  9509. Client cli("yahoo.com:80");
  9510. ASSERT_TRUE(cli.is_valid());
  9511. }
  9512. TEST(SendAPI, SimpleInterface_Online) {
  9513. Client cli("http://yahoo.com");
  9514. Request req;
  9515. req.method = "GET";
  9516. req.path = "/";
  9517. auto res = cli.send(req);
  9518. ASSERT_TRUE(res);
  9519. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9520. }
  9521. TEST(SendAPI, WithParamsInRequest) {
  9522. Server svr;
  9523. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9524. EXPECT_TRUE(req.has_param("test"));
  9525. EXPECT_EQ("test_value", req.get_param_value("test"));
  9526. });
  9527. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9528. auto se = detail::scope_exit([&] {
  9529. svr.stop();
  9530. t.join();
  9531. ASSERT_FALSE(svr.is_running());
  9532. });
  9533. svr.wait_until_ready();
  9534. Client cli(HOST, PORT);
  9535. {
  9536. Request req;
  9537. req.method = "GET";
  9538. req.path = "/";
  9539. req.params.emplace("test", "test_value");
  9540. auto res = cli.send(req);
  9541. ASSERT_TRUE(res);
  9542. }
  9543. {
  9544. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9545. ASSERT_TRUE(res);
  9546. }
  9547. }
  9548. TEST(ClientImplMethods, GetSocketTest) {
  9549. httplib::Server svr;
  9550. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9551. res.status = StatusCode::OK_200;
  9552. });
  9553. auto port = svr.bind_to_any_port("127.0.0.1");
  9554. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. thread.join();
  9558. ASSERT_FALSE(svr.is_running());
  9559. });
  9560. svr.wait_until_ready();
  9561. {
  9562. httplib::Client cli("127.0.0.1", port);
  9563. cli.set_keep_alive(true);
  9564. // Use the behavior of cpp-httplib of opening the connection
  9565. // only when the first request happens. If that changes,
  9566. // this test would be obsolete.
  9567. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9568. // This also implicitly tests the server. But other tests would fail much
  9569. // earlier than this one to be considered.
  9570. auto res = cli.Get("/");
  9571. ASSERT_TRUE(res);
  9572. EXPECT_EQ(StatusCode::OK_200, res->status);
  9573. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9574. }
  9575. }
  9576. #ifdef CPPHTTPLIB_SSL_ENABLED
  9577. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9578. Client cli("http://yahoo.com");
  9579. auto res = cli.Get("/");
  9580. ASSERT_TRUE(res);
  9581. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9582. cli.set_follow_location(true);
  9583. res = cli.Get("/");
  9584. ASSERT_TRUE(res);
  9585. EXPECT_EQ(StatusCode::OK_200, res->status);
  9586. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9587. }
  9588. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9589. Client cli("https://yahoo.com");
  9590. auto res = cli.Get("/");
  9591. ASSERT_TRUE(res);
  9592. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9593. cli.set_follow_location(true);
  9594. res = cli.Get("/");
  9595. ASSERT_TRUE(res);
  9596. EXPECT_EQ(StatusCode::OK_200, res->status);
  9597. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9598. }
  9599. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9600. Client cli("https://yahoo.com");
  9601. auto res = cli.Get("/");
  9602. ASSERT_TRUE(res);
  9603. ASSERT_FALSE(!res);
  9604. ASSERT_TRUE(res);
  9605. ASSERT_FALSE(res == nullptr);
  9606. ASSERT_TRUE(res != nullptr);
  9607. EXPECT_EQ(Error::Success, res.error());
  9608. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9609. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9610. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9611. cli.set_follow_location(true);
  9612. res = cli.Get("/");
  9613. ASSERT_TRUE(res);
  9614. EXPECT_EQ(Error::Success, res.error());
  9615. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9616. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9617. EXPECT_EQ(StatusCode::OK_200, res->status);
  9618. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9619. }
  9620. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9621. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9622. Client cli("https://cdnjs.cloudflare.com");
  9623. auto res =
  9624. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9625. ASSERT_TRUE(res);
  9626. EXPECT_EQ(StatusCode::OK_200, res->status);
  9627. EXPECT_EQ(287630U, res->body.size());
  9628. EXPECT_EQ("application/javascript; charset=utf-8",
  9629. res->get_header_value("Content-Type"));
  9630. }
  9631. #endif
  9632. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9633. #undef REDIR_HOST // Silence compiler warning
  9634. #define REDIR_HOST "https://httpbingo.org"
  9635. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9636. Client cli(REDIR_HOST);
  9637. cli.set_follow_location(true);
  9638. auto res =
  9639. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9640. ASSERT_TRUE(res);
  9641. EXPECT_EQ(StatusCode::OK_200, res->status);
  9642. }
  9643. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9644. Client cli(REDIR_HOST);
  9645. cli.set_follow_location(true);
  9646. Params params;
  9647. params.emplace("url", "http://example.com");
  9648. params.emplace("status_code", "302");
  9649. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9650. ASSERT_TRUE(res);
  9651. EXPECT_EQ(StatusCode::OK_200, res->status);
  9652. }
  9653. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9654. Client cli(REDIR_HOST);
  9655. cli.set_follow_location(true);
  9656. Params params;
  9657. params.emplace("url", "http://example.com");
  9658. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9659. ASSERT_TRUE(res);
  9660. EXPECT_EQ(StatusCode::OK_200, res->status);
  9661. }
  9662. TEST(HttpToHttpsRedirectTest, CertFile) {
  9663. auto ssl_port = PORT + 1;
  9664. Server svr;
  9665. ASSERT_TRUE(svr.is_valid());
  9666. svr.Get("/index", [&](const Request &, Response &res) {
  9667. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9668. "/index");
  9669. svr.stop();
  9670. });
  9671. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9672. ASSERT_TRUE(ssl_svr.is_valid());
  9673. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9674. res.set_content("test", "text/plain");
  9675. ssl_svr.stop();
  9676. });
  9677. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9678. thread t2 =
  9679. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9680. auto se = detail::scope_exit([&] {
  9681. t2.join();
  9682. t.join();
  9683. ASSERT_FALSE(svr.is_running());
  9684. });
  9685. svr.wait_until_ready();
  9686. ssl_svr.wait_until_ready();
  9687. Client cli("127.0.0.1", PORT);
  9688. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9689. cli.enable_server_certificate_verification(true);
  9690. cli.set_follow_location(true);
  9691. cli.set_connection_timeout(30);
  9692. auto res = cli.Get("/index");
  9693. ASSERT_TRUE(res);
  9694. ASSERT_EQ(StatusCode::OK_200, res->status);
  9695. }
  9696. TEST(SSLClientRedirectTest, CertFile) {
  9697. auto ssl_port = PORT + 1;
  9698. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9699. ASSERT_TRUE(ssl_svr1.is_valid());
  9700. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9701. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9702. "/index");
  9703. ssl_svr1.stop();
  9704. });
  9705. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9706. ASSERT_TRUE(ssl_svr2.is_valid());
  9707. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9708. res.set_content("test", "text/plain");
  9709. ssl_svr2.stop();
  9710. });
  9711. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9712. thread t2 =
  9713. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9714. auto se = detail::scope_exit([&] {
  9715. t2.join();
  9716. t.join();
  9717. ASSERT_FALSE(ssl_svr1.is_running());
  9718. });
  9719. ssl_svr1.wait_until_ready();
  9720. ssl_svr2.wait_until_ready();
  9721. SSLClient cli("127.0.0.1", PORT);
  9722. std::string cert;
  9723. read_file(SERVER_CERT2_FILE, cert);
  9724. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9725. cli.enable_server_certificate_verification(true);
  9726. cli.set_follow_location(true);
  9727. cli.set_connection_timeout(30);
  9728. auto res = cli.Get("/index");
  9729. ASSERT_TRUE(res);
  9730. ASSERT_EQ(StatusCode::OK_200, res->status);
  9731. }
  9732. #endif
  9733. #ifdef CPPHTTPLIB_SSL_ENABLED
  9734. // Test that set_ca_cert_store() skips system certs (consistent with
  9735. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9736. // should be trusted - system certs should NOT be loaded.
  9737. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9738. // Load a specific cert that is NOT a system CA cert
  9739. std::string cert;
  9740. read_file(SERVER_CERT2_FILE, cert);
  9741. SSLClient cli("google.com");
  9742. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9743. cli.enable_server_certificate_verification(true);
  9744. // This should FAIL because:
  9745. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9746. // 2. System certs should NOT be loaded when custom store is set
  9747. // If system certs WERE loaded, this would succeed
  9748. auto res = cli.Get("/");
  9749. ASSERT_FALSE(res);
  9750. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9751. }
  9752. // Same as above, but through the native store handle path. Regression test:
  9753. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  9754. // merged system certs into the user-provided store.
  9755. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  9756. std::string cert;
  9757. read_file(SERVER_CERT2_FILE, cert);
  9758. SSLClient cli("google.com");
  9759. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  9760. cli.enable_server_certificate_verification(true);
  9761. auto res = cli.Get("/");
  9762. ASSERT_FALSE(res);
  9763. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9764. }
  9765. // A custom store set via the native handle must still verify a server whose
  9766. // cert it does contain.
  9767. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  9768. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9769. ASSERT_TRUE(svr.is_valid());
  9770. svr.Get("/test", [&](const Request &, Response &res) {
  9771. res.set_content("test", "text/plain");
  9772. });
  9773. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9774. auto se = detail::scope_exit([&] {
  9775. svr.stop();
  9776. t.join();
  9777. ASSERT_FALSE(svr.is_running());
  9778. });
  9779. svr.wait_until_ready();
  9780. SSLClient cli("127.0.0.1", PORT);
  9781. std::string cert;
  9782. read_file(SERVER_CERT2_FILE, cert);
  9783. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  9784. cli.enable_server_certificate_verification(true);
  9785. cli.set_connection_timeout(30);
  9786. auto res = cli.Get("/test");
  9787. ASSERT_TRUE(res);
  9788. ASSERT_EQ(StatusCode::OK_200, res->status);
  9789. }
  9790. // CA certs loaded through the universal Client must be transferred to the
  9791. // client created internally for following an HTTPS redirect. Regression test:
  9792. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  9793. // the CA data for redirect transfer.
  9794. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  9795. auto ssl_port = PORT + 1;
  9796. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9797. ASSERT_TRUE(ssl_svr1.is_valid());
  9798. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9799. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9800. "/index");
  9801. });
  9802. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9803. ASSERT_TRUE(ssl_svr2.is_valid());
  9804. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9805. res.set_content("test", "text/plain");
  9806. });
  9807. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9808. thread t2 =
  9809. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9810. auto se = detail::scope_exit([&] {
  9811. ssl_svr2.stop();
  9812. ssl_svr1.stop();
  9813. t2.join();
  9814. t.join();
  9815. ASSERT_FALSE(ssl_svr1.is_running());
  9816. });
  9817. ssl_svr1.wait_until_ready();
  9818. ssl_svr2.wait_until_ready();
  9819. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  9820. std::string cert;
  9821. read_file(SERVER_CERT2_FILE, cert);
  9822. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9823. cli.enable_server_certificate_verification(true);
  9824. cli.set_follow_location(true);
  9825. cli.set_connection_timeout(30);
  9826. auto res = cli.Get("/index");
  9827. ASSERT_TRUE(res);
  9828. ASSERT_EQ(StatusCode::OK_200, res->status);
  9829. }
  9830. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  9831. // so a host signed by a system CA verifies even though a custom CA is set
  9832. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  9833. std::string cert;
  9834. read_file(SERVER_CERT2_FILE, cert);
  9835. SSLClient cli("google.com");
  9836. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9837. cli.enable_system_ca(true);
  9838. cli.enable_server_certificate_verification(true);
  9839. auto res = cli.Get("/");
  9840. ASSERT_TRUE(res);
  9841. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9842. }
  9843. // The custom CA remains effective when combined with the system CA
  9844. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  9845. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9846. ASSERT_TRUE(svr.is_valid());
  9847. svr.Get("/test", [&](const Request &, Response &res) {
  9848. res.set_content("test", "text/plain");
  9849. });
  9850. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9851. auto se = detail::scope_exit([&] {
  9852. svr.stop();
  9853. t.join();
  9854. ASSERT_FALSE(svr.is_running());
  9855. });
  9856. svr.wait_until_ready();
  9857. SSLClient cli("127.0.0.1", PORT);
  9858. std::string cert;
  9859. read_file(SERVER_CERT2_FILE, cert);
  9860. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9861. cli.enable_system_ca(true);
  9862. cli.enable_server_certificate_verification(true);
  9863. cli.set_connection_timeout(30);
  9864. auto res = cli.Get("/test");
  9865. ASSERT_TRUE(res);
  9866. ASSERT_EQ(StatusCode::OK_200, res->status);
  9867. }
  9868. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  9869. // skip chain verification entirely (only the certificate identity was
  9870. // checked), so a server presenting an untrusted certificate with a matching
  9871. // IP SAN was accepted. The chain must be validated for IP hosts too.
  9872. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  9873. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9874. ASSERT_TRUE(svr.is_valid());
  9875. svr.Get("/test", [&](const Request &, Response &res) {
  9876. res.set_content("test", "text/plain");
  9877. });
  9878. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9879. auto se = detail::scope_exit([&] {
  9880. svr.stop();
  9881. t.join();
  9882. ASSERT_FALSE(svr.is_running());
  9883. });
  9884. svr.wait_until_ready();
  9885. SSLClient cli("127.0.0.1", PORT);
  9886. std::string cert;
  9887. // A trusted CA that did not sign the server certificate. The server cert
  9888. // (cert2) carries the matching IP SAN, so only chain validation can reject
  9889. // this connection.
  9890. read_file(CLIENT_CA_CERT_FILE, cert);
  9891. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9892. cli.enable_server_certificate_verification(true);
  9893. cli.set_connection_timeout(30);
  9894. auto res = cli.Get("/test");
  9895. ASSERT_FALSE(res);
  9896. }
  9897. // enable_system_ca(false) prevents system CA loading entirely
  9898. TEST(SSLClientTest, DisableSystemCa_Online) {
  9899. SSLClient cli("google.com");
  9900. cli.enable_system_ca(false);
  9901. cli.enable_server_certificate_verification(true);
  9902. auto res = cli.Get("/");
  9903. ASSERT_FALSE(res);
  9904. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  9905. // itself when the CA chain is empty
  9906. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9907. res.error() == Error::SSLConnection);
  9908. }
  9909. // The universal Client forwards enable_system_ca()
  9910. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  9911. std::string cert;
  9912. read_file(SERVER_CERT2_FILE, cert);
  9913. Client cli("https://google.com");
  9914. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9915. cli.enable_system_ca(true);
  9916. cli.enable_server_certificate_verification(true);
  9917. auto res = cli.Get("/");
  9918. ASSERT_TRUE(res);
  9919. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9920. }
  9921. // The system CA policy must carry over to the client created internally for
  9922. // following a cross-host HTTPS redirect
  9923. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  9924. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9925. ASSERT_TRUE(svr.is_valid());
  9926. svr.Get("/index", [&](const Request &, Response &res) {
  9927. res.set_redirect("https://www.google.com/");
  9928. });
  9929. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9930. auto se = detail::scope_exit([&] {
  9931. svr.stop();
  9932. t.join();
  9933. ASSERT_FALSE(svr.is_running());
  9934. });
  9935. svr.wait_until_ready();
  9936. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  9937. std::string cert;
  9938. read_file(SERVER_CERT2_FILE, cert);
  9939. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9940. cli.enable_system_ca(true);
  9941. cli.enable_server_certificate_verification(true);
  9942. cli.set_follow_location(true);
  9943. cli.set_connection_timeout(30);
  9944. // Receiving any response proves the redirect client completed the TLS
  9945. // handshake with a system-CA-signed host
  9946. auto res = cli.Get("/index");
  9947. ASSERT_TRUE(res);
  9948. }
  9949. TEST(MultipartFormDataTest, LargeData) {
  9950. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9951. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9952. const ContentReader &content_reader) {
  9953. if (req.is_multipart_form_data()) {
  9954. std::vector<FormData> items;
  9955. content_reader(
  9956. [&](const FormData &file) {
  9957. items.push_back(file);
  9958. return true;
  9959. },
  9960. [&](const char *data, size_t data_length) {
  9961. items.back().content.append(data, data_length);
  9962. return true;
  9963. });
  9964. EXPECT_TRUE(std::string(items[0].name) == "document");
  9965. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9966. EXPECT_TRUE(items[0].filename == "2MB_data");
  9967. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9968. EXPECT_TRUE(items[1].name == "hello");
  9969. EXPECT_TRUE(items[1].content == "world");
  9970. EXPECT_TRUE(items[1].filename == "");
  9971. EXPECT_TRUE(items[1].content_type == "");
  9972. } else {
  9973. std::string body;
  9974. content_reader([&](const char *data, size_t data_length) {
  9975. body.append(data, data_length);
  9976. return true;
  9977. });
  9978. }
  9979. });
  9980. auto port = svr.bind_to_any_port(HOST);
  9981. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9982. auto se = detail::scope_exit([&] {
  9983. svr.stop();
  9984. t.join();
  9985. ASSERT_FALSE(svr.is_running());
  9986. });
  9987. svr.wait_until_ready();
  9988. {
  9989. std::string data(1024 * 1024 * 2, '.');
  9990. std::stringstream buffer;
  9991. buffer << data;
  9992. SSLClient cli(HOST, port);
  9993. cli.enable_server_certificate_verification(false);
  9994. UploadFormDataItems items{
  9995. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9996. {"hello", "world", "", ""},
  9997. };
  9998. auto res = cli.Post("/post", items);
  9999. ASSERT_TRUE(res);
  10000. ASSERT_EQ(StatusCode::OK_200, res->status);
  10001. }
  10002. }
  10003. TEST(MultipartFormDataTest, DataProviderItems) {
  10004. std::random_device seed_gen;
  10005. std::mt19937 random(seed_gen());
  10006. std::string rand1;
  10007. rand1.resize(1000);
  10008. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10009. std::string rand2;
  10010. rand2.resize(3000);
  10011. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10013. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10014. const ContentReader &content_reader) {
  10015. ASSERT_FALSE(req.is_multipart_form_data());
  10016. std::string body;
  10017. content_reader([&](const char *data, size_t data_length) {
  10018. body.append(data, data_length);
  10019. return true;
  10020. });
  10021. EXPECT_EQ(body, "");
  10022. });
  10023. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10024. const ContentReader &content_reader) {
  10025. ASSERT_TRUE(req.is_multipart_form_data());
  10026. std::vector<FormData> items;
  10027. content_reader(
  10028. [&](const FormData &file) {
  10029. items.push_back(file);
  10030. return true;
  10031. },
  10032. [&](const char *data, size_t data_length) {
  10033. items.back().content.append(data, data_length);
  10034. return true;
  10035. });
  10036. ASSERT_TRUE(items.size() == 2);
  10037. EXPECT_EQ(std::string(items[0].name), "name1");
  10038. EXPECT_EQ(items[0].content, "Testing123");
  10039. EXPECT_EQ(items[0].filename, "filename1");
  10040. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10041. EXPECT_EQ(items[1].name, "name2");
  10042. EXPECT_EQ(items[1].content, "Testing456");
  10043. EXPECT_EQ(items[1].filename, "");
  10044. EXPECT_EQ(items[1].content_type, "");
  10045. });
  10046. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10047. const ContentReader &content_reader) {
  10048. ASSERT_TRUE(req.is_multipart_form_data());
  10049. std::vector<FormData> items;
  10050. content_reader(
  10051. [&](const FormData &file) {
  10052. items.push_back(file);
  10053. return true;
  10054. },
  10055. [&](const char *data, size_t data_length) {
  10056. items.back().content.append(data, data_length);
  10057. return true;
  10058. });
  10059. ASSERT_TRUE(items.size() == 2);
  10060. EXPECT_EQ(items[0].name, "name3");
  10061. EXPECT_EQ(items[0].content, rand1);
  10062. EXPECT_EQ(items[0].filename, "filename3");
  10063. EXPECT_EQ(items[0].content_type, "");
  10064. EXPECT_EQ(items[1].name, "name4");
  10065. EXPECT_EQ(items[1].content, rand2);
  10066. EXPECT_EQ(items[1].filename, "filename4");
  10067. EXPECT_EQ(items[1].content_type, "");
  10068. });
  10069. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10070. const ContentReader &content_reader) {
  10071. ASSERT_TRUE(req.is_multipart_form_data());
  10072. std::vector<FormData> items;
  10073. content_reader(
  10074. [&](const FormData &file) {
  10075. items.push_back(file);
  10076. return true;
  10077. },
  10078. [&](const char *data, size_t data_length) {
  10079. items.back().content.append(data, data_length);
  10080. return true;
  10081. });
  10082. ASSERT_TRUE(items.size() == 4);
  10083. EXPECT_EQ(std::string(items[0].name), "name1");
  10084. EXPECT_EQ(items[0].content, "Testing123");
  10085. EXPECT_EQ(items[0].filename, "filename1");
  10086. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10087. EXPECT_EQ(items[1].name, "name2");
  10088. EXPECT_EQ(items[1].content, "Testing456");
  10089. EXPECT_EQ(items[1].filename, "");
  10090. EXPECT_EQ(items[1].content_type, "");
  10091. EXPECT_EQ(items[2].name, "name3");
  10092. EXPECT_EQ(items[2].content, rand1);
  10093. EXPECT_EQ(items[2].filename, "filename3");
  10094. EXPECT_EQ(items[2].content_type, "");
  10095. EXPECT_EQ(items[3].name, "name4");
  10096. EXPECT_EQ(items[3].content, rand2);
  10097. EXPECT_EQ(items[3].filename, "filename4");
  10098. EXPECT_EQ(items[3].content_type, "");
  10099. });
  10100. auto port = svr.bind_to_any_port("localhost");
  10101. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10102. auto se = detail::scope_exit([&] {
  10103. svr.stop();
  10104. t.join();
  10105. ASSERT_FALSE(svr.is_running());
  10106. });
  10107. svr.wait_until_ready();
  10108. {
  10109. SSLClient cli("localhost", port);
  10110. cli.enable_server_certificate_verification(false);
  10111. UploadFormDataItems items{
  10112. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10113. {"name2", "Testing456", "", ""}, // not a file
  10114. };
  10115. {
  10116. auto res = cli.Post("/post-none", {}, {}, {});
  10117. ASSERT_TRUE(res);
  10118. ASSERT_EQ(StatusCode::OK_200, res->status);
  10119. }
  10120. FormDataProviderItems providers;
  10121. {
  10122. auto res =
  10123. cli.Post("/post-items", {}, items, providers); // empty providers
  10124. ASSERT_TRUE(res);
  10125. ASSERT_EQ(StatusCode::OK_200, res->status);
  10126. }
  10127. providers.push_back({"name3",
  10128. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10129. // test the offset is given correctly at each step
  10130. if (!offset)
  10131. sink.os.write(rand1.data(), 30);
  10132. else if (offset == 30)
  10133. sink.os.write(rand1.data() + 30, 300);
  10134. else if (offset == 330)
  10135. sink.os.write(rand1.data() + 330, 670);
  10136. else if (offset == rand1.size())
  10137. sink.done();
  10138. return true;
  10139. },
  10140. "filename3",
  10141. {}});
  10142. providers.push_back({"name4",
  10143. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10144. // test the offset is given correctly at each step
  10145. if (!offset)
  10146. sink.os.write(rand2.data(), 2000);
  10147. else if (offset == 2000)
  10148. sink.os.write(rand2.data() + 2000, 1);
  10149. else if (offset == 2001)
  10150. sink.os.write(rand2.data() + 2001, 999);
  10151. else if (offset == rand2.size())
  10152. sink.done();
  10153. return true;
  10154. },
  10155. "filename4",
  10156. {}});
  10157. {
  10158. auto res = cli.Post("/post-providers", {}, {}, providers);
  10159. ASSERT_TRUE(res);
  10160. ASSERT_EQ(StatusCode::OK_200, res->status);
  10161. }
  10162. {
  10163. auto res = cli.Post("/post-both", {}, items, providers);
  10164. ASSERT_TRUE(res);
  10165. ASSERT_EQ(StatusCode::OK_200, res->status);
  10166. }
  10167. }
  10168. }
  10169. TEST(MultipartFormDataTest, BadHeader) {
  10170. Server svr;
  10171. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10172. res.set_content("ok", "text/plain");
  10173. });
  10174. thread t = thread([&] { svr.listen(HOST, PORT); });
  10175. auto se = detail::scope_exit([&] {
  10176. svr.stop();
  10177. t.join();
  10178. ASSERT_FALSE(svr.is_running());
  10179. });
  10180. svr.wait_until_ready();
  10181. const std::string body =
  10182. "This is the preamble. It is to be ignored, though it\r\n"
  10183. "is a handy place for composition agents to include an\r\n"
  10184. "explanatory note to non-MIME conformant readers.\r\n"
  10185. "\r\n"
  10186. "\r\n"
  10187. "--simple boundary\r\n"
  10188. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10189. ": BAD...\r\n"
  10190. "\r\n"
  10191. "value1\r\n"
  10192. "--simple boundary\r\n"
  10193. "Content-Disposition: form-data; name=\"field2\"; "
  10194. "filename=\"example.txt\"\r\n"
  10195. "\r\n"
  10196. "value2\r\n"
  10197. "--simple boundary--\r\n"
  10198. "This is the epilogue. It is also to be ignored.\r\n";
  10199. std::string content_type =
  10200. R"(multipart/form-data; boundary="simple boundary")";
  10201. Client cli(HOST, PORT);
  10202. auto res = cli.Post("/post", body, content_type.c_str());
  10203. ASSERT_TRUE(res);
  10204. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10205. }
  10206. TEST(MultipartFormDataTest, WithPreamble) {
  10207. Server svr;
  10208. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10209. res.set_content("ok", "text/plain");
  10210. });
  10211. thread t = thread([&] { svr.listen(HOST, PORT); });
  10212. auto se = detail::scope_exit([&] {
  10213. svr.stop();
  10214. t.join();
  10215. ASSERT_FALSE(svr.is_running());
  10216. });
  10217. svr.wait_until_ready();
  10218. const std::string body =
  10219. "This is the preamble. It is to be ignored, though it\r\n"
  10220. "is a handy place for composition agents to include an\r\n"
  10221. "explanatory note to non-MIME conformant readers.\r\n"
  10222. "\r\n"
  10223. "\r\n"
  10224. "--simple boundary\r\n"
  10225. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10226. "\r\n"
  10227. "value1\r\n"
  10228. "--simple boundary\r\n"
  10229. "Content-Disposition: form-data; name=\"field2\"; "
  10230. "filename=\"example.txt\"\r\n"
  10231. "\r\n"
  10232. "value2\r\n"
  10233. "--simple boundary--\r\n"
  10234. "This is the epilogue. It is also to be ignored.\r\n";
  10235. std::string content_type =
  10236. R"(multipart/form-data; boundary="simple boundary")";
  10237. Client cli(HOST, PORT);
  10238. auto res = cli.Post("/post", body, content_type.c_str());
  10239. ASSERT_TRUE(res);
  10240. EXPECT_EQ(StatusCode::OK_200, res->status);
  10241. }
  10242. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10243. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10244. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10245. const ContentReader &content_reader) {
  10246. if (req.is_multipart_form_data()) {
  10247. std::vector<FormData> items;
  10248. content_reader(
  10249. [&](const FormData &file) {
  10250. items.push_back(file);
  10251. return true;
  10252. },
  10253. [&](const char *data, size_t data_length) {
  10254. items.back().content.append(data, data_length);
  10255. return true;
  10256. });
  10257. EXPECT_TRUE(std::string(items[0].name) == "document");
  10258. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10259. EXPECT_TRUE(items[0].filename == "2MB_data");
  10260. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10261. EXPECT_TRUE(items[1].name == "hello");
  10262. EXPECT_TRUE(items[1].content == "world");
  10263. EXPECT_TRUE(items[1].filename == "");
  10264. EXPECT_TRUE(items[1].content_type == "");
  10265. } else {
  10266. std::string body;
  10267. content_reader([&](const char *data, size_t data_length) {
  10268. body.append(data, data_length);
  10269. return true;
  10270. });
  10271. }
  10272. });
  10273. auto port = svr.bind_to_any_port("localhost");
  10274. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10275. auto se = detail::scope_exit([&] {
  10276. svr.stop();
  10277. t.join();
  10278. ASSERT_FALSE(svr.is_running());
  10279. });
  10280. svr.wait_until_ready();
  10281. {
  10282. std::string data(1024 * 1024 * 2, '.');
  10283. std::stringstream buffer;
  10284. buffer << data;
  10285. SSLClient cli("localhost", port);
  10286. cli.enable_server_certificate_verification(false);
  10287. UploadFormDataItems items{
  10288. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10289. {"hello", "world", "", ""},
  10290. };
  10291. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10292. ASSERT_TRUE(res);
  10293. ASSERT_EQ(StatusCode::OK_200, res->status);
  10294. }
  10295. }
  10296. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10297. std::string data(1024 * 1024 * 2, '&');
  10298. std::stringstream buffer;
  10299. buffer << data;
  10300. Client cli("https://localhost:8080");
  10301. UploadFormDataItems items{
  10302. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10303. {"hello", "world", "", ""},
  10304. };
  10305. for (const char &c : " \t\r\n") {
  10306. auto res =
  10307. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10308. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10309. ASSERT_FALSE(res);
  10310. }
  10311. }
  10312. TEST(MultipartFormDataTest, PutFormData) {
  10313. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10314. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10315. const ContentReader &content_reader) {
  10316. if (req.is_multipart_form_data()) {
  10317. std::vector<FormData> items;
  10318. content_reader(
  10319. [&](const FormData &file) {
  10320. items.push_back(file);
  10321. return true;
  10322. },
  10323. [&](const char *data, size_t data_length) {
  10324. items.back().content.append(data, data_length);
  10325. return true;
  10326. });
  10327. EXPECT_TRUE(std::string(items[0].name) == "document");
  10328. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10329. EXPECT_TRUE(items[0].filename == "2MB_data");
  10330. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10331. EXPECT_TRUE(items[1].name == "hello");
  10332. EXPECT_TRUE(items[1].content == "world");
  10333. EXPECT_TRUE(items[1].filename == "");
  10334. EXPECT_TRUE(items[1].content_type == "");
  10335. } else {
  10336. std::string body;
  10337. content_reader([&](const char *data, size_t data_length) {
  10338. body.append(data, data_length);
  10339. return true;
  10340. });
  10341. }
  10342. });
  10343. auto port = svr.bind_to_any_port("localhost");
  10344. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10345. auto se = detail::scope_exit([&] {
  10346. svr.stop();
  10347. t.join();
  10348. ASSERT_FALSE(svr.is_running());
  10349. });
  10350. svr.wait_until_ready();
  10351. {
  10352. std::string data(1024 * 1024 * 2, '&');
  10353. std::stringstream buffer;
  10354. buffer << data;
  10355. SSLClient cli("localhost", port);
  10356. cli.enable_server_certificate_verification(false);
  10357. UploadFormDataItems items{
  10358. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10359. {"hello", "world", "", ""},
  10360. };
  10361. auto res = cli.Put("/put", items);
  10362. ASSERT_TRUE(res);
  10363. ASSERT_EQ(StatusCode::OK_200, res->status);
  10364. }
  10365. }
  10366. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10367. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10368. svr.Put("/put_customboundary",
  10369. [&](const Request &req, const Response & /*res*/,
  10370. const ContentReader &content_reader) {
  10371. if (req.is_multipart_form_data()) {
  10372. std::vector<FormData> items;
  10373. content_reader(
  10374. [&](const FormData &file) {
  10375. items.push_back(file);
  10376. return true;
  10377. },
  10378. [&](const char *data, size_t data_length) {
  10379. items.back().content.append(data, data_length);
  10380. return true;
  10381. });
  10382. EXPECT_TRUE(std::string(items[0].name) == "document");
  10383. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10384. EXPECT_TRUE(items[0].filename == "2MB_data");
  10385. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10386. EXPECT_TRUE(items[1].name == "hello");
  10387. EXPECT_TRUE(items[1].content == "world");
  10388. EXPECT_TRUE(items[1].filename == "");
  10389. EXPECT_TRUE(items[1].content_type == "");
  10390. } else {
  10391. std::string body;
  10392. content_reader([&](const char *data, size_t data_length) {
  10393. body.append(data, data_length);
  10394. return true;
  10395. });
  10396. }
  10397. });
  10398. auto port = svr.bind_to_any_port("localhost");
  10399. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10400. auto se = detail::scope_exit([&] {
  10401. svr.stop();
  10402. t.join();
  10403. ASSERT_FALSE(svr.is_running());
  10404. });
  10405. svr.wait_until_ready();
  10406. {
  10407. std::string data(1024 * 1024 * 2, '&');
  10408. std::stringstream buffer;
  10409. buffer << data;
  10410. SSLClient cli("localhost", port);
  10411. cli.enable_server_certificate_verification(false);
  10412. UploadFormDataItems items{
  10413. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10414. {"hello", "world", "", ""},
  10415. };
  10416. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10417. ASSERT_TRUE(res);
  10418. ASSERT_EQ(StatusCode::OK_200, res->status);
  10419. }
  10420. }
  10421. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10422. std::string data(1024 * 1024 * 2, '&');
  10423. std::stringstream buffer;
  10424. buffer << data;
  10425. Client cli("https://localhost:8080");
  10426. cli.enable_server_certificate_verification(false);
  10427. UploadFormDataItems items{
  10428. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10429. {"hello", "world", "", ""},
  10430. };
  10431. for (const char &c : " \t\r\n") {
  10432. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10433. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10434. ASSERT_FALSE(res);
  10435. }
  10436. }
  10437. TEST(MultipartFormDataTest, AlternateFilename) {
  10438. auto handled = false;
  10439. Server svr;
  10440. svr.Post("/test", [&](const Request &req, Response &res) {
  10441. ASSERT_EQ(2u, req.form.files.size());
  10442. ASSERT_EQ(1u, req.form.fields.size());
  10443. // Test files
  10444. const auto &file1 = req.form.get_file("file1");
  10445. ASSERT_EQ("file1", file1.name);
  10446. ASSERT_EQ("A.txt", file1.filename);
  10447. ASSERT_EQ("text/plain", file1.content_type);
  10448. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10449. const auto &file2 = req.form.get_file("file2");
  10450. ASSERT_EQ("file2", file2.name);
  10451. ASSERT_EQ("a.html", file2.filename);
  10452. ASSERT_EQ("text/html", file2.content_type);
  10453. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10454. file2.content);
  10455. // Test text field
  10456. const auto &text = req.form.get_field("text");
  10457. ASSERT_EQ("text default", text);
  10458. res.set_content("ok", "text/plain");
  10459. handled = true;
  10460. });
  10461. thread t = thread([&] { svr.listen(HOST, PORT); });
  10462. auto se = detail::scope_exit([&] {
  10463. svr.stop();
  10464. t.join();
  10465. ASSERT_FALSE(svr.is_running());
  10466. ASSERT_TRUE(handled);
  10467. });
  10468. svr.wait_until_ready();
  10469. auto req = "POST /test HTTP/1.1\r\n"
  10470. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10471. "Content-Length: 399\r\n"
  10472. "\r\n"
  10473. "----------\r\n"
  10474. "Content-Disposition: form-data; name=\"text\"\r\n"
  10475. "\r\n"
  10476. "text default\r\n"
  10477. "----------\r\n"
  10478. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10479. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10480. "Content-Type: text/plain\r\n"
  10481. "\r\n"
  10482. "Content of a.txt.\r\n"
  10483. "\r\n"
  10484. "----------\r\n"
  10485. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10486. "\"a.html\"\r\n"
  10487. "Content-Type: text/html\r\n"
  10488. "\r\n"
  10489. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10490. "\r\n"
  10491. "------------\r\n";
  10492. ASSERT_TRUE(send_request(1, req));
  10493. }
  10494. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10495. auto handled = false;
  10496. Server svr;
  10497. svr.Post("/test", [&](const Request &req, Response &res) {
  10498. // Case-insensitive "utf-8''" prefix with a long value
  10499. const auto &file = req.form.get_file("file1");
  10500. ASSERT_EQ("file1", file.name);
  10501. // 8000 chars exercises both the Content-Disposition parser and the
  10502. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10503. // Prior to the fix, std::regex_match on this header would cause O(N)
  10504. // stack recursion in libstdc++, leading to SIGSEGV.
  10505. std::string expected_filename(8000, 'A');
  10506. ASSERT_EQ(expected_filename, file.filename);
  10507. res.set_content("ok", "text/plain");
  10508. handled = true;
  10509. });
  10510. thread t = thread([&] { svr.listen(HOST, PORT); });
  10511. auto se = detail::scope_exit([&] {
  10512. svr.stop();
  10513. t.join();
  10514. ASSERT_FALSE(svr.is_running());
  10515. ASSERT_TRUE(handled);
  10516. });
  10517. svr.wait_until_ready();
  10518. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10519. // Regression test for GHSA-qq6v-r583-3h69
  10520. std::string long_filename(8000, 'A');
  10521. std::string body = "----------\r\n"
  10522. "Content-Disposition: form-data; name=\"file1\"; "
  10523. "filename*=\"Utf-8''" +
  10524. long_filename +
  10525. "\"\r\n"
  10526. "\r\n"
  10527. "hello\r\n"
  10528. "------------\r\n";
  10529. auto req = "POST /test HTTP/1.1\r\n"
  10530. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10531. "Content-Length: " +
  10532. std::to_string(body.size()) + "\r\n\r\n" + body;
  10533. ASSERT_TRUE(send_request(1, req));
  10534. }
  10535. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10536. auto handled = false;
  10537. Server svr;
  10538. svr.Post("/test", [&](const Request &req, Response &) {
  10539. ASSERT_EQ(2u, req.form.fields.size());
  10540. const auto &text1 = req.form.get_field("text1");
  10541. ASSERT_EQ("text1", text1);
  10542. const auto &text2 = req.form.get_field("text2");
  10543. ASSERT_EQ("text2", text2);
  10544. handled = true;
  10545. });
  10546. thread t = thread([&] { svr.listen(HOST, PORT); });
  10547. auto se = detail::scope_exit([&] {
  10548. svr.stop();
  10549. t.join();
  10550. ASSERT_FALSE(svr.is_running());
  10551. ASSERT_TRUE(handled);
  10552. });
  10553. svr.wait_until_ready();
  10554. auto req = "POST /test HTTP/1.1\r\n"
  10555. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10556. "Content-Length: 146\r\n"
  10557. "\r\n----------\r\n"
  10558. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10559. "\r\n"
  10560. "text1"
  10561. "\r\n----------\r\n"
  10562. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10563. "\r\n"
  10564. "text2"
  10565. "\r\n------------";
  10566. std::string response;
  10567. ASSERT_TRUE(send_request(1, req, &response));
  10568. ASSERT_EQ("200", response.substr(9, 3));
  10569. }
  10570. TEST(MultipartFormDataTest, ContentLength) {
  10571. auto handled = false;
  10572. Server svr;
  10573. svr.Post("/test", [&](const Request &req, Response &) {
  10574. ASSERT_EQ(2u, req.form.fields.size());
  10575. const auto &text1 = req.form.get_field("text1");
  10576. ASSERT_EQ("text1", text1);
  10577. const auto &text2 = req.form.get_field("text2");
  10578. ASSERT_EQ("text2", text2);
  10579. handled = true;
  10580. });
  10581. thread t = thread([&] { svr.listen(HOST, PORT); });
  10582. auto se = detail::scope_exit([&] {
  10583. svr.stop();
  10584. t.join();
  10585. ASSERT_FALSE(svr.is_running());
  10586. ASSERT_TRUE(handled);
  10587. });
  10588. svr.wait_until_ready();
  10589. auto req = "POST /test HTTP/1.1\r\n"
  10590. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10591. "Content-Length: 167\r\n"
  10592. "\r\n----------\r\n"
  10593. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10594. "Content-Length: 5\r\n"
  10595. "\r\n"
  10596. "text1"
  10597. "\r\n----------\r\n"
  10598. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10599. "\r\n"
  10600. "text2"
  10601. "\r\n------------\r\n";
  10602. std::string response;
  10603. ASSERT_TRUE(send_request(1, req, &response));
  10604. ASSERT_EQ("200", response.substr(9, 3));
  10605. }
  10606. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10607. auto handled = false;
  10608. Server svr;
  10609. svr.Post("/test", [&](const Request &req, Response &) {
  10610. ASSERT_EQ(2u, req.form.fields.size());
  10611. const auto &text1 = req.form.get_field("text1");
  10612. ASSERT_EQ("text1", text1);
  10613. // TODO: Add header access for text fields if needed
  10614. const auto &text2 = req.form.get_field("text2");
  10615. ASSERT_EQ("text2", text2);
  10616. // TODO: Header access for text fields needs to be implemented
  10617. // auto &headers = it->second.headers;
  10618. // ASSERT_EQ(3U, headers.size());
  10619. // auto custom_header = headers.find("x-whatever");
  10620. // ASSERT_TRUE(custom_header != headers.end());
  10621. // ASSERT_NE("customvalue", custom_header->second);
  10622. // ASSERT_EQ("CustomValue", custom_header->second);
  10623. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10624. handled = true;
  10625. });
  10626. thread t = thread([&] { svr.listen(HOST, PORT); });
  10627. auto se = detail::scope_exit([&] {
  10628. svr.stop();
  10629. t.join();
  10630. ASSERT_FALSE(svr.is_running());
  10631. ASSERT_TRUE(handled);
  10632. });
  10633. svr.wait_until_ready();
  10634. auto req = "POST /test HTTP/1.1\r\n"
  10635. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10636. "Content-Length: 232\r\n"
  10637. "\r\n----------\r\n"
  10638. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10639. "Content-Length: 5\r\n"
  10640. "X-Test: 1\r\n"
  10641. "\r\n"
  10642. "text1"
  10643. "\r\n----------\r\n"
  10644. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10645. "Content-Type: text/plain\r\n"
  10646. "X-Whatever: CustomValue\r\n"
  10647. "\r\n"
  10648. "text2"
  10649. "\r\n------------\r\n"
  10650. "That should be disregarded. Not even read";
  10651. std::string response;
  10652. ASSERT_TRUE(send_request(1, req, &response));
  10653. ASSERT_EQ("200", response.substr(9, 3));
  10654. }
  10655. TEST(MultipartFormDataTest, LargeHeader) {
  10656. auto handled = false;
  10657. Server svr;
  10658. svr.Post("/test", [&](const Request &req, Response &) {
  10659. ASSERT_EQ(1u, req.form.fields.size());
  10660. const auto &text = req.form.get_field("name1");
  10661. ASSERT_EQ("text1", text);
  10662. handled = true;
  10663. });
  10664. thread t = thread([&] { svr.listen(HOST, PORT); });
  10665. auto se = detail::scope_exit([&] {
  10666. svr.stop();
  10667. t.join();
  10668. ASSERT_FALSE(svr.is_running());
  10669. ASSERT_TRUE(handled);
  10670. });
  10671. svr.wait_until_ready();
  10672. auto boundary = std::string("cpp-httplib-multipart-data");
  10673. std::string content = "--" + boundary +
  10674. "\r\n"
  10675. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10676. "\r\n"
  10677. "text1\r\n"
  10678. "--" +
  10679. boundary + "--\r\n";
  10680. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10681. "Content-Type: multipart/form-data;boundary=" +
  10682. boundary +
  10683. "\r\n"
  10684. "Content-Length: " +
  10685. std::to_string(content.size()) +
  10686. "\r\n"
  10687. "Dummy-Header: ";
  10688. std::string header_suffix = "\r\n"
  10689. "\r\n";
  10690. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10691. size_t header_dummy_size =
  10692. read_buff_size -
  10693. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10694. auto header_dummy = std::string(header_dummy_size, '@');
  10695. auto req = header_prefix + header_dummy + header_suffix + content;
  10696. std::string response;
  10697. ASSERT_TRUE(send_request(1, req, &response));
  10698. ASSERT_EQ("200", response.substr(9, 3));
  10699. }
  10700. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10701. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10702. // (not chunked Transfer-Encoding) after the streaming refactor.
  10703. auto handled = false;
  10704. Server svr;
  10705. svr.Post("/upload", [&](const Request &req, Response &res) {
  10706. auto cl_it = req.headers.find("Content-Length");
  10707. EXPECT_TRUE(cl_it != req.headers.end());
  10708. auto te_it = req.headers.find("Transfer-Encoding");
  10709. EXPECT_TRUE(te_it == req.headers.end());
  10710. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10711. res.set_content("ok", "text/plain");
  10712. handled = true;
  10713. });
  10714. auto port = svr.bind_to_any_port(HOST);
  10715. auto t = thread([&] { svr.listen_after_bind(); });
  10716. auto se = detail::scope_exit([&] {
  10717. svr.stop();
  10718. t.join();
  10719. ASSERT_FALSE(svr.is_running());
  10720. ASSERT_TRUE(handled);
  10721. });
  10722. svr.wait_until_ready();
  10723. UploadFormDataItems items = {
  10724. {"field1", "hello", "", "text/plain"},
  10725. {"file1", "world", "test.txt", "application/octet-stream"},
  10726. };
  10727. Client cli(HOST, port);
  10728. auto res = cli.Post("/upload", {}, items);
  10729. ASSERT_TRUE(res);
  10730. EXPECT_EQ(StatusCode::OK_200, res->status);
  10731. }
  10732. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10733. // Verify that make_multipart_content_provider coalesces many small segments
  10734. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10735. constexpr size_t kItemCount = 1000;
  10736. UploadFormDataItems items;
  10737. items.reserve(kItemCount);
  10738. for (size_t i = 0; i < kItemCount; i++) {
  10739. items.push_back(
  10740. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10741. }
  10742. const std::string boundary = "----test-boundary";
  10743. auto content_length = detail::get_multipart_content_length(items, boundary);
  10744. auto provider = detail::make_multipart_content_provider(items, boundary);
  10745. // Drive the provider the same way write_content_with_progress does
  10746. size_t write_count = 0;
  10747. size_t total_bytes = 0;
  10748. DataSink sink;
  10749. size_t offset = 0;
  10750. sink.write = [&](const char *d, size_t l) -> bool {
  10751. (void)d;
  10752. write_count++;
  10753. total_bytes += l;
  10754. offset += l;
  10755. return true;
  10756. };
  10757. sink.is_writable = []() -> bool { return true; };
  10758. while (offset < content_length) {
  10759. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10760. }
  10761. EXPECT_EQ(content_length, total_bytes);
  10762. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10763. // With buffering into 64KB blocks, write_count should be much smaller.
  10764. auto segment_count = 3 * kItemCount + 1;
  10765. EXPECT_LT(write_count, segment_count / 10);
  10766. }
  10767. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10768. // Integration test: send many UploadFormDataItems and verify the server
  10769. // receives all of them correctly (#2410).
  10770. constexpr size_t kItemCount = 500;
  10771. auto handled = false;
  10772. Server svr;
  10773. svr.Post("/upload", [&](const Request &req, Response &res) {
  10774. EXPECT_EQ(kItemCount, req.form.fields.size());
  10775. for (size_t i = 0; i < kItemCount; i++) {
  10776. auto key = "field" + std::to_string(i);
  10777. auto val = "value" + std::to_string(i);
  10778. auto it = req.form.fields.find(key);
  10779. if (it != req.form.fields.end()) {
  10780. EXPECT_EQ(val, it->second.content);
  10781. } else {
  10782. ADD_FAILURE() << "Missing field: " << key;
  10783. }
  10784. }
  10785. res.set_content("ok", "text/plain");
  10786. handled = true;
  10787. });
  10788. auto port = svr.bind_to_any_port(HOST);
  10789. auto t = thread([&] { svr.listen_after_bind(); });
  10790. auto se = detail::scope_exit([&] {
  10791. svr.stop();
  10792. t.join();
  10793. ASSERT_FALSE(svr.is_running());
  10794. ASSERT_TRUE(handled);
  10795. });
  10796. svr.wait_until_ready();
  10797. UploadFormDataItems items;
  10798. items.reserve(kItemCount);
  10799. for (size_t i = 0; i < kItemCount; i++) {
  10800. items.push_back(
  10801. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10802. }
  10803. Client cli(HOST, port);
  10804. auto res = cli.Post("/upload", items);
  10805. ASSERT_TRUE(res);
  10806. EXPECT_EQ(StatusCode::OK_200, res->status);
  10807. }
  10808. TEST(MultipartFormDataTest, MakeFileProvider) {
  10809. // Verify make_file_provider sends a file's contents correctly.
  10810. const std::string file_content(4096, 'Z');
  10811. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10812. {
  10813. std::ofstream ofs(tmp_path, std::ios::binary);
  10814. ofs.write(file_content.data(),
  10815. static_cast<std::streamsize>(file_content.size()));
  10816. }
  10817. auto handled = false;
  10818. Server svr;
  10819. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10820. const ContentReader &content_reader) {
  10821. ASSERT_TRUE(req.is_multipart_form_data());
  10822. std::vector<FormData> items;
  10823. content_reader(
  10824. [&](const FormData &file) {
  10825. items.push_back(file);
  10826. return true;
  10827. },
  10828. [&](const char *data, size_t data_length) {
  10829. items.back().content.append(data, data_length);
  10830. return true;
  10831. });
  10832. ASSERT_EQ(1u, items.size());
  10833. EXPECT_EQ("myfile", items[0].name);
  10834. EXPECT_EQ("data.bin", items[0].filename);
  10835. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10836. EXPECT_EQ(file_content, items[0].content);
  10837. handled = true;
  10838. });
  10839. auto port = svr.bind_to_any_port(HOST);
  10840. auto t = thread([&] { svr.listen_after_bind(); });
  10841. auto se = detail::scope_exit([&] {
  10842. svr.stop();
  10843. t.join();
  10844. ASSERT_FALSE(svr.is_running());
  10845. ASSERT_TRUE(handled);
  10846. std::remove(tmp_path.c_str());
  10847. });
  10848. svr.wait_until_ready();
  10849. FormDataProviderItems providers;
  10850. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10851. "application/octet-stream"));
  10852. Client cli(HOST, port);
  10853. auto res = cli.Post("/upload", {}, {}, providers);
  10854. ASSERT_TRUE(res);
  10855. EXPECT_EQ(StatusCode::OK_200, res->status);
  10856. }
  10857. TEST(MakeFileBodyTest, Basic) {
  10858. const std::string file_content(4096, 'Z');
  10859. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10860. {
  10861. std::ofstream ofs(tmp_path, std::ios::binary);
  10862. ofs.write(file_content.data(),
  10863. static_cast<std::streamsize>(file_content.size()));
  10864. }
  10865. auto handled = false;
  10866. Server svr;
  10867. svr.Post("/upload", [&](const Request &req, Response &res) {
  10868. EXPECT_EQ(file_content, req.body);
  10869. handled = true;
  10870. res.status = StatusCode::OK_200;
  10871. });
  10872. auto port = svr.bind_to_any_port(HOST);
  10873. auto t = thread([&] { svr.listen_after_bind(); });
  10874. auto se = detail::scope_exit([&] {
  10875. svr.stop();
  10876. t.join();
  10877. ASSERT_FALSE(svr.is_running());
  10878. ASSERT_TRUE(handled);
  10879. std::remove(tmp_path.c_str());
  10880. });
  10881. svr.wait_until_ready();
  10882. auto fb = make_file_body(tmp_path);
  10883. ASSERT_GT(fb.first, 0u);
  10884. Client cli(HOST, port);
  10885. auto res =
  10886. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10887. ASSERT_TRUE(res);
  10888. EXPECT_EQ(StatusCode::OK_200, res->status);
  10889. }
  10890. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10891. static constexpr unsigned int number_of_tasks{1000000};
  10892. std::atomic_uint count{0};
  10893. std::unique_ptr<TaskQueue> task_queue{
  10894. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10895. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10896. auto queued = task_queue->enqueue(
  10897. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10898. EXPECT_TRUE(queued);
  10899. }
  10900. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10901. task_queue->shutdown();
  10902. #else
  10903. EXPECT_NO_THROW(task_queue->shutdown());
  10904. #endif
  10905. EXPECT_EQ(number_of_tasks, count.load());
  10906. }
  10907. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10908. static constexpr unsigned int number_of_tasks{1000000};
  10909. static constexpr unsigned int qlimit{2};
  10910. unsigned int queued_count{0};
  10911. std::atomic_uint count{0};
  10912. std::unique_ptr<TaskQueue> task_queue{
  10913. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10914. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10915. if (task_queue->enqueue(
  10916. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10917. queued_count++;
  10918. }
  10919. }
  10920. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10921. task_queue->shutdown();
  10922. #else
  10923. EXPECT_NO_THROW(task_queue->shutdown());
  10924. #endif
  10925. EXPECT_EQ(queued_count, count.load());
  10926. EXPECT_TRUE(queued_count <= number_of_tasks);
  10927. EXPECT_TRUE(queued_count >= qlimit);
  10928. }
  10929. TEST(TaskQueueTest, MaxQueuedRequests) {
  10930. static constexpr unsigned int qlimit{3};
  10931. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10932. std::condition_variable sem_cv;
  10933. std::mutex sem_mtx;
  10934. int credits = 0;
  10935. bool queued;
  10936. /* Fill up the queue with tasks that will block until we give them credits to
  10937. * complete. */
  10938. for (unsigned int n = 0; n <= qlimit;) {
  10939. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10940. std::unique_lock<std::mutex> lock(sem_mtx);
  10941. while (credits <= 0) {
  10942. sem_cv.wait(lock);
  10943. }
  10944. /* Consume the credit and signal the test code if they are all gone. */
  10945. if (--credits == 0) { sem_cv.notify_one(); }
  10946. });
  10947. if (n < qlimit) {
  10948. /* The first qlimit enqueues must succeed. */
  10949. EXPECT_TRUE(queued);
  10950. } else {
  10951. /* The last one will succeed only when the worker thread
  10952. * starts and dequeues the first blocking task. Although
  10953. * not necessary for the correctness of this test, we sleep for
  10954. * a short while to avoid busy waiting. */
  10955. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10956. }
  10957. if (queued) { n++; }
  10958. }
  10959. /* Further enqueues must fail since the queue is full. */
  10960. for (auto i = 0; i < 4; i++) {
  10961. queued = task_queue->enqueue([] {});
  10962. EXPECT_FALSE(queued);
  10963. }
  10964. /* Give the credits to allow the previous tasks to complete. */
  10965. {
  10966. std::unique_lock<std::mutex> lock(sem_mtx);
  10967. credits += qlimit + 1;
  10968. }
  10969. sem_cv.notify_all();
  10970. /* Wait for all the credits to be consumed. */
  10971. {
  10972. std::unique_lock<std::mutex> lock(sem_mtx);
  10973. while (credits > 0) {
  10974. sem_cv.wait(lock);
  10975. }
  10976. }
  10977. /* Check that we are able again to enqueue at least qlimit tasks. */
  10978. for (unsigned int i = 0; i < qlimit; i++) {
  10979. queued = task_queue->enqueue([] {});
  10980. EXPECT_TRUE(queued);
  10981. }
  10982. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10983. task_queue->shutdown();
  10984. #else
  10985. EXPECT_NO_THROW(task_queue->shutdown());
  10986. #endif
  10987. }
  10988. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10989. Server svr;
  10990. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10991. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10992. });
  10993. svr.Get("/hello", [](const Request &req, Response &res) {
  10994. res.set_content(req.get_param_value("key"), "text/plain");
  10995. });
  10996. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10997. auto se = detail::scope_exit([&] {
  10998. svr.stop();
  10999. thread.join();
  11000. ASSERT_FALSE(svr.is_running());
  11001. });
  11002. svr.wait_until_ready();
  11003. {
  11004. Client cli(HOST, PORT);
  11005. cli.set_follow_location(true);
  11006. auto res = cli.Get("/");
  11007. ASSERT_TRUE(res);
  11008. EXPECT_EQ(StatusCode::OK_200, res->status);
  11009. EXPECT_EQ("val&key2=val2", res->body);
  11010. }
  11011. }
  11012. #endif
  11013. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11014. Server svr;
  11015. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11016. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11017. });
  11018. svr.Get("/hello", [](const Request &req, Response &res) {
  11019. res.set_content(req.get_param_value("key"), "text/plain");
  11020. });
  11021. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11022. auto se = detail::scope_exit([&] {
  11023. svr.stop();
  11024. thread.join();
  11025. ASSERT_FALSE(svr.is_running());
  11026. });
  11027. svr.wait_until_ready();
  11028. {
  11029. Client cli(HOST, PORT);
  11030. cli.set_follow_location(true);
  11031. auto res = cli.Get("/");
  11032. ASSERT_TRUE(res);
  11033. EXPECT_EQ(StatusCode::OK_200, res->status);
  11034. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11035. }
  11036. }
  11037. TEST(RedirectTest, RedirectWithPlusInPath) {
  11038. Server svr;
  11039. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11040. res.set_redirect("/a+b");
  11041. });
  11042. // Route pattern uses regex; escape + as \\+
  11043. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11044. res.set_content(req.path, "text/plain");
  11045. });
  11046. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11047. auto se = detail::scope_exit([&] {
  11048. svr.stop();
  11049. thread.join();
  11050. ASSERT_FALSE(svr.is_running());
  11051. });
  11052. svr.wait_until_ready();
  11053. {
  11054. Client cli(HOST, PORT);
  11055. cli.set_follow_location(true);
  11056. auto res = cli.Get("/");
  11057. ASSERT_TRUE(res);
  11058. EXPECT_EQ(StatusCode::OK_200, res->status);
  11059. EXPECT_EQ("/a+b", res->body);
  11060. }
  11061. }
  11062. #ifdef CPPHTTPLIB_SSL_ENABLED
  11063. TEST(RedirectTest, Issue2185_Online) {
  11064. SSLClient client("github.com");
  11065. client.set_follow_location(true);
  11066. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11067. "Coollab-Windows.zip");
  11068. ASSERT_TRUE(res);
  11069. EXPECT_EQ(StatusCode::OK_200, res->status);
  11070. EXPECT_EQ(9920427U, res->body.size());
  11071. }
  11072. #endif
  11073. TEST(VulnerabilityTest, CRLFInjection) {
  11074. Server svr;
  11075. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11076. res.set_content("Hello 1", "text/plain");
  11077. });
  11078. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11079. res.set_content("Hello 2", "text/plain");
  11080. });
  11081. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11082. res.set_content("Hello 3", "text/plain");
  11083. });
  11084. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11085. res.set_content("Hello 4", "text/plain");
  11086. });
  11087. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11088. for (const auto &x : req.headers) {
  11089. auto key = x.first;
  11090. EXPECT_STRNE("evil", key.c_str());
  11091. }
  11092. });
  11093. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11094. auto se = detail::scope_exit([&] {
  11095. svr.stop();
  11096. thread.join();
  11097. ASSERT_FALSE(svr.is_running());
  11098. });
  11099. svr.wait_until_ready();
  11100. {
  11101. Client cli(HOST, PORT);
  11102. cli.Post("/test1", "A=B",
  11103. "application/x-www-form-urlencoded\r\nevil: hello1");
  11104. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11105. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11106. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11107. }
  11108. }
  11109. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11110. auto server_thread = std::thread([] {
  11111. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11112. default_socket_options(srv);
  11113. sockaddr_in addr{};
  11114. addr.sin_family = AF_INET;
  11115. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11116. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11117. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11118. ::listen(srv, 1);
  11119. sockaddr_in cli_addr{};
  11120. socklen_t cli_len = sizeof(cli_addr);
  11121. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11122. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11123. std::string buf_all;
  11124. char buf[2048];
  11125. ssize_t n;
  11126. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11127. buf_all.append(buf, static_cast<size_t>(n));
  11128. size_t pos;
  11129. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11130. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11131. auto e = request_block.find("\r\n");
  11132. if (e != std::string::npos) {
  11133. auto request_line = request_block.substr(0, e);
  11134. std::string msg =
  11135. "CRLF injection detected in request line: '" + request_line + "'";
  11136. EXPECT_FALSE(true) << msg;
  11137. }
  11138. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11139. ::send(cli,
  11140. #ifdef _WIN32
  11141. static_cast<const char *>(resp.c_str()),
  11142. static_cast<int>(resp.size()),
  11143. #else
  11144. resp.c_str(), resp.size(),
  11145. #endif
  11146. 0);
  11147. buf_all.erase(0, pos + 4);
  11148. }
  11149. }
  11150. detail::close_socket(cli);
  11151. detail::close_socket(srv);
  11152. });
  11153. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11154. auto cli = Client("127.0.0.1", PORT + 1);
  11155. auto headers = Headers{
  11156. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11157. {"Connection", "keep-alive"}};
  11158. auto res = cli.Get("/hi", headers);
  11159. EXPECT_FALSE(res);
  11160. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11161. server_thread.join();
  11162. }
  11163. TEST(PathParamsTest, StaticMatch) {
  11164. const auto pattern = "/users/all";
  11165. detail::PathParamsMatcher matcher(pattern);
  11166. Request request;
  11167. request.path = "/users/all";
  11168. ASSERT_TRUE(matcher.match(request));
  11169. std::unordered_map<std::string, std::string> expected_params = {};
  11170. EXPECT_EQ(request.path_params, expected_params);
  11171. }
  11172. TEST(PathParamsTest, StaticMismatch) {
  11173. const auto pattern = "/users/all";
  11174. detail::PathParamsMatcher matcher(pattern);
  11175. Request request;
  11176. request.path = "/users/1";
  11177. ASSERT_FALSE(matcher.match(request));
  11178. }
  11179. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11180. const auto pattern = "/users/:id/subscriptions";
  11181. detail::PathParamsMatcher matcher(pattern);
  11182. Request request;
  11183. request.path = "/users/42/subscriptions";
  11184. ASSERT_TRUE(matcher.match(request));
  11185. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11186. EXPECT_EQ(request.path_params, expected_params);
  11187. }
  11188. TEST(PathParamsTest, SingleParamInTheEnd) {
  11189. const auto pattern = "/users/:id";
  11190. detail::PathParamsMatcher matcher(pattern);
  11191. Request request;
  11192. request.path = "/users/24";
  11193. ASSERT_TRUE(matcher.match(request));
  11194. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11195. EXPECT_EQ(request.path_params, expected_params);
  11196. }
  11197. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11198. const auto pattern = "/users/:id/";
  11199. detail::PathParamsMatcher matcher(pattern);
  11200. Request request;
  11201. request.path = "/users/42/";
  11202. ASSERT_TRUE(matcher.match(request));
  11203. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11204. EXPECT_EQ(request.path_params, expected_params);
  11205. }
  11206. TEST(PathParamsTest, EmptyParam) {
  11207. const auto pattern = "/users/:id/";
  11208. detail::PathParamsMatcher matcher(pattern);
  11209. Request request;
  11210. request.path = "/users//";
  11211. ASSERT_TRUE(matcher.match(request));
  11212. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11213. EXPECT_EQ(request.path_params, expected_params);
  11214. }
  11215. TEST(PathParamsTest, FragmentMismatch) {
  11216. const auto pattern = "/users/:id/";
  11217. detail::PathParamsMatcher matcher(pattern);
  11218. Request request;
  11219. request.path = "/admins/24/";
  11220. ASSERT_FALSE(matcher.match(request));
  11221. }
  11222. TEST(PathParamsTest, ExtraFragments) {
  11223. const auto pattern = "/users/:id";
  11224. detail::PathParamsMatcher matcher(pattern);
  11225. Request request;
  11226. request.path = "/users/42/subscriptions";
  11227. ASSERT_FALSE(matcher.match(request));
  11228. }
  11229. TEST(PathParamsTest, MissingTrailingParam) {
  11230. const auto pattern = "/users/:id";
  11231. detail::PathParamsMatcher matcher(pattern);
  11232. Request request;
  11233. request.path = "/users";
  11234. ASSERT_FALSE(matcher.match(request));
  11235. }
  11236. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11237. const auto pattern = "/users/:id/subscriptions";
  11238. detail::PathParamsMatcher matcher(pattern);
  11239. Request request;
  11240. request.path = "/users/subscriptions";
  11241. ASSERT_FALSE(matcher.match(request));
  11242. }
  11243. TEST(PathParamsTest, MultipleParams) {
  11244. const auto pattern = "/users/:userid/subscriptions/:subid";
  11245. detail::PathParamsMatcher matcher(pattern);
  11246. Request request;
  11247. request.path = "/users/42/subscriptions/2";
  11248. ASSERT_TRUE(matcher.match(request));
  11249. std::unordered_map<std::string, std::string> expected_params = {
  11250. {"userid", "42"}, {"subid", "2"}};
  11251. EXPECT_EQ(request.path_params, expected_params);
  11252. }
  11253. TEST(PathParamsTest, SequenceOfParams) {
  11254. const auto pattern = "/values/:x/:y/:z";
  11255. detail::PathParamsMatcher matcher(pattern);
  11256. Request request;
  11257. request.path = "/values/1/2/3";
  11258. ASSERT_TRUE(matcher.match(request));
  11259. std::unordered_map<std::string, std::string> expected_params = {
  11260. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11261. EXPECT_EQ(request.path_params, expected_params);
  11262. }
  11263. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11264. const auto pattern = "/prefix:suffix";
  11265. detail::PathParamsMatcher matcher(pattern);
  11266. Request request;
  11267. request.path = "/prefix:suffix";
  11268. ASSERT_TRUE(matcher.match(request));
  11269. const std::unordered_map<std::string, std::string> expected_params = {};
  11270. EXPECT_EQ(request.path_params, expected_params);
  11271. }
  11272. TEST(ParseUrlTest, VariousPatterns) {
  11273. {
  11274. detail::UrlComponents uc;
  11275. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11276. EXPECT_EQ("http", uc.scheme);
  11277. EXPECT_EQ("example.com", uc.host);
  11278. EXPECT_EQ("8080", uc.port);
  11279. EXPECT_EQ("/path", uc.path);
  11280. EXPECT_EQ("?q=1", uc.query);
  11281. }
  11282. {
  11283. detail::UrlComponents uc;
  11284. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11285. EXPECT_EQ("https", uc.scheme);
  11286. EXPECT_EQ("example.com", uc.host);
  11287. EXPECT_TRUE(uc.port.empty());
  11288. EXPECT_EQ("/path", uc.path);
  11289. }
  11290. {
  11291. detail::UrlComponents uc;
  11292. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11293. EXPECT_EQ("::1", uc.host);
  11294. EXPECT_EQ("8080", uc.port);
  11295. EXPECT_EQ("/path", uc.path);
  11296. }
  11297. {
  11298. detail::UrlComponents uc;
  11299. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11300. }
  11301. {
  11302. detail::UrlComponents uc;
  11303. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11304. EXPECT_TRUE(uc.scheme.empty());
  11305. EXPECT_EQ("example.com", uc.host);
  11306. EXPECT_EQ("/path", uc.path);
  11307. EXPECT_EQ("?q=1", uc.query);
  11308. }
  11309. {
  11310. detail::UrlComponents uc;
  11311. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11312. EXPECT_TRUE(uc.host.empty());
  11313. EXPECT_EQ("/path", uc.path);
  11314. EXPECT_EQ("?q=1", uc.query);
  11315. }
  11316. {
  11317. detail::UrlComponents uc;
  11318. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11319. EXPECT_EQ("example.com", uc.host);
  11320. EXPECT_EQ("8080", uc.port);
  11321. }
  11322. {
  11323. // Unix socket path — must not be parsed as host
  11324. detail::UrlComponents uc;
  11325. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11326. EXPECT_TRUE(uc.host.empty());
  11327. }
  11328. {
  11329. detail::UrlComponents uc;
  11330. ASSERT_TRUE(detail::parse_url("", uc));
  11331. EXPECT_TRUE(uc.host.empty());
  11332. EXPECT_TRUE(uc.path.empty());
  11333. }
  11334. {
  11335. detail::UrlComponents uc;
  11336. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11337. }
  11338. {
  11339. detail::UrlComponents uc;
  11340. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11341. }
  11342. {
  11343. // Accepted by parse_url; callers restrict to http/https
  11344. detail::UrlComponents uc;
  11345. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11346. EXPECT_EQ("ftp", uc.scheme);
  11347. }
  11348. {
  11349. detail::UrlComponents uc;
  11350. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11351. }
  11352. {
  11353. detail::UrlComponents uc;
  11354. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11355. }
  11356. }
  11357. TEST(ParseUrlTest, FragmentHandling) {
  11358. {
  11359. detail::UrlComponents uc;
  11360. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11361. EXPECT_EQ("/path", uc.path);
  11362. EXPECT_TRUE(uc.query.empty());
  11363. }
  11364. {
  11365. detail::UrlComponents uc;
  11366. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11367. EXPECT_TRUE(uc.path.empty());
  11368. EXPECT_TRUE(uc.query.empty());
  11369. }
  11370. }
  11371. TEST(ParseUrlTest, UserinfoHandling) {
  11372. // Userinfo with @ but no colon — host includes @
  11373. detail::UrlComponents uc;
  11374. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11375. EXPECT_EQ("user@host.com", uc.host);
  11376. EXPECT_EQ("/path", uc.path);
  11377. }
  11378. TEST(ParseUrlTest, IPv6EdgeCases) {
  11379. {
  11380. detail::UrlComponents uc;
  11381. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11382. EXPECT_TRUE(uc.scheme.empty());
  11383. EXPECT_EQ("::1", uc.host);
  11384. EXPECT_EQ("8080", uc.port);
  11385. }
  11386. {
  11387. // Zone ID '%25' is not in [a-fA-F0-9:]
  11388. detail::UrlComponents uc;
  11389. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11390. }
  11391. }
  11392. TEST(ParseUrlTest, SchemeEdgeCases) {
  11393. {
  11394. detail::UrlComponents uc;
  11395. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11396. }
  11397. {
  11398. detail::UrlComponents uc;
  11399. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11400. }
  11401. {
  11402. detail::UrlComponents uc;
  11403. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11404. }
  11405. }
  11406. TEST(ParseUrlTest, PortEdgeCases) {
  11407. {
  11408. detail::UrlComponents uc;
  11409. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11410. EXPECT_TRUE(uc.port.empty());
  11411. EXPECT_EQ("/path", uc.path);
  11412. }
  11413. {
  11414. // parse_url accepts any port string; validation is done by parse_port
  11415. detail::UrlComponents uc;
  11416. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11417. EXPECT_EQ("abc", uc.port);
  11418. }
  11419. }
  11420. TEST(ParseUrlTest, WebSocketPatterns) {
  11421. {
  11422. detail::UrlComponents uc;
  11423. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11424. EXPECT_EQ("ws", uc.scheme);
  11425. EXPECT_EQ("echo.example.com", uc.host);
  11426. EXPECT_EQ("8080", uc.port);
  11427. EXPECT_EQ("/ws", uc.path);
  11428. }
  11429. {
  11430. detail::UrlComponents uc;
  11431. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11432. EXPECT_EQ("wss", uc.scheme);
  11433. EXPECT_EQ("echo.example.com", uc.host);
  11434. EXPECT_TRUE(uc.port.empty());
  11435. EXPECT_EQ("/ws", uc.path);
  11436. }
  11437. }
  11438. TEST(ParseUrlTest, QueryOnly) {
  11439. detail::UrlComponents uc;
  11440. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11441. EXPECT_TRUE(uc.host.empty());
  11442. EXPECT_TRUE(uc.path.empty());
  11443. EXPECT_EQ("?q=1&r=2", uc.query);
  11444. }
  11445. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11446. detail::UrlComponents uc;
  11447. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11448. EXPECT_TRUE(uc.scheme.empty());
  11449. EXPECT_EQ("example.com", uc.host);
  11450. EXPECT_EQ("443", uc.port);
  11451. EXPECT_EQ("/path", uc.path);
  11452. }
  11453. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11454. // If ipv6 regex working, regex match codepath is taken.
  11455. // else port will default to 80 in Client impl
  11456. int clientImplMagicPort = 80;
  11457. int port = 4321;
  11458. // above ports must be different to avoid false negative
  11459. EXPECT_NE(clientImplMagicPort, port);
  11460. std::string ipV6TestURL = "http://[ff06::c3]";
  11461. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11462. CLIENT_PRIVATE_KEY_FILE);
  11463. EXPECT_EQ(cli.port(), port);
  11464. }
  11465. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11466. auto file_path = "./www/dir/index.html";
  11467. auto dir_path = "./www/dir";
  11468. detail::FileStat stat_file(file_path);
  11469. EXPECT_TRUE(stat_file.is_file());
  11470. EXPECT_FALSE(stat_file.is_dir());
  11471. detail::FileStat stat_dir(dir_path);
  11472. EXPECT_FALSE(stat_dir.is_file());
  11473. EXPECT_TRUE(stat_dir.is_dir());
  11474. }
  11475. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11476. // IPv4 with default HTTP port (80)
  11477. EXPECT_EQ("example.com",
  11478. detail::make_host_and_port_string("example.com", 80, false));
  11479. // IPv4 with default HTTPS port (443)
  11480. EXPECT_EQ("example.com",
  11481. detail::make_host_and_port_string("example.com", 443, true));
  11482. // IPv4 with non-default HTTP port
  11483. EXPECT_EQ("example.com:8080",
  11484. detail::make_host_and_port_string("example.com", 8080, false));
  11485. // IPv4 with non-default HTTPS port
  11486. EXPECT_EQ("example.com:8443",
  11487. detail::make_host_and_port_string("example.com", 8443, true));
  11488. // IPv6 with default HTTP port (80)
  11489. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11490. // IPv6 with default HTTPS port (443)
  11491. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11492. // IPv6 with non-default HTTP port
  11493. EXPECT_EQ("[::1]:8080",
  11494. detail::make_host_and_port_string("::1", 8080, false));
  11495. // IPv6 with non-default HTTPS port
  11496. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11497. // IPv6 full address with default port
  11498. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11499. detail::make_host_and_port_string(
  11500. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11501. // IPv6 full address with non-default port
  11502. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11503. detail::make_host_and_port_string(
  11504. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11505. // IPv6 localhost with non-default port
  11506. EXPECT_EQ("[::1]:3000",
  11507. detail::make_host_and_port_string("::1", 3000, false));
  11508. // IPv6 with zone ID (link-local address) with default port
  11509. EXPECT_EQ("[fe80::1%eth0]",
  11510. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11511. // IPv6 with zone ID (link-local address) with non-default port
  11512. EXPECT_EQ("[fe80::1%eth0]:8080",
  11513. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11514. // Edge case: Port 443 with is_ssl=false (should add port)
  11515. EXPECT_EQ("example.com:443",
  11516. detail::make_host_and_port_string("example.com", 443, false));
  11517. // Edge case: Port 80 with is_ssl=true (should add port)
  11518. EXPECT_EQ("example.com:80",
  11519. detail::make_host_and_port_string("example.com", 80, true));
  11520. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11521. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11522. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11523. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11524. // Security fix: Already bracketed IPv6 should not get double brackets
  11525. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11526. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11527. EXPECT_EQ("[::1]:8080",
  11528. detail::make_host_and_port_string("[::1]", 8080, false));
  11529. EXPECT_EQ("[2001:db8::1]:8080",
  11530. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11531. EXPECT_EQ("[fe80::1%eth0]",
  11532. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11533. EXPECT_EQ("[fe80::1%eth0]:8080",
  11534. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11535. // Edge case: Empty host (should return as-is)
  11536. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11537. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11538. // This is a known limitation but shouldn't crash
  11539. EXPECT_EQ("[host:name]",
  11540. detail::make_host_and_port_string("host:name", 80, false));
  11541. // Port number edge cases (no validation, but should not crash)
  11542. EXPECT_EQ("example.com:0",
  11543. detail::make_host_and_port_string("example.com", 0, false));
  11544. EXPECT_EQ("example.com:-1",
  11545. detail::make_host_and_port_string("example.com", -1, false));
  11546. EXPECT_EQ("example.com:65535",
  11547. detail::make_host_and_port_string("example.com", 65535, false));
  11548. EXPECT_EQ("example.com:65536",
  11549. detail::make_host_and_port_string("example.com", 65536, false));
  11550. }
  11551. #ifdef CPPHTTPLIB_SSL_ENABLED
  11552. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11553. httplib::SSLClient cli("roblox.com", 443);
  11554. cli.set_follow_location(true);
  11555. auto res = cli.Get("/");
  11556. ASSERT_TRUE(res);
  11557. EXPECT_EQ(StatusCode::OK_200, res->status);
  11558. }
  11559. #endif
  11560. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11561. Server svr;
  11562. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11563. EXPECT_EQ(res.status, 400);
  11564. });
  11565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11566. auto se = detail::scope_exit([&] {
  11567. svr.stop();
  11568. thread.join();
  11569. ASSERT_FALSE(svr.is_running());
  11570. });
  11571. svr.wait_until_ready();
  11572. Client cli(HOST, PORT);
  11573. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11574. }
  11575. TEST(InvalidHeaderCharsTest, is_field_name) {
  11576. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11577. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11578. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11579. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11580. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11581. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11582. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11583. EXPECT_FALSE(detail::fields::is_field_name(""));
  11584. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11585. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11586. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11587. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11588. }
  11589. TEST(InvalidHeaderCharsTest, is_field_value) {
  11590. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11591. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11592. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11593. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11594. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11595. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11596. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11597. EXPECT_TRUE(detail::fields::is_field_value(""));
  11598. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11599. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11600. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11601. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11602. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11603. }
  11604. TEST(InvalidHeaderCharsTest, OnServer) {
  11605. Server svr;
  11606. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11607. std::string header = "Not Set";
  11608. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11609. res.set_header(header, "value");
  11610. res.set_content("Page Content Page Content", "text/plain");
  11611. });
  11612. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11613. std::string header = "Not Set";
  11614. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11615. res.set_header("X-Test", header);
  11616. res.set_content("Page Content Page Content", "text/plain");
  11617. });
  11618. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11619. auto se = detail::scope_exit([&] {
  11620. svr.stop();
  11621. thread.join();
  11622. ASSERT_FALSE(svr.is_running());
  11623. });
  11624. svr.wait_until_ready();
  11625. Client cli(HOST, PORT);
  11626. {
  11627. auto res = cli.Get(
  11628. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11629. ASSERT_TRUE(res);
  11630. EXPECT_EQ("Page Content Page Content", res->body);
  11631. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11632. }
  11633. {
  11634. auto res = cli.Get(
  11635. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11636. ASSERT_TRUE(res);
  11637. EXPECT_EQ("Page Content Page Content", res->body);
  11638. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11639. }
  11640. }
  11641. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11642. auto handled = false;
  11643. Server svr;
  11644. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11645. thread t = thread([&] { svr.listen(HOST, PORT); });
  11646. auto se = detail::scope_exit([&] {
  11647. svr.stop();
  11648. t.join();
  11649. ASSERT_FALSE(svr.is_running());
  11650. ASSERT_FALSE(handled);
  11651. });
  11652. svr.wait_until_ready();
  11653. auto req = "POST /test HTTP/1.1\r\n"
  11654. "Content-Length: x\r\n"
  11655. "\r\n";
  11656. std::string response;
  11657. ASSERT_TRUE(send_request(1, req, &response));
  11658. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11659. response.substr(0, response.find("\r\n")));
  11660. }
  11661. #ifndef _WIN32
  11662. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11663. static constexpr char reject[] = "Unauthorized";
  11664. static constexpr char accept[] = "Upload accepted";
  11665. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11666. Server svr;
  11667. svr.set_expect_100_continue_handler(
  11668. [](const Request & /*req*/, Response &res) {
  11669. res.status = StatusCode::Unauthorized_401;
  11670. res.set_content(reject, "text/plain");
  11671. return res.status;
  11672. });
  11673. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11674. res.set_content(accept, "text/plain");
  11675. });
  11676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11677. auto se = detail::scope_exit([&] {
  11678. svr.stop();
  11679. thread.join();
  11680. ASSERT_FALSE(svr.is_running());
  11681. });
  11682. svr.wait_until_ready();
  11683. {
  11684. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11685. curl_easy_init(), &curl_easy_cleanup};
  11686. ASSERT_NE(curl, nullptr);
  11687. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11688. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11689. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11690. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11691. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11692. &curl_slist_free_all};
  11693. ASSERT_NE(list, nullptr);
  11694. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11695. struct read_data {
  11696. size_t read_size;
  11697. size_t total_size;
  11698. } data = {0, total_size};
  11699. using read_callback_t =
  11700. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11701. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11702. void *userdata) -> size_t {
  11703. read_data *d = (read_data *)userdata;
  11704. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11705. std::fill_n(ptr, size * nmemb, 'A');
  11706. d->read_size += size * nmemb;
  11707. return size * nmemb;
  11708. };
  11709. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11710. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11711. std::vector<char> buffer;
  11712. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11713. using write_callback_t =
  11714. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11715. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11716. void *userdata) -> size_t {
  11717. std::vector<char> *buf = (std::vector<char> *)userdata;
  11718. buf->reserve(buf->size() + size * nmemb + 1);
  11719. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11720. return size * nmemb;
  11721. };
  11722. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11723. {
  11724. const auto res = curl_easy_perform(curl.get());
  11725. ASSERT_EQ(res, CURLE_OK);
  11726. }
  11727. {
  11728. auto response_code = long{};
  11729. const auto res =
  11730. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11731. ASSERT_EQ(res, CURLE_OK);
  11732. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11733. }
  11734. {
  11735. auto dl = curl_off_t{};
  11736. const auto res =
  11737. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11738. ASSERT_EQ(res, CURLE_OK);
  11739. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11740. }
  11741. {
  11742. buffer.push_back('\0');
  11743. ASSERT_STRCASEEQ(buffer.data(), reject);
  11744. }
  11745. }
  11746. }
  11747. #endif
  11748. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  11749. // Regression test for #2458.
  11750. //
  11751. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  11752. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  11753. // ticket can make the client socket spuriously readable during the
  11754. // 100-continue wait. If the readiness is mistaken for an incoming response,
  11755. // the client withholds the body and then blocks reading a response that never
  11756. // comes, failing with `Failed to read connection`.
  11757. //
  11758. // A correct client (like curl) sends the body once no `100 Continue` arrives
  11759. // within the timeout. This raw OpenSSL server deliberately never sends
  11760. // `100 Continue`; the client must still deliver the body and receive 200.
  11761. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  11762. signal(SIGPIPE, SIG_IGN);
  11763. const auto port = PORT + 4;
  11764. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11765. ASSERT_NE(srv, INVALID_SOCKET);
  11766. int opt = 1;
  11767. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  11768. sockaddr_in addr{};
  11769. addr.sin_family = AF_INET;
  11770. addr.sin_port = htons(static_cast<uint16_t>(port));
  11771. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11772. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11773. ASSERT_EQ(0, ::listen(srv, 1));
  11774. std::atomic<size_t> server_body_bytes{0};
  11775. auto server_thread = std::thread([&] {
  11776. sockaddr_in cli_addr{};
  11777. socklen_t cli_len = sizeof(cli_addr);
  11778. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11779. if (cli == INVALID_SOCKET) { return; }
  11780. // Bound the lifetime of the server side so a buggy client (which never
  11781. // sends the body) cannot make this thread block forever on join.
  11782. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  11783. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  11784. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  11785. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  11786. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  11787. SSL *ssl = SSL_new(ctx);
  11788. SSL_set_fd(ssl, static_cast<int>(cli));
  11789. if (SSL_accept(ssl) > 0) {
  11790. // Read the request headers. Reading here also flushes the TLS 1.3
  11791. // session tickets to the client. Deliberately do NOT send
  11792. // `100 Continue`.
  11793. std::string buf;
  11794. char tmp[1024];
  11795. while (buf.find("\r\n\r\n") == std::string::npos) {
  11796. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11797. if (n <= 0) { break; }
  11798. buf.append(tmp, static_cast<size_t>(n));
  11799. }
  11800. // A correct client sends the body now; count what arrives.
  11801. auto pos = buf.find("\r\n\r\n");
  11802. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  11803. while (body < 4096) {
  11804. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11805. if (n <= 0) { break; }
  11806. body += static_cast<size_t>(n);
  11807. }
  11808. server_body_bytes = body;
  11809. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  11810. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  11811. SSL_shutdown(ssl);
  11812. }
  11813. SSL_free(ssl);
  11814. detail::close_socket(cli);
  11815. SSL_CTX_free(ctx);
  11816. });
  11817. auto se = detail::scope_exit([&] {
  11818. server_thread.join();
  11819. detail::close_socket(srv);
  11820. });
  11821. SSLClient cli("127.0.0.1", port);
  11822. cli.enable_server_certificate_verification(false);
  11823. cli.set_connection_timeout(5, 0);
  11824. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  11825. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  11826. std::string body(4096, 'A');
  11827. auto res = cli.Put("/api/test", body, "application/json");
  11828. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  11829. EXPECT_EQ(StatusCode::OK_200, res->status);
  11830. EXPECT_EQ(body.size(), server_body_bytes.load());
  11831. }
  11832. #endif
  11833. template <typename S, typename C>
  11834. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11835. svr.Get("/stream", [&](const Request &, Response &res) {
  11836. auto data = new std::string("01234567890123456789");
  11837. res.set_content_provider(
  11838. data->size(), "text/plain",
  11839. [&, data](size_t offset, size_t length, DataSink &sink) {
  11840. const size_t DATA_CHUNK_SIZE = 4;
  11841. const auto &d = *data;
  11842. std::this_thread::sleep_for(std::chrono::seconds(1));
  11843. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11844. return true;
  11845. },
  11846. [data](bool success) {
  11847. EXPECT_FALSE(success);
  11848. delete data;
  11849. });
  11850. });
  11851. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11852. auto i = new size_t(0);
  11853. res.set_content_provider(
  11854. "text/plain",
  11855. [i](size_t, DataSink &sink) {
  11856. if (*i < 5) {
  11857. std::this_thread::sleep_for(std::chrono::seconds(1));
  11858. sink.write("abcd", 4);
  11859. (*i)++;
  11860. } else {
  11861. sink.done();
  11862. }
  11863. return true;
  11864. },
  11865. [i](bool success) {
  11866. EXPECT_FALSE(success);
  11867. delete i;
  11868. });
  11869. });
  11870. svr.Get("/chunked", [&](const Request &, Response &res) {
  11871. auto i = new size_t(0);
  11872. res.set_chunked_content_provider(
  11873. "text/plain",
  11874. [i](size_t, DataSink &sink) {
  11875. if (*i < 5) {
  11876. std::this_thread::sleep_for(std::chrono::seconds(1));
  11877. sink.os << "abcd";
  11878. (*i)++;
  11879. } else {
  11880. sink.done();
  11881. }
  11882. return true;
  11883. },
  11884. [i](bool success) {
  11885. EXPECT_FALSE(success);
  11886. delete i;
  11887. });
  11888. });
  11889. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11890. auto se = detail::scope_exit([&] {
  11891. svr.stop();
  11892. listen_thread.join();
  11893. ASSERT_FALSE(svr.is_running());
  11894. });
  11895. svr.wait_until_ready();
  11896. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11897. {
  11898. auto start = std::chrono::steady_clock::now();
  11899. auto res = cli.Get("/stream");
  11900. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11901. std::chrono::steady_clock::now() - start)
  11902. .count();
  11903. ASSERT_FALSE(res);
  11904. EXPECT_EQ(Error::Read, res.error());
  11905. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11906. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11907. }
  11908. {
  11909. auto start = std::chrono::steady_clock::now();
  11910. auto res = cli.Get("/stream_without_length");
  11911. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11912. std::chrono::steady_clock::now() - start)
  11913. .count();
  11914. ASSERT_FALSE(res);
  11915. EXPECT_EQ(Error::Read, res.error());
  11916. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11917. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11918. }
  11919. {
  11920. auto start = std::chrono::steady_clock::now();
  11921. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11922. EXPECT_EQ("abcd", string(data, data_length));
  11923. return true;
  11924. });
  11925. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11926. std::chrono::steady_clock::now() - start)
  11927. .count();
  11928. ASSERT_FALSE(res);
  11929. EXPECT_EQ(Error::Read, res.error());
  11930. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11931. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11932. }
  11933. }
  11934. TEST(MaxTimeoutTest, ContentStream) {
  11935. time_t timeout = 2000;
  11936. time_t threshold = 200;
  11937. Server svr;
  11938. Client cli("localhost", PORT);
  11939. max_timeout_test(svr, cli, timeout, threshold);
  11940. }
  11941. #ifdef CPPHTTPLIB_SSL_ENABLED
  11942. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11943. time_t timeout = 2000;
  11944. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11945. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11946. SSLClient cli("localhost", PORT);
  11947. cli.enable_server_certificate_verification(false);
  11948. max_timeout_test(svr, cli, timeout, threshold);
  11949. }
  11950. #endif
  11951. class EventDispatcher {
  11952. public:
  11953. EventDispatcher() {}
  11954. bool wait_event(DataSink *sink) {
  11955. unique_lock<mutex> lk(m_);
  11956. int id = id_;
  11957. // Wait with timeout to prevent hanging if client disconnects
  11958. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11959. [&] { return cid_ == id; })) {
  11960. return false; // Timeout occurred
  11961. }
  11962. sink->write(message_.data(), message_.size());
  11963. return true;
  11964. }
  11965. void send_event(const string &message) {
  11966. lock_guard<mutex> lk(m_);
  11967. cid_ = id_++;
  11968. message_ = message;
  11969. cv_.notify_all();
  11970. }
  11971. private:
  11972. mutex m_;
  11973. condition_variable cv_;
  11974. atomic_int id_{0};
  11975. atomic_int cid_{-1};
  11976. string message_;
  11977. };
  11978. TEST(ClientInThreadTest, Issue2068) {
  11979. EventDispatcher ed;
  11980. Server svr;
  11981. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11982. res.set_chunked_content_provider("text/event-stream",
  11983. [&](size_t /*offset*/, DataSink &sink) {
  11984. return ed.wait_event(&sink);
  11985. });
  11986. });
  11987. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11988. svr.wait_until_ready();
  11989. thread event_thread([&] {
  11990. int id = 0;
  11991. while (svr.is_running()) {
  11992. this_thread::sleep_for(chrono::milliseconds(500));
  11993. std::stringstream ss;
  11994. ss << "data: " << id << "\n\n";
  11995. ed.send_event(ss.str());
  11996. id++;
  11997. }
  11998. });
  11999. auto se = detail::scope_exit([&] {
  12000. svr.stop();
  12001. listen_thread.join();
  12002. event_thread.join();
  12003. ASSERT_FALSE(svr.is_running());
  12004. });
  12005. {
  12006. auto client = detail::make_unique<Client>(HOST, PORT);
  12007. client->set_read_timeout(std::chrono::minutes(10));
  12008. std::atomic<bool> stop{false};
  12009. std::thread t([&] {
  12010. client->Get("/event1",
  12011. [&](const char *, size_t) -> bool { return !stop; });
  12012. });
  12013. std::this_thread::sleep_for(std::chrono::seconds(2));
  12014. stop = true;
  12015. client->stop();
  12016. t.join();
  12017. // Reset client after thread has finished
  12018. client.reset();
  12019. }
  12020. }
  12021. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12022. auto handled = false;
  12023. Server svr;
  12024. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12025. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12026. auto se = detail::scope_exit([&] {
  12027. svr.stop();
  12028. t.join();
  12029. ASSERT_FALSE(svr.is_running());
  12030. ASSERT_FALSE(handled);
  12031. });
  12032. svr.wait_until_ready();
  12033. // Two Content-Length headers with different values — must be rejected
  12034. auto req = "POST /test HTTP/1.1\r\n"
  12035. "Content-Length: 5\r\n"
  12036. "Content-Length: 10\r\n"
  12037. "\r\n"
  12038. "hello";
  12039. std::string response;
  12040. ASSERT_TRUE(send_request(1, req, &response));
  12041. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12042. response.substr(0, response.find("\r\n")));
  12043. }
  12044. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12045. auto handled = false;
  12046. Server svr;
  12047. svr.Post("/test", [&](const Request &, Response &res) {
  12048. handled = true;
  12049. res.set_content("ok", "text/plain");
  12050. });
  12051. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12052. auto se = detail::scope_exit([&] {
  12053. svr.stop();
  12054. t.join();
  12055. ASSERT_FALSE(svr.is_running());
  12056. ASSERT_TRUE(handled);
  12057. });
  12058. svr.wait_until_ready();
  12059. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12060. auto req = "POST /test HTTP/1.1\r\n"
  12061. "Content-Length: 5\r\n"
  12062. "Content-Length: 5\r\n"
  12063. "\r\n"
  12064. "hello";
  12065. std::string response;
  12066. ASSERT_TRUE(send_request(1, req, &response));
  12067. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12068. }
  12069. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12070. Server svr;
  12071. svr.Get("/", [](const Request &req, Response &res) {
  12072. EXPECT_EQ(2U, req.trailers.size());
  12073. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12074. // Denied
  12075. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12076. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12077. // Accepted
  12078. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12079. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12080. EXPECT_TRUE(req.has_trailer("X-World"));
  12081. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12082. res.set_content("ok", "text/plain");
  12083. });
  12084. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12085. auto se = detail::scope_exit([&] {
  12086. svr.stop();
  12087. t.join();
  12088. ASSERT_FALSE(svr.is_running());
  12089. });
  12090. svr.wait_until_ready();
  12091. const std::string req = "GET / HTTP/1.1\r\n"
  12092. "Transfer-Encoding: chunked\r\n"
  12093. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12094. "\r\n"
  12095. "0\r\n"
  12096. "Content-Length: 10\r\n"
  12097. "Host: internal.local\r\n"
  12098. "Content-Type: malicious/content\r\n"
  12099. "Cookie: any\r\n"
  12100. "Set-Cookie: any\r\n"
  12101. "X-Forwarded-For: attacker.com\r\n"
  12102. "X-Real-Ip: 1.1.1.1\r\n"
  12103. "X-Hello: hello\r\n"
  12104. "X-World: world\r\n"
  12105. "\r\n";
  12106. std::string res;
  12107. ASSERT_TRUE(send_request(1, req, &res));
  12108. }
  12109. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12110. Server svr;
  12111. std::string observed_remote_addr;
  12112. std::string observed_xff;
  12113. svr.Get("/ip", [&](const Request &req, Response &res) {
  12114. observed_remote_addr = req.remote_addr;
  12115. observed_xff = req.get_header_value("X-Forwarded-For");
  12116. res.set_content("ok", "text/plain");
  12117. });
  12118. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12119. auto se = detail::scope_exit([&] {
  12120. svr.stop();
  12121. t.join();
  12122. ASSERT_FALSE(svr.is_running());
  12123. });
  12124. svr.wait_until_ready();
  12125. Client cli(HOST, PORT);
  12126. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  12127. ASSERT_TRUE(res);
  12128. EXPECT_EQ(StatusCode::OK_200, res->status);
  12129. EXPECT_EQ(observed_xff, "203.0.113.66");
  12130. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12131. observed_remote_addr == "127.0.0.1");
  12132. }
  12133. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12134. Server svr;
  12135. svr.set_trusted_proxies({"203.0.113.66"});
  12136. std::string observed_remote_addr;
  12137. std::string observed_xff;
  12138. svr.Get("/ip", [&](const Request &req, Response &res) {
  12139. observed_remote_addr = req.remote_addr;
  12140. observed_xff = req.get_header_value("X-Forwarded-For");
  12141. res.set_content("ok", "text/plain");
  12142. });
  12143. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12144. auto se = detail::scope_exit([&] {
  12145. svr.stop();
  12146. t.join();
  12147. ASSERT_FALSE(svr.is_running());
  12148. });
  12149. svr.wait_until_ready();
  12150. Client cli(HOST, PORT);
  12151. auto res = cli.Get("/ip");
  12152. ASSERT_TRUE(res);
  12153. EXPECT_EQ(StatusCode::OK_200, res->status);
  12154. EXPECT_EQ(observed_xff, "");
  12155. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12156. observed_remote_addr == "127.0.0.1");
  12157. }
  12158. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12159. Server svr;
  12160. svr.set_trusted_proxies({"203.0.113.66"});
  12161. std::string observed_remote_addr;
  12162. std::string observed_xff;
  12163. svr.Get("/ip", [&](const Request &req, Response &res) {
  12164. observed_remote_addr = req.remote_addr;
  12165. observed_xff = req.get_header_value("X-Forwarded-For");
  12166. res.set_content("ok", "text/plain");
  12167. });
  12168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12169. auto se = detail::scope_exit([&] {
  12170. svr.stop();
  12171. t.join();
  12172. ASSERT_FALSE(svr.is_running());
  12173. });
  12174. svr.wait_until_ready();
  12175. Client cli(HOST, PORT);
  12176. auto res =
  12177. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12178. ASSERT_TRUE(res);
  12179. EXPECT_EQ(StatusCode::OK_200, res->status);
  12180. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12181. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12182. }
  12183. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12184. Server svr;
  12185. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12186. std::string observed_remote_addr;
  12187. std::string observed_xff;
  12188. svr.Get("/ip", [&](const Request &req, Response &res) {
  12189. observed_remote_addr = req.remote_addr;
  12190. observed_xff = req.get_header_value("X-Forwarded-For");
  12191. res.set_content("ok", "text/plain");
  12192. });
  12193. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12194. auto se = detail::scope_exit([&] {
  12195. svr.stop();
  12196. t.join();
  12197. ASSERT_FALSE(svr.is_running());
  12198. });
  12199. svr.wait_until_ready();
  12200. Client cli(HOST, PORT);
  12201. auto res = cli.Get(
  12202. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12203. ASSERT_TRUE(res);
  12204. EXPECT_EQ(StatusCode::OK_200, res->status);
  12205. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12206. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12207. }
  12208. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12209. Server svr;
  12210. svr.set_trusted_proxies({"192.0.2.45"});
  12211. std::string observed_remote_addr;
  12212. std::string observed_xff;
  12213. svr.Get("/ip", [&](const Request &req, Response &res) {
  12214. observed_remote_addr = req.remote_addr;
  12215. observed_xff = req.get_header_value("X-Forwarded-For");
  12216. res.set_content("ok", "text/plain");
  12217. });
  12218. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12219. auto se = detail::scope_exit([&] {
  12220. svr.stop();
  12221. t.join();
  12222. ASSERT_FALSE(svr.is_running());
  12223. });
  12224. svr.wait_until_ready();
  12225. Client cli(HOST, PORT);
  12226. auto res =
  12227. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12228. ASSERT_TRUE(res);
  12229. EXPECT_EQ(StatusCode::OK_200, res->status);
  12230. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12231. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12232. }
  12233. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12234. Server svr;
  12235. svr.set_trusted_proxies({"192.0.2.45"});
  12236. std::string observed_remote_addr;
  12237. std::string observed_xff;
  12238. svr.Get("/ip", [&](const Request &req, Response &res) {
  12239. observed_remote_addr = req.remote_addr;
  12240. observed_xff = req.get_header_value("X-Forwarded-For");
  12241. res.set_content("ok", "text/plain");
  12242. });
  12243. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12244. auto se = detail::scope_exit([&] {
  12245. svr.stop();
  12246. t.join();
  12247. ASSERT_FALSE(svr.is_running());
  12248. });
  12249. svr.wait_until_ready();
  12250. Client cli(HOST, PORT);
  12251. auto res = cli.Get(
  12252. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12253. ASSERT_TRUE(res);
  12254. EXPECT_EQ(StatusCode::OK_200, res->status);
  12255. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12256. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12257. }
  12258. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12259. Server svr;
  12260. svr.set_trusted_proxies({"192.0.2.45"});
  12261. std::string observed_remote_addr;
  12262. std::string observed_xff;
  12263. svr.Get("/ip", [&](const Request &req, Response &res) {
  12264. observed_remote_addr = req.remote_addr;
  12265. observed_xff = req.get_header_value("X-Forwarded-For");
  12266. res.set_content("ok", "text/plain");
  12267. });
  12268. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12269. auto se = detail::scope_exit([&] {
  12270. svr.stop();
  12271. t.join();
  12272. ASSERT_FALSE(svr.is_running());
  12273. });
  12274. svr.wait_until_ready();
  12275. std::string raw_req =
  12276. "GET /ip HTTP/1.1\r\n"
  12277. "Host: localhost\r\n"
  12278. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12279. "Connection: close\r\n"
  12280. "\r\n";
  12281. std::string out;
  12282. ASSERT_TRUE(send_request(5, raw_req, &out));
  12283. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12284. // Header parser trims surrounding whitespace of the header value
  12285. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12286. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12287. }
  12288. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12289. // crash the server (it used to call front() on an empty vector inside
  12290. // get_client_ip). The connection-level remote address must be retained instead.
  12291. static void run_malformed_xff_test(const std::string &xff_value) {
  12292. Server svr;
  12293. svr.set_trusted_proxies({"192.0.2.45"});
  12294. std::string observed_remote_addr;
  12295. svr.Get("/ip", [&](const Request &req, Response &res) {
  12296. observed_remote_addr = req.remote_addr;
  12297. res.set_content("ok", "text/plain");
  12298. });
  12299. int port = 0;
  12300. thread t = thread([&]() {
  12301. port = svr.bind_to_any_port(HOST);
  12302. svr.listen_after_bind();
  12303. });
  12304. auto se = detail::scope_exit([&] {
  12305. svr.stop();
  12306. t.join();
  12307. ASSERT_FALSE(svr.is_running());
  12308. });
  12309. svr.wait_until_ready();
  12310. Client cli(HOST, port);
  12311. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  12312. ASSERT_TRUE(res);
  12313. EXPECT_EQ(StatusCode::OK_200, res->status);
  12314. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12315. observed_remote_addr == "127.0.0.1");
  12316. }
  12317. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12318. run_malformed_xff_test("");
  12319. }
  12320. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12321. run_malformed_xff_test(",");
  12322. }
  12323. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12324. run_malformed_xff_test(", , ,");
  12325. }
  12326. #ifndef _WIN32
  12327. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12328. Server svr;
  12329. svr.Post("/post", [&](const Request &req, Response &res) {
  12330. res.set_content(req.body, "text/plain");
  12331. });
  12332. svr.Put("/put", [&](const Request &req, Response &res) {
  12333. res.set_content(req.body, "text/plain");
  12334. });
  12335. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12336. res.set_content(req.body, "text/plain");
  12337. });
  12338. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12339. res.set_content(req.body, "text/plain");
  12340. });
  12341. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12342. auto se = detail::scope_exit([&] {
  12343. svr.stop();
  12344. t.join();
  12345. ASSERT_FALSE(svr.is_running());
  12346. });
  12347. svr.wait_until_ready();
  12348. std::string resp;
  12349. // POST without Content-Length
  12350. ASSERT_TRUE(send_request(5,
  12351. "POST /post HTTP/1.1\r\n"
  12352. "Host: localhost\r\n"
  12353. "Connection: close\r\n"
  12354. "\r\n",
  12355. &resp));
  12356. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12357. // PUT without Content-Length
  12358. resp.clear();
  12359. ASSERT_TRUE(send_request(5,
  12360. "PUT /put HTTP/1.1\r\n"
  12361. "Host: localhost\r\n"
  12362. "Connection: close\r\n"
  12363. "\r\n",
  12364. &resp));
  12365. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12366. // PATCH without Content-Length
  12367. resp.clear();
  12368. ASSERT_TRUE(send_request(5,
  12369. "PATCH /patch HTTP/1.1\r\n"
  12370. "Host: localhost\r\n"
  12371. "Connection: close\r\n"
  12372. "\r\n",
  12373. &resp));
  12374. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12375. // DELETE without Content-Length
  12376. resp.clear();
  12377. ASSERT_TRUE(send_request(5,
  12378. "DELETE /delete HTTP/1.1\r\n"
  12379. "Host: localhost\r\n"
  12380. "Connection: close\r\n"
  12381. "\r\n",
  12382. &resp));
  12383. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12384. }
  12385. #endif
  12386. //==============================================================================
  12387. // open_stream() Tests
  12388. //==============================================================================
  12389. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12390. std::string result;
  12391. char buf[8192];
  12392. ssize_t n;
  12393. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12394. result.append(buf, static_cast<size_t>(n));
  12395. }
  12396. return result;
  12397. }
  12398. // Mock stream for unit tests
  12399. class MockStream : public Stream {
  12400. public:
  12401. std::string data;
  12402. size_t pos = 0;
  12403. ssize_t error_after = -1; // -1 = no error
  12404. explicit MockStream(const std::string &d, ssize_t err = -1)
  12405. : data(d), error_after(err) {}
  12406. bool is_readable() const override { return true; }
  12407. bool wait_readable() const override { return true; }
  12408. bool wait_writable() const override { return true; }
  12409. ssize_t read(char *ptr, size_t size) override {
  12410. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12411. if (pos >= data.size()) return 0;
  12412. size_t limit =
  12413. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12414. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12415. std::memcpy(ptr, data.data() + pos, to_read);
  12416. pos += to_read;
  12417. return static_cast<ssize_t>(to_read);
  12418. }
  12419. ssize_t write(const char *, size_t) override { return -1; }
  12420. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12421. ip = "127.0.0.1";
  12422. port = 0;
  12423. }
  12424. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12425. ip = "127.0.0.1";
  12426. port = 0;
  12427. }
  12428. socket_t socket() const override { return INVALID_SOCKET; }
  12429. time_t duration() const override { return 0; }
  12430. };
  12431. TEST(StreamHandleTest, Basic) {
  12432. ClientImpl::StreamHandle handle;
  12433. EXPECT_FALSE(handle.is_valid());
  12434. handle.response = detail::make_unique<Response>();
  12435. handle.error = Error::Connection;
  12436. EXPECT_FALSE(handle.is_valid());
  12437. handle.error = Error::Success;
  12438. EXPECT_TRUE(handle.is_valid());
  12439. }
  12440. TEST(BodyReaderTest, Basic) {
  12441. MockStream stream("Hello, World!");
  12442. detail::BodyReader reader;
  12443. reader.stream = &stream;
  12444. reader.content_length = 13;
  12445. char buf[32];
  12446. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12447. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12448. EXPECT_TRUE(reader.eof);
  12449. }
  12450. TEST(BodyReaderTest, NoStream) {
  12451. detail::BodyReader reader;
  12452. char buf[32];
  12453. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12454. EXPECT_EQ(Error::Connection, reader.last_error);
  12455. }
  12456. TEST(BodyReaderTest, Error) {
  12457. MockStream stream("Hello, World!", 5);
  12458. detail::BodyReader reader;
  12459. reader.stream = &stream;
  12460. reader.content_length = 13;
  12461. char buf[32];
  12462. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12463. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12464. EXPECT_EQ(Error::Read, reader.last_error);
  12465. }
  12466. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12467. // Mock-based StreamHandle tests relying on private internals are removed.
  12468. class OpenStreamTest : public ::testing::Test {
  12469. protected:
  12470. void SetUp() override {
  12471. svr_.Get("/hello", [](const Request &, Response &res) {
  12472. res.set_content("Hello World!", "text/plain");
  12473. });
  12474. svr_.Get("/large", [](const Request &, Response &res) {
  12475. res.set_content(std::string(10000, 'X'), "text/plain");
  12476. });
  12477. svr_.Get("/chunked", [](const Request &, Response &res) {
  12478. res.set_chunked_content_provider("text/plain",
  12479. [](size_t offset, DataSink &sink) {
  12480. if (offset < 15) {
  12481. sink.write("chunk", 5);
  12482. return true;
  12483. }
  12484. sink.done();
  12485. return true;
  12486. });
  12487. });
  12488. svr_.Get("/compressible", [](const Request &, Response &res) {
  12489. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12490. DataSink &sink) {
  12491. if (offset < 100 * 1024) {
  12492. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12493. sink.write(chunk.data(), chunk.size());
  12494. return true;
  12495. }
  12496. sink.done();
  12497. return true;
  12498. });
  12499. });
  12500. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12501. [](const Request & /*req*/, Response &res) {
  12502. auto i = new int(0);
  12503. res.set_header("Trailer", "Content-Length, X-Allowed");
  12504. res.set_chunked_content_provider(
  12505. "text/plain",
  12506. [i](size_t /*offset*/, DataSink &sink) {
  12507. switch (*i) {
  12508. case 0: sink.os << "123"; break;
  12509. case 1: sink.os << "456"; break;
  12510. case 2: sink.os << "789"; break;
  12511. case 3: {
  12512. sink.done_with_trailer(
  12513. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12514. } break;
  12515. }
  12516. (*i)++;
  12517. return true;
  12518. },
  12519. [i](bool success) {
  12520. EXPECT_TRUE(success);
  12521. delete i;
  12522. });
  12523. });
  12524. // Echo headers endpoint for header-related tests
  12525. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12526. std::string body;
  12527. for (const auto &h : req.headers) {
  12528. body.append(h.first);
  12529. body.push_back(':');
  12530. body.append(h.second);
  12531. body.push_back('\n');
  12532. }
  12533. res.set_content(body, "text/plain");
  12534. });
  12535. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12536. std::string body;
  12537. for (const auto &h : req.headers) {
  12538. body.append(h.first);
  12539. body.push_back(':');
  12540. body.append(h.second);
  12541. body.push_back('\n');
  12542. }
  12543. res.set_content(body, "text/plain");
  12544. });
  12545. port_ = svr_.bind_to_any_port("127.0.0.1");
  12546. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12547. svr_.wait_until_ready();
  12548. }
  12549. void TearDown() override {
  12550. svr_.stop();
  12551. if (thread_.joinable()) thread_.join();
  12552. }
  12553. Server svr_;
  12554. std::thread thread_;
  12555. int port_ = 0;
  12556. };
  12557. TEST_F(OpenStreamTest, Basic) {
  12558. Client cli("127.0.0.1", port_);
  12559. auto handle = cli.open_stream("GET", "/hello");
  12560. EXPECT_TRUE(handle.is_valid());
  12561. EXPECT_EQ("Hello World!", read_all(handle));
  12562. }
  12563. TEST_F(OpenStreamTest, SmallBuffer) {
  12564. Client cli("127.0.0.1", port_);
  12565. auto handle = cli.open_stream("GET", "/hello");
  12566. std::string result;
  12567. char buf[4];
  12568. ssize_t n;
  12569. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12570. result.append(buf, static_cast<size_t>(n));
  12571. EXPECT_EQ("Hello World!", result);
  12572. }
  12573. TEST_F(OpenStreamTest, DefaultHeaders) {
  12574. Client cli("127.0.0.1", port_);
  12575. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12576. {
  12577. auto handle = cli.open_stream("GET", "/echo-headers");
  12578. ASSERT_TRUE(handle.is_valid());
  12579. auto body = read_all(handle);
  12580. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12581. std::string::npos);
  12582. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12583. std::string::npos);
  12584. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12585. }
  12586. // open_stream POST with body and no explicit content_type should NOT add
  12587. // text/plain Content-Type (behavior differs from non-streaming path), but
  12588. // should include Content-Length
  12589. {
  12590. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12591. ASSERT_TRUE(handle.is_valid());
  12592. auto body = read_all(handle);
  12593. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12594. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12595. }
  12596. // open_stream POST with explicit Content-Type should preserve it
  12597. {
  12598. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12599. {{"Content-Type", "application/custom"}},
  12600. "{}", "application/custom");
  12601. ASSERT_TRUE(handle.is_valid());
  12602. auto body = read_all(handle);
  12603. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12604. }
  12605. // User-specified User-Agent must not be overwritten for stream API
  12606. {
  12607. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12608. {{"User-Agent", "MyAgent/1.2"}});
  12609. ASSERT_TRUE(handle.is_valid());
  12610. auto body = read_all(handle);
  12611. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12612. }
  12613. }
  12614. TEST_F(OpenStreamTest, Large) {
  12615. Client cli("127.0.0.1", port_);
  12616. auto handle = cli.open_stream("GET", "/large");
  12617. EXPECT_EQ(10000u, read_all(handle).size());
  12618. }
  12619. TEST_F(OpenStreamTest, ConnectionError) {
  12620. Client cli("127.0.0.1", 9999);
  12621. auto handle = cli.open_stream("GET", "/hello");
  12622. EXPECT_FALSE(handle.is_valid());
  12623. }
  12624. TEST_F(OpenStreamTest, Chunked) {
  12625. Client cli("127.0.0.1", port_);
  12626. auto handle = cli.open_stream("GET", "/chunked");
  12627. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12628. "Transfer-Encoding") == "chunked");
  12629. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12630. }
  12631. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12632. Client cli("127.0.0.1", port_);
  12633. auto handle =
  12634. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12635. ASSERT_TRUE(handle.is_valid());
  12636. // Consume body to allow trailers to be received/parsed
  12637. auto body = read_all(handle);
  12638. // Explicitly parse trailers (ensure trailers are available for assertion)
  12639. handle.parse_trailers_if_needed();
  12640. EXPECT_EQ(std::string("123456789"), body);
  12641. // The response should include a Trailer header declaring both names
  12642. ASSERT_TRUE(handle.response);
  12643. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12644. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12645. handle.response->get_header_value("Trailer"));
  12646. // Prohibited trailer must not be present
  12647. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12648. // Allowed trailer should be present
  12649. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12650. EXPECT_EQ(std::string("yes"),
  12651. handle.response->get_trailer_value("X-Allowed"));
  12652. // Verify trailers are NOT present as regular headers
  12653. EXPECT_EQ(std::string(""),
  12654. handle.response->get_header_value("Content-Length"));
  12655. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12656. }
  12657. static std::thread serve_single_response(std::promise<int> &port_promise,
  12658. const std::string &response) {
  12659. return std::thread([&port_promise, response] {
  12660. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12661. default_socket_options(srv);
  12662. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12663. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12664. sockaddr_in addr{};
  12665. addr.sin_family = AF_INET;
  12666. addr.sin_port = htons(0); // Let OS assign a free port
  12667. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12668. int opt = 1;
  12669. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12670. #ifdef _WIN32
  12671. reinterpret_cast<const char *>(&opt),
  12672. #else
  12673. &opt,
  12674. #endif
  12675. sizeof(opt));
  12676. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12677. ::listen(srv, 1) != 0) {
  12678. port_promise.set_value(-1);
  12679. detail::close_socket(srv);
  12680. return;
  12681. }
  12682. socklen_t addr_len = sizeof(addr);
  12683. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12684. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12685. sockaddr_in cli_addr{};
  12686. socklen_t cli_len = sizeof(cli_addr);
  12687. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12688. if (cli != INVALID_SOCKET) {
  12689. // Read the complete HTTP request (until the blank line that terminates
  12690. // headers) before sending the response. If the server closes the socket
  12691. // while the client's request data is still unread in the kernel receive
  12692. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12693. // connection on both sides: it discards the client's receive buffer
  12694. // (which already holds our response) and causes any in-progress write on
  12695. // the client to fail with ECONNRESET. Reading all request data first
  12696. // ensures close() emits a graceful FIN.
  12697. {
  12698. char rbuf[256];
  12699. std::string req;
  12700. while (req.find("\r\n\r\n") == std::string::npos) {
  12701. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12702. if (n <= 0) { break; }
  12703. req.append(rbuf, static_cast<size_t>(n));
  12704. }
  12705. }
  12706. ::send(cli,
  12707. #ifdef _WIN32
  12708. static_cast<const char *>(response.c_str()),
  12709. static_cast<int>(response.size()),
  12710. #else
  12711. response.c_str(), response.size(),
  12712. #endif
  12713. 0);
  12714. detail::close_socket(cli);
  12715. }
  12716. detail::close_socket(srv);
  12717. });
  12718. }
  12719. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12720. #ifndef _WIN32
  12721. signal(SIGPIPE, SIG_IGN);
  12722. #endif
  12723. std::promise<int> port_promise;
  12724. auto port_future = port_promise.get_future();
  12725. auto server_thread =
  12726. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12727. "Content-Type: text/plain\r\n"
  12728. "Content-Length: not-a-number\r\n"
  12729. "Connection: close\r\n"
  12730. "\r\n"
  12731. "hello");
  12732. auto port = port_future.get();
  12733. ASSERT_GT(port, 0);
  12734. Client cli("127.0.0.1", port);
  12735. auto handle = cli.open_stream("GET", "/");
  12736. EXPECT_FALSE(handle.is_valid());
  12737. server_thread.join();
  12738. }
  12739. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12740. #ifndef _WIN32
  12741. signal(SIGPIPE, SIG_IGN);
  12742. #endif
  12743. std::promise<int> port_promise;
  12744. auto port_future = port_promise.get_future();
  12745. auto server_thread = serve_single_response(
  12746. port_promise, "HTTP/1.1 200 OK\r\n"
  12747. "Content-Type: text/plain\r\n"
  12748. "Content-Length: 99999999999999999999999999\r\n"
  12749. "Connection: close\r\n"
  12750. "\r\n"
  12751. "hello");
  12752. auto port = port_future.get();
  12753. ASSERT_GT(port, 0);
  12754. // Before the fix, std::stoull would throw std::out_of_range here and
  12755. // crash the process. After the fix, strtoull silently clamps to
  12756. // ULLONG_MAX so the stream opens without crashing. The important thing
  12757. // is that the process does NOT terminate.
  12758. Client cli("127.0.0.1", port);
  12759. auto handle = cli.open_stream("GET", "/");
  12760. EXPECT_TRUE(handle.is_valid());
  12761. server_thread.join();
  12762. }
  12763. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12764. TEST_F(OpenStreamTest, Gzip) {
  12765. Client cli("127.0.0.1", port_);
  12766. auto handle = cli.open_stream("GET", "/compressible", {},
  12767. {{"Accept-Encoding", "gzip"}});
  12768. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12769. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12770. }
  12771. #endif
  12772. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12773. TEST_F(OpenStreamTest, Brotli) {
  12774. Client cli("127.0.0.1", port_);
  12775. auto handle =
  12776. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12777. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12778. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12779. }
  12780. #endif
  12781. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12782. TEST_F(OpenStreamTest, Zstd) {
  12783. Client cli("127.0.0.1", port_);
  12784. auto handle = cli.open_stream("GET", "/compressible", {},
  12785. {{"Accept-Encoding", "zstd"}});
  12786. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12787. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12788. }
  12789. #endif
  12790. #ifdef CPPHTTPLIB_SSL_ENABLED
  12791. class SSLOpenStreamTest : public ::testing::Test {
  12792. protected:
  12793. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12794. void SetUp() override {
  12795. svr_.Get("/hello", [](const Request &, Response &res) {
  12796. res.set_content("Hello SSL World!", "text/plain");
  12797. });
  12798. svr_.Get("/chunked", [](const Request &, Response &res) {
  12799. res.set_chunked_content_provider("text/plain",
  12800. [](size_t offset, DataSink &sink) {
  12801. if (offset < 15) {
  12802. sink.write("chunk", 5);
  12803. return true;
  12804. }
  12805. sink.done();
  12806. return true;
  12807. });
  12808. });
  12809. svr_.Post("/echo", [](const Request &req, Response &res) {
  12810. res.set_content(req.body, req.get_header_value("Content-Type"));
  12811. });
  12812. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12813. std::string body = req.body;
  12814. res.set_chunked_content_provider(
  12815. "text/plain", [body](size_t offset, DataSink &sink) {
  12816. if (offset < body.size()) {
  12817. sink.write(body.data() + offset, body.size() - offset);
  12818. }
  12819. sink.done();
  12820. return true;
  12821. });
  12822. });
  12823. port_ = svr_.bind_to_any_port("127.0.0.1");
  12824. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12825. svr_.wait_until_ready();
  12826. }
  12827. void TearDown() override {
  12828. svr_.stop();
  12829. if (thread_.joinable()) thread_.join();
  12830. }
  12831. SSLServer svr_;
  12832. std::thread thread_;
  12833. int port_ = 0;
  12834. };
  12835. TEST_F(SSLOpenStreamTest, Basic) {
  12836. SSLClient cli("127.0.0.1", port_);
  12837. cli.enable_server_certificate_verification(false);
  12838. auto handle = cli.open_stream("GET", "/hello");
  12839. ASSERT_TRUE(handle.is_valid());
  12840. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12841. }
  12842. TEST_F(SSLOpenStreamTest, Chunked) {
  12843. SSLClient cli("127.0.0.1", port_);
  12844. cli.enable_server_certificate_verification(false);
  12845. auto handle = cli.open_stream("GET", "/chunked");
  12846. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12847. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12848. "Transfer-Encoding") == "chunked");
  12849. auto body = read_all(handle);
  12850. EXPECT_EQ("chunkchunkchunk", body);
  12851. }
  12852. TEST_F(SSLOpenStreamTest, Post) {
  12853. SSLClient cli("127.0.0.1", port_);
  12854. cli.enable_server_certificate_verification(false);
  12855. auto handle =
  12856. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12857. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12858. EXPECT_EQ(200, handle.response->status);
  12859. auto body = read_all(handle);
  12860. EXPECT_EQ("Hello SSL POST", body);
  12861. }
  12862. TEST_F(SSLOpenStreamTest, PostChunked) {
  12863. SSLClient cli("127.0.0.1", port_);
  12864. cli.enable_server_certificate_verification(false);
  12865. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12866. "Chunked SSL Data", "text/plain");
  12867. ASSERT_TRUE(handle.is_valid());
  12868. EXPECT_EQ(200, handle.response->status);
  12869. auto body = read_all(handle);
  12870. EXPECT_EQ("Chunked SSL Data", body);
  12871. }
  12872. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12873. // Content-Length is terminated by the server closing the connection. When the
  12874. // SSL peer sends a close_notify after the body, the client must treat it as a
  12875. // clean EOF and return a successful response rather than an error.
  12876. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12878. ASSERT_TRUE(svr.is_valid());
  12879. svr.set_keep_alive_max_count(1);
  12880. const std::string expected_body = "Hello from connection-close response!";
  12881. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12882. res.set_content_provider("text/plain",
  12883. [&](size_t offset, DataSink &sink) -> bool {
  12884. if (offset < expected_body.size()) {
  12885. sink.write(expected_body.data() + offset,
  12886. expected_body.size() - offset);
  12887. }
  12888. sink.done();
  12889. return true;
  12890. });
  12891. });
  12892. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12893. auto se = detail::scope_exit([&] {
  12894. svr.stop();
  12895. listen_thread.join();
  12896. ASSERT_FALSE(svr.is_running());
  12897. });
  12898. svr.wait_until_ready();
  12899. SSLClient cli(HOST, PORT);
  12900. cli.enable_server_certificate_verification(false);
  12901. auto res = cli.Get("/no-content-length");
  12902. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12903. EXPECT_EQ(StatusCode::OK_200, res->status);
  12904. EXPECT_EQ(expected_body, res->body);
  12905. }
  12906. #endif // CPPHTTPLIB_SSL_ENABLED
  12907. //==============================================================================
  12908. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12909. // results for various scenarios.
  12910. //==============================================================================
  12911. TEST(ParityTest, GetVsOpenStream) {
  12912. Server svr;
  12913. const std::string path = "/parity";
  12914. const std::string content = "Parity test content: hello world";
  12915. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12916. res.set_content(content, "text/plain");
  12917. });
  12918. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12919. auto se = detail::scope_exit([&] {
  12920. svr.stop();
  12921. t.join();
  12922. ASSERT_FALSE(svr.is_running());
  12923. });
  12924. svr.wait_until_ready();
  12925. Client cli(HOST, PORT);
  12926. // Non-stream path
  12927. auto r1 = cli.Get(path);
  12928. ASSERT_TRUE(r1);
  12929. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12930. // Stream path
  12931. auto h = cli.open_stream("GET", path);
  12932. ASSERT_TRUE(h.is_valid());
  12933. EXPECT_EQ(r1->body, read_all(h));
  12934. }
  12935. // Helper to compress data with provided compressor type T
  12936. template <typename Compressor>
  12937. static std::string compress_payload_for_parity(const std::string &in) {
  12938. std::string out;
  12939. Compressor compressor;
  12940. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12941. [&](const char *data, size_t n) {
  12942. out.append(data, n);
  12943. return true;
  12944. });
  12945. EXPECT_TRUE(ok);
  12946. return out;
  12947. }
  12948. // Helper function for compression parity tests
  12949. template <typename Compressor>
  12950. static void test_compression_parity(const std::string &original,
  12951. const std::string &path,
  12952. const std::string &encoding) {
  12953. const std::string compressed =
  12954. compress_payload_for_parity<Compressor>(original);
  12955. Server svr;
  12956. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12957. res.set_content(compressed, "application/octet-stream");
  12958. res.set_header("Content-Encoding", encoding);
  12959. });
  12960. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12961. auto se = detail::scope_exit([&] {
  12962. svr.stop();
  12963. t.join();
  12964. ASSERT_FALSE(svr.is_running());
  12965. });
  12966. svr.wait_until_ready();
  12967. Client cli(HOST, PORT);
  12968. // Non-streaming
  12969. {
  12970. auto res = cli.Get(path);
  12971. ASSERT_TRUE(res);
  12972. EXPECT_EQ(StatusCode::OK_200, res->status);
  12973. EXPECT_EQ(original, res->body);
  12974. }
  12975. // Streaming
  12976. {
  12977. auto h = cli.open_stream("GET", path);
  12978. ASSERT_TRUE(h.is_valid());
  12979. EXPECT_EQ(original, read_all(h));
  12980. }
  12981. }
  12982. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12983. TEST(ParityTest, Gzip) {
  12984. test_compression_parity<detail::gzip_compressor>(
  12985. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12986. }
  12987. #endif
  12988. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12989. TEST(ParityTest, Brotli) {
  12990. test_compression_parity<detail::brotli_compressor>(
  12991. "Hello, brotli parity test payload", "/parity-br", "br");
  12992. }
  12993. #endif
  12994. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12995. TEST(ParityTest, Zstd) {
  12996. test_compression_parity<detail::zstd_compressor>(
  12997. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12998. }
  12999. #endif
  13000. //==============================================================================
  13001. // New Stream API Tests
  13002. //==============================================================================
  13003. inline std::string read_body(httplib::stream::Result &result) {
  13004. std::string body;
  13005. while (result.next()) {
  13006. body.append(result.data(), result.size());
  13007. }
  13008. return body;
  13009. }
  13010. TEST(ClientConnectionTest, Basic) {
  13011. httplib::ClientConnection conn;
  13012. EXPECT_FALSE(conn.is_open());
  13013. conn.sock = 1;
  13014. EXPECT_TRUE(conn.is_open());
  13015. httplib::ClientConnection conn2(std::move(conn));
  13016. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13017. conn2.sock = INVALID_SOCKET;
  13018. }
  13019. // Unified test server for all stream::* tests
  13020. class StreamApiTest : public ::testing::Test {
  13021. protected:
  13022. void SetUp() override {
  13023. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13024. res.set_content("Hello World!", "text/plain");
  13025. });
  13026. svr_.Get("/echo-params",
  13027. [](const httplib::Request &req, httplib::Response &res) {
  13028. std::string r;
  13029. for (const auto &p : req.params) {
  13030. if (!r.empty()) r += "&";
  13031. r += p.first + "=" + p.second;
  13032. }
  13033. res.set_content(r, "text/plain");
  13034. });
  13035. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13036. res.set_content(req.body, req.get_header_value("Content-Type"));
  13037. });
  13038. svr_.Post("/echo-headers",
  13039. [](const httplib::Request &req, httplib::Response &res) {
  13040. std::string r;
  13041. for (const auto &h : req.headers)
  13042. r += h.first + ": " + h.second + "\n";
  13043. res.set_content(r, "text/plain");
  13044. });
  13045. svr_.Post("/echo-params",
  13046. [](const httplib::Request &req, httplib::Response &res) {
  13047. std::string r = "params:";
  13048. for (const auto &p : req.params)
  13049. r += p.first + "=" + p.second + ";";
  13050. res.set_content(r + " body:" + req.body, "text/plain");
  13051. });
  13052. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13053. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13054. });
  13055. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13056. res.set_content("PUT:" + req.body, "text/plain");
  13057. });
  13058. svr_.Patch("/echo",
  13059. [](const httplib::Request &req, httplib::Response &res) {
  13060. res.set_content("PATCH:" + req.body, "text/plain");
  13061. });
  13062. svr_.Delete(
  13063. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13064. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13065. "text/plain");
  13066. });
  13067. svr_.Get("/head-test",
  13068. [](const httplib::Request &, httplib::Response &res) {
  13069. res.set_content("body for HEAD", "text/plain");
  13070. });
  13071. svr_.Options("/options",
  13072. [](const httplib::Request &, httplib::Response &res) {
  13073. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13074. });
  13075. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13076. svr_.wait_until_ready();
  13077. }
  13078. void TearDown() override {
  13079. svr_.stop();
  13080. if (thread_.joinable()) thread_.join();
  13081. }
  13082. httplib::Server svr_;
  13083. std::thread thread_;
  13084. };
  13085. // stream::Get tests
  13086. TEST_F(StreamApiTest, GetBasic) {
  13087. httplib::Client cli(HOST, PORT);
  13088. auto result = httplib::stream::Get(cli, "/hello");
  13089. ASSERT_TRUE(result.is_valid());
  13090. EXPECT_EQ(200, result.status());
  13091. EXPECT_EQ("Hello World!", read_body(result));
  13092. }
  13093. TEST_F(StreamApiTest, GetWithParams) {
  13094. httplib::Client cli(HOST, PORT);
  13095. httplib::Params params{{"foo", "bar"}};
  13096. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13097. ASSERT_TRUE(result.is_valid());
  13098. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13099. }
  13100. TEST_F(StreamApiTest, GetConnectionError) {
  13101. httplib::Client cli(HOST, 9999);
  13102. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13103. }
  13104. TEST_F(StreamApiTest, Get404) {
  13105. httplib::Client cli(HOST, PORT);
  13106. auto result = httplib::stream::Get(cli, "/nonexistent");
  13107. EXPECT_TRUE(result.is_valid());
  13108. EXPECT_EQ(404, result.status());
  13109. }
  13110. // stream::Post tests
  13111. TEST_F(StreamApiTest, PostBasic) {
  13112. httplib::Client cli(HOST, PORT);
  13113. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13114. "application/json");
  13115. ASSERT_TRUE(result.is_valid());
  13116. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13117. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13118. }
  13119. TEST_F(StreamApiTest, PostWithHeaders) {
  13120. httplib::Client cli(HOST, PORT);
  13121. httplib::Headers headers{{"X-Custom", "value"}};
  13122. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13123. "text/plain");
  13124. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13125. }
  13126. TEST_F(StreamApiTest, PostWithParams) {
  13127. httplib::Client cli(HOST, PORT);
  13128. httplib::Params params{{"k", "v"}};
  13129. auto result =
  13130. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13131. auto body = read_body(result);
  13132. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13133. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13134. }
  13135. TEST_F(StreamApiTest, PostLarge) {
  13136. httplib::Client cli(HOST, PORT);
  13137. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13138. size_t total = 0;
  13139. while (result.next()) {
  13140. total += result.size();
  13141. }
  13142. EXPECT_EQ(100u * 1024u, total);
  13143. }
  13144. // stream::Put/Patch tests
  13145. TEST_F(StreamApiTest, PutAndPatch) {
  13146. httplib::Client cli(HOST, PORT);
  13147. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13148. EXPECT_EQ("PUT:test", read_body(put));
  13149. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13150. EXPECT_EQ("PATCH:test", read_body(patch));
  13151. }
  13152. // stream::Delete tests
  13153. TEST_F(StreamApiTest, Delete) {
  13154. httplib::Client cli(HOST, PORT);
  13155. auto del1 = httplib::stream::Delete(cli, "/resource");
  13156. EXPECT_EQ("Deleted", read_body(del1));
  13157. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13158. EXPECT_EQ("Deleted:data", read_body(del2));
  13159. }
  13160. // stream::Head/Options tests
  13161. TEST_F(StreamApiTest, HeadAndOptions) {
  13162. httplib::Client cli(HOST, PORT);
  13163. auto head = httplib::stream::Head(cli, "/head-test");
  13164. EXPECT_TRUE(head.is_valid());
  13165. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13166. auto opts = httplib::stream::Options(cli, "/options");
  13167. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13168. }
  13169. // SSL stream::* tests
  13170. #ifdef CPPHTTPLIB_SSL_ENABLED
  13171. class SSLStreamApiTest : public ::testing::Test {
  13172. protected:
  13173. void SetUp() override {
  13174. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13175. res.set_content("Hello SSL!", "text/plain");
  13176. });
  13177. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13178. res.set_content(req.body, "text/plain");
  13179. });
  13180. port_ = svr_.bind_to_any_port("127.0.0.1");
  13181. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13182. svr_.wait_until_ready();
  13183. }
  13184. void TearDown() override {
  13185. svr_.stop();
  13186. if (thread_.joinable()) thread_.join();
  13187. }
  13188. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13189. std::thread thread_;
  13190. int port_ = 0;
  13191. };
  13192. TEST_F(SSLStreamApiTest, GetAndPost) {
  13193. httplib::SSLClient cli("127.0.0.1", port_);
  13194. cli.enable_server_certificate_verification(false);
  13195. auto get = httplib::stream::Get(cli, "/hello");
  13196. EXPECT_EQ("Hello SSL!", read_body(get));
  13197. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13198. EXPECT_EQ("test", read_body(post));
  13199. }
  13200. #endif
  13201. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13202. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13203. // BodyReader
  13204. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13205. // Test that read timeout during streaming is detected
  13206. // Use a large content-length response where server delays mid-stream
  13207. Server svr;
  13208. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13209. // Send a large response with delay in the middle
  13210. res.set_content_provider(
  13211. 1000, // content_length
  13212. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13213. if (offset < 100) {
  13214. // Send first 100 bytes immediately
  13215. std::string data(100, 'A');
  13216. sink.write(data.c_str(), data.size());
  13217. return true;
  13218. }
  13219. // Then delay longer than client timeout
  13220. std::this_thread::sleep_for(std::chrono::seconds(3));
  13221. std::string data(900, 'B');
  13222. sink.write(data.c_str(), data.size());
  13223. return true;
  13224. });
  13225. });
  13226. auto port = 8091;
  13227. std::thread t([&]() { svr.listen("localhost", port); });
  13228. svr.wait_until_ready();
  13229. Client cli("localhost", port);
  13230. cli.set_read_timeout(1, 0); // 1 second timeout
  13231. auto handle = cli.open_stream("GET", "/slow-stream");
  13232. ASSERT_TRUE(handle.is_valid());
  13233. char buf[256];
  13234. ssize_t total = 0;
  13235. ssize_t n;
  13236. bool got_error = false;
  13237. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13238. total += n;
  13239. }
  13240. if (n < 0) {
  13241. got_error = true;
  13242. // Should be timeout or read error
  13243. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13244. handle.get_read_error() == Error::Read)
  13245. << "Actual error: " << to_string(handle.get_read_error());
  13246. }
  13247. // Either we got an error, or we got less data than expected
  13248. EXPECT_TRUE(got_error || total < 1000)
  13249. << "Expected timeout but got all " << total << " bytes";
  13250. svr.stop();
  13251. t.join();
  13252. }
  13253. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13254. // Test connection closed detection via BodyReader
  13255. Server svr;
  13256. std::atomic<bool> close_now{false};
  13257. svr.Get("/will-close", [&](const Request &, Response &res) {
  13258. res.set_content_provider(
  13259. 10000, // Large content_length that we won't fully send
  13260. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13261. if (offset < 100) {
  13262. std::string data(100, 'X');
  13263. sink.write(data.c_str(), data.size());
  13264. return true;
  13265. }
  13266. // Wait for signal then abort
  13267. while (!close_now) {
  13268. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13269. }
  13270. return false; // Abort - server will close connection
  13271. });
  13272. });
  13273. auto port = 8092;
  13274. std::thread t([&]() { svr.listen("localhost", port); });
  13275. svr.wait_until_ready();
  13276. Client cli("localhost", port);
  13277. auto handle = cli.open_stream("GET", "/will-close");
  13278. ASSERT_TRUE(handle.is_valid());
  13279. char buf[256];
  13280. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13281. EXPECT_GT(n, 0) << "First read should succeed";
  13282. // Signal server to close
  13283. close_now = true;
  13284. // Keep reading until error or EOF
  13285. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13286. // Keep reading
  13287. }
  13288. // Should get an error since content_length wasn't satisfied
  13289. if (n < 0) {
  13290. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13291. handle.get_read_error() == Error::Read)
  13292. << "Actual error: " << to_string(handle.get_read_error());
  13293. }
  13294. svr.stop();
  13295. t.join();
  13296. }
  13297. #ifdef CPPHTTPLIB_SSL_ENABLED
  13298. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13299. // Test that read timeout during SSL streaming is detected
  13300. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13301. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13302. res.set_content_provider(
  13303. 1000, "text/plain",
  13304. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13305. if (offset < 100) {
  13306. std::string data(100, 'A');
  13307. sink.write(data.c_str(), data.size());
  13308. return true;
  13309. }
  13310. std::this_thread::sleep_for(std::chrono::seconds(3));
  13311. std::string data(900, 'B');
  13312. sink.write(data.c_str(), data.size());
  13313. return true;
  13314. });
  13315. });
  13316. auto port = 8093;
  13317. std::thread t([&]() { svr.listen("localhost", port); });
  13318. svr.wait_until_ready();
  13319. SSLClient cli("localhost", port);
  13320. cli.enable_server_certificate_verification(false);
  13321. cli.set_read_timeout(1, 0); // 1 second timeout
  13322. auto handle = cli.open_stream("GET", "/slow-stream");
  13323. ASSERT_TRUE(handle.is_valid());
  13324. char buf[256];
  13325. ssize_t total = 0;
  13326. ssize_t n;
  13327. bool got_error = false;
  13328. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13329. total += n;
  13330. }
  13331. if (n < 0) {
  13332. got_error = true;
  13333. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13334. handle.get_read_error() == Error::Read)
  13335. << "Actual error: " << to_string(handle.get_read_error());
  13336. }
  13337. EXPECT_TRUE(got_error || total < 1000)
  13338. << "Expected timeout but got all " << total << " bytes";
  13339. svr.stop();
  13340. t.join();
  13341. }
  13342. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13343. // Test SSL connection closed detection
  13344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13345. std::atomic<bool> close_now{false};
  13346. svr.Get("/will-close", [&](const Request &, Response &res) {
  13347. res.set_content_provider(
  13348. 10000, "text/plain",
  13349. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13350. if (offset < 100) {
  13351. std::string data(100, 'X');
  13352. sink.write(data.c_str(), data.size());
  13353. return true;
  13354. }
  13355. while (!close_now) {
  13356. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13357. }
  13358. return false;
  13359. });
  13360. });
  13361. auto port = 8094;
  13362. std::thread t([&]() { svr.listen("localhost", port); });
  13363. svr.wait_until_ready();
  13364. SSLClient cli("localhost", port);
  13365. cli.enable_server_certificate_verification(false);
  13366. auto handle = cli.open_stream("GET", "/will-close");
  13367. ASSERT_TRUE(handle.is_valid());
  13368. char buf[256];
  13369. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13370. EXPECT_GT(n, 0);
  13371. // Signal server to close
  13372. close_now = true;
  13373. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13374. // Keep reading
  13375. }
  13376. if (n < 0) {
  13377. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13378. handle.get_read_error() == Error::Read)
  13379. << "Actual error: " << to_string(handle.get_read_error());
  13380. }
  13381. svr.stop();
  13382. t.join();
  13383. }
  13384. #endif
  13385. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13386. using namespace httplib;
  13387. // Create a test file
  13388. const char *fname = "etag_testfile.txt";
  13389. const char *content = "etag-content";
  13390. {
  13391. std::ofstream ofs(fname);
  13392. ofs << content;
  13393. ASSERT_TRUE(ofs.good());
  13394. }
  13395. Server svr;
  13396. svr.set_mount_point("/static", ".");
  13397. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13398. svr.wait_until_ready();
  13399. Client cli(HOST, PORT);
  13400. // First request: should get 200 with ETag header
  13401. auto res1 = cli.Get("/static/etag_testfile.txt");
  13402. ASSERT_TRUE(res1);
  13403. ASSERT_EQ(200, res1->status);
  13404. ASSERT_TRUE(res1->has_header("ETag"));
  13405. std::string etag = res1->get_header_value("ETag");
  13406. EXPECT_FALSE(etag.empty());
  13407. // Verify ETag format: W/"hex-hex"
  13408. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13409. EXPECT_EQ('W', etag[0]);
  13410. EXPECT_EQ('/', etag[1]);
  13411. EXPECT_EQ('"', etag[2]);
  13412. EXPECT_EQ('"', etag.back());
  13413. // Exact match: expect 304 Not Modified
  13414. Headers h2 = {{"If-None-Match", etag}};
  13415. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13416. ASSERT_TRUE(res2);
  13417. EXPECT_EQ(304, res2->status);
  13418. // Wildcard match: expect 304 Not Modified
  13419. Headers h3 = {{"If-None-Match", "*"}};
  13420. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13421. ASSERT_TRUE(res3);
  13422. EXPECT_EQ(304, res3->status);
  13423. // Non-matching ETag: expect 200
  13424. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13425. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13426. ASSERT_TRUE(res4);
  13427. EXPECT_EQ(200, res4->status);
  13428. // Multiple ETags with one matching: expect 304
  13429. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13430. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13431. ASSERT_TRUE(res5);
  13432. EXPECT_EQ(304, res5->status);
  13433. svr.stop();
  13434. t.join();
  13435. std::remove(fname);
  13436. }
  13437. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13438. using namespace httplib;
  13439. Server svr;
  13440. svr.set_mount_point("/static", ".");
  13441. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13442. svr.wait_until_ready();
  13443. Client cli(HOST, PORT);
  13444. // Send If-None-Match: * to a non-existent file
  13445. Headers h = {{"If-None-Match", "*"}};
  13446. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13447. ASSERT_TRUE(res);
  13448. EXPECT_EQ(404, res->status);
  13449. svr.stop();
  13450. t.join();
  13451. }
  13452. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13453. using namespace httplib;
  13454. // Create a test file
  13455. const char *fname = "etag_boundary_testfile.txt";
  13456. const char *content = "boundary-test";
  13457. {
  13458. std::ofstream ofs(fname);
  13459. ofs << content;
  13460. ASSERT_TRUE(ofs.good());
  13461. }
  13462. Server svr;
  13463. svr.set_mount_point("/static", ".");
  13464. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13465. svr.wait_until_ready();
  13466. Client cli(HOST, PORT);
  13467. // Get the actual ETag
  13468. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13469. ASSERT_TRUE(res1);
  13470. ASSERT_EQ(200, res1->status);
  13471. ASSERT_TRUE(res1->has_header("ETag"));
  13472. std::string etag = res1->get_header_value("ETag");
  13473. // Test 1: Very long ETag value (longer than actual ETag)
  13474. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13475. Headers h1 = {{"If-None-Match", "W/"
  13476. "\"very-long-etag-value-that-is-much-longer-"
  13477. "than-the-actual-etag-value\""}};
  13478. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13479. ASSERT_TRUE(res2);
  13480. EXPECT_EQ(200, res2->status); // Should not match
  13481. // Test 2: Long string followed by wildcard
  13482. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13483. // string)
  13484. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13485. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13486. ASSERT_TRUE(res3);
  13487. EXPECT_EQ(304, res3->status); // Should match on "*"
  13488. // Test 3: Wildcard followed by long string
  13489. // Should match on "*" immediately and return 304
  13490. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13491. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13492. ASSERT_TRUE(res4);
  13493. EXPECT_EQ(304, res4->status); // Should match on "*"
  13494. // Test 4: Multiple long non-matching values
  13495. // Should NOT match and return 200 (test that all comparisons are safe)
  13496. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13497. "W/\"second-long-non-matching-value\", "
  13498. "W/\"third-long-non-matching-value\""}};
  13499. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13500. ASSERT_TRUE(res5);
  13501. EXPECT_EQ(200, res5->status); // Should not match
  13502. // Test 5: Single character that is not "*" (edge case)
  13503. Headers h5 = {{"If-None-Match", "X"}};
  13504. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13505. ASSERT_TRUE(res6);
  13506. EXPECT_EQ(200, res6->status); // Should not match
  13507. svr.stop();
  13508. t.join();
  13509. std::remove(fname);
  13510. }
  13511. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13512. using namespace httplib;
  13513. // Create a test file
  13514. const char *fname = "ims_testfile.txt";
  13515. const char *content = "if-modified-since-test";
  13516. {
  13517. std::ofstream ofs(fname);
  13518. ofs << content;
  13519. ASSERT_TRUE(ofs.good());
  13520. }
  13521. Server svr;
  13522. svr.set_mount_point("/static", ".");
  13523. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13524. svr.wait_until_ready();
  13525. Client cli(HOST, PORT);
  13526. // First request: should get 200 with Last-Modified header
  13527. auto res1 = cli.Get("/static/ims_testfile.txt");
  13528. ASSERT_TRUE(res1);
  13529. ASSERT_EQ(200, res1->status);
  13530. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13531. std::string last_modified = res1->get_header_value("Last-Modified");
  13532. EXPECT_FALSE(last_modified.empty());
  13533. // If-Modified-Since with same time: expect 304
  13534. Headers h2 = {{"If-Modified-Since", last_modified}};
  13535. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13536. ASSERT_TRUE(res2);
  13537. EXPECT_EQ(304, res2->status);
  13538. // If-Modified-Since with future time: expect 304
  13539. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13540. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13541. ASSERT_TRUE(res3);
  13542. EXPECT_EQ(304, res3->status);
  13543. // If-Modified-Since with past time: expect 200
  13544. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13545. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13546. ASSERT_TRUE(res4);
  13547. EXPECT_EQ(200, res4->status);
  13548. // If-None-Match takes precedence over If-Modified-Since
  13549. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13550. ASSERT_TRUE(res1->has_header("ETag"));
  13551. std::string etag = res1->get_header_value("ETag");
  13552. Headers h5 = {{"If-None-Match", etag},
  13553. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13554. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13555. ASSERT_TRUE(res5);
  13556. EXPECT_EQ(304, res5->status);
  13557. svr.stop();
  13558. t.join();
  13559. std::remove(fname);
  13560. }
  13561. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13562. using namespace httplib;
  13563. Server svr;
  13564. // Endpoint that returns compressible content
  13565. svr.Get("/compressible", [](const Request &, Response &res) {
  13566. // Return a large enough body to trigger compression
  13567. std::string body(1000, 'a');
  13568. res.set_content(body, "text/plain");
  13569. });
  13570. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13571. svr.wait_until_ready();
  13572. Client cli(HOST, PORT);
  13573. // Request with gzip support: should get Vary header when compressed
  13574. cli.set_compress(true);
  13575. auto res1 = cli.Get("/compressible");
  13576. ASSERT_TRUE(res1);
  13577. EXPECT_EQ(200, res1->status);
  13578. // If Content-Encoding is set, Vary should also be set
  13579. if (res1->has_header("Content-Encoding")) {
  13580. EXPECT_TRUE(res1->has_header("Vary"));
  13581. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13582. }
  13583. // Request without Accept-Encoding header: should not have compression
  13584. Headers h_no_compress;
  13585. auto res2 = cli.Get("/compressible", h_no_compress);
  13586. ASSERT_TRUE(res2);
  13587. EXPECT_EQ(200, res2->status);
  13588. // Verify Vary header is present when compression is applied
  13589. // (the exact behavior depends on server configuration)
  13590. svr.stop();
  13591. t.join();
  13592. }
  13593. TEST(ETagTest, IfRangeWithETag) {
  13594. using namespace httplib;
  13595. // Create a test file with known content
  13596. const char *fname = "if_range_testfile.txt";
  13597. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13598. {
  13599. std::ofstream ofs(fname);
  13600. ofs << content;
  13601. ASSERT_TRUE(ofs.good());
  13602. }
  13603. Server svr;
  13604. svr.set_mount_point("/static", ".");
  13605. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13606. svr.wait_until_ready();
  13607. Client cli(HOST, PORT);
  13608. // First request: get ETag
  13609. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13610. ASSERT_TRUE(res1);
  13611. ASSERT_EQ(200, res1->status);
  13612. ASSERT_TRUE(res1->has_header("ETag"));
  13613. std::string etag = res1->get_header_value("ETag");
  13614. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13615. // Since our server generates weak ETags (W/"..."), If-Range with our
  13616. // ETag should NOT result in partial content - it should return full content.
  13617. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13618. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13619. ASSERT_TRUE(res2);
  13620. // Weak ETag in If-Range -> full content (200), not partial (206)
  13621. EXPECT_EQ(200, res2->status);
  13622. EXPECT_EQ(content, res2->body);
  13623. EXPECT_FALSE(res2->has_header("Content-Range"));
  13624. // Range request with non-matching If-Range (ETag): should get 200 (full
  13625. // content)
  13626. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13627. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13628. ASSERT_TRUE(res3);
  13629. EXPECT_EQ(200, res3->status);
  13630. EXPECT_EQ(content, res3->body);
  13631. EXPECT_FALSE(res3->has_header("Content-Range"));
  13632. // Range request with strong ETag (hypothetical - our server doesn't generate
  13633. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13634. // should return full content)
  13635. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13636. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13637. ASSERT_TRUE(res4);
  13638. EXPECT_EQ(200, res4->status);
  13639. EXPECT_EQ(content, res4->body);
  13640. EXPECT_FALSE(res4->has_header("Content-Range"));
  13641. svr.stop();
  13642. t.join();
  13643. std::remove(fname);
  13644. }
  13645. TEST(ETagTest, IfRangeWithDate) {
  13646. using namespace httplib;
  13647. // Create a test file
  13648. const char *fname = "if_range_date_testfile.txt";
  13649. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13650. {
  13651. std::ofstream ofs(fname);
  13652. ofs << content;
  13653. ASSERT_TRUE(ofs.good());
  13654. }
  13655. Server svr;
  13656. svr.set_mount_point("/static", ".");
  13657. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13658. svr.wait_until_ready();
  13659. Client cli(HOST, PORT);
  13660. // First request: get Last-Modified
  13661. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13662. ASSERT_TRUE(res1);
  13663. ASSERT_EQ(200, res1->status);
  13664. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13665. std::string last_modified = res1->get_header_value("Last-Modified");
  13666. // Range request with matching If-Range (date): should get 206
  13667. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13668. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13669. ASSERT_TRUE(res2);
  13670. EXPECT_EQ(206, res2->status);
  13671. EXPECT_EQ("FGHIJ", res2->body);
  13672. // Range request with old If-Range date: should get 200 (full content)
  13673. Headers h3 = {{"Range", "bytes=5-9"},
  13674. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13675. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13676. ASSERT_TRUE(res3);
  13677. EXPECT_EQ(200, res3->status);
  13678. EXPECT_EQ(content, res3->body);
  13679. // Range request with future If-Range date: should get 206
  13680. Headers h4 = {{"Range", "bytes=0-4"},
  13681. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13682. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13683. ASSERT_TRUE(res4);
  13684. EXPECT_EQ(206, res4->status);
  13685. EXPECT_EQ("ABCDE", res4->body);
  13686. svr.stop();
  13687. t.join();
  13688. std::remove(fname);
  13689. }
  13690. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13691. using namespace httplib;
  13692. const char *fname = "etag_malformed.txt";
  13693. const char *content = "malformed-etag";
  13694. {
  13695. std::ofstream ofs(fname);
  13696. ofs << content;
  13697. ASSERT_TRUE(ofs.good());
  13698. }
  13699. Server svr;
  13700. svr.set_mount_point("/static", ".");
  13701. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13702. svr.wait_until_ready();
  13703. Client cli(HOST, PORT);
  13704. // baseline: should get 200 and an ETag
  13705. auto res1 = cli.Get("/static/etag_malformed.txt");
  13706. ASSERT_TRUE(res1);
  13707. ASSERT_EQ(200, res1->status);
  13708. ASSERT_TRUE(res1->has_header("ETag"));
  13709. // Malformed ETag value (missing quotes) should be treated as non-matching
  13710. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13711. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13712. ASSERT_TRUE(res_bad);
  13713. EXPECT_EQ(200, res_bad->status);
  13714. // Whitespace-only header value should be considered invalid / non-matching
  13715. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13716. "Host: localhost\r\n"
  13717. "If-None-Match: \r\n"
  13718. "Connection: close\r\n"
  13719. "\r\n";
  13720. std::string out;
  13721. ASSERT_TRUE(send_request(5, raw_req, &out));
  13722. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13723. svr.stop();
  13724. t.join();
  13725. std::remove(fname);
  13726. }
  13727. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13728. using namespace httplib;
  13729. const char *fname = "ims_invalid_format.txt";
  13730. const char *content = "ims-bad-format";
  13731. {
  13732. std::ofstream ofs(fname);
  13733. ofs << content;
  13734. ASSERT_TRUE(ofs.good());
  13735. }
  13736. Server svr;
  13737. svr.set_mount_point("/static", ".");
  13738. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13739. svr.wait_until_ready();
  13740. Client cli(HOST, PORT);
  13741. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13742. ASSERT_TRUE(res1);
  13743. ASSERT_EQ(200, res1->status);
  13744. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13745. // If-Modified-Since with invalid format should not result in 304
  13746. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13747. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13748. ASSERT_TRUE(res_bad);
  13749. EXPECT_EQ(200, res_bad->status);
  13750. // If-Range with invalid date format should be treated as mismatch -> full
  13751. // content (200)
  13752. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13753. {"If-Range", "invalid-date"}};
  13754. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13755. ASSERT_TRUE(res_ifrange);
  13756. EXPECT_EQ(200, res_ifrange->status);
  13757. svr.stop();
  13758. t.join();
  13759. std::remove(fname);
  13760. }
  13761. TEST(ETagTest, IfRangeWithMalformedETag) {
  13762. using namespace httplib;
  13763. const char *fname = "ifrange_malformed.txt";
  13764. const std::string content = "0123456789";
  13765. {
  13766. std::ofstream ofs(fname);
  13767. ofs << content;
  13768. ASSERT_TRUE(ofs.good());
  13769. }
  13770. Server svr;
  13771. svr.set_mount_point("/static", ".");
  13772. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13773. svr.wait_until_ready();
  13774. Client cli(HOST, PORT);
  13775. // First request: get ETag
  13776. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13777. ASSERT_TRUE(res1);
  13778. ASSERT_EQ(200, res1->status);
  13779. ASSERT_TRUE(res1->has_header("ETag"));
  13780. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13781. // full content (200)
  13782. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13783. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13784. ASSERT_TRUE(res2);
  13785. EXPECT_EQ(200, res2->status);
  13786. EXPECT_EQ(content, res2->body);
  13787. svr.stop();
  13788. t.join();
  13789. std::remove(fname);
  13790. }
  13791. TEST(ETagTest, ExtremeLargeDateValues) {
  13792. using namespace httplib;
  13793. const char *fname = "ims_extreme_date.txt";
  13794. const char *content = "ims-extreme-date";
  13795. {
  13796. std::ofstream ofs(fname);
  13797. ofs << content;
  13798. ASSERT_TRUE(ofs.good());
  13799. }
  13800. Server svr;
  13801. svr.set_mount_point("/static", ".");
  13802. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13803. svr.wait_until_ready();
  13804. Client cli(HOST, PORT);
  13805. auto res1 = cli.Get(std::string("/static/") + fname);
  13806. ASSERT_TRUE(res1);
  13807. ASSERT_EQ(200, res1->status);
  13808. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13809. // Extremely large year that may overflow date parsing routines.
  13810. Headers h_large_date = {
  13811. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13812. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13813. ASSERT_TRUE(res_bad);
  13814. // Expect server to treat this as invalid/mismatch and return full content
  13815. EXPECT_EQ(200, res_bad->status);
  13816. // If-Range with extremely large date should be treated as mismatch -> full
  13817. // content (200)
  13818. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13819. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13820. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13821. ASSERT_TRUE(res_ifrange);
  13822. EXPECT_EQ(200, res_ifrange->status);
  13823. svr.stop();
  13824. t.join();
  13825. std::remove(fname);
  13826. }
  13827. TEST(ETagTest, NegativeFileModificationTime) {
  13828. using namespace httplib;
  13829. const char *fname = "ims_negative_mtime.txt";
  13830. const std::string content = "negative-mtime";
  13831. {
  13832. std::ofstream ofs(fname);
  13833. ofs << content;
  13834. ASSERT_TRUE(ofs.good());
  13835. }
  13836. // Try to set file mtime to a negative value. This may fail on some
  13837. // platforms/filesystems; if it fails, the test will still verify server
  13838. // behaves safely by performing a regular conditional request.
  13839. #if defined(__APPLE__) || defined(__linux__)
  13840. bool set_negative = false;
  13841. do {
  13842. struct timeval times[2];
  13843. // access time: now
  13844. times[0].tv_sec = time(nullptr);
  13845. times[0].tv_usec = 0;
  13846. // modification time: negative (e.g., -1)
  13847. times[1].tv_sec = -1;
  13848. times[1].tv_usec = 0;
  13849. if (utimes(fname, times) == 0) { set_negative = true; }
  13850. } while (0);
  13851. #else
  13852. bool set_negative = false;
  13853. #endif
  13854. Server svr;
  13855. svr.set_mount_point("/static", ".");
  13856. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13857. svr.wait_until_ready();
  13858. Client cli(HOST, PORT);
  13859. auto res1 = cli.Get(std::string("/static/") + fname);
  13860. ASSERT_TRUE(res1);
  13861. ASSERT_EQ(200, res1->status);
  13862. bool has_last_modified = res1->has_header("Last-Modified");
  13863. std::string last_modified;
  13864. if (has_last_modified) {
  13865. last_modified = res1->get_header_value("Last-Modified");
  13866. }
  13867. if (set_negative) {
  13868. // If we successfully set a negative mtime, ensure server returns a
  13869. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13870. // with an old date and ensure server handles it without crash.
  13871. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13872. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13873. ASSERT_TRUE(res2);
  13874. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13875. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13876. } else {
  13877. // Could not set negative mtime on this platform; fall back to verifying
  13878. // that normal invalid/malformed dates are treated safely (non-304).
  13879. Headers h_bad_date = {
  13880. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13881. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13882. ASSERT_TRUE(res_bad);
  13883. EXPECT_EQ(200, res_bad->status);
  13884. }
  13885. svr.stop();
  13886. t.join();
  13887. std::remove(fname);
  13888. }
  13889. //==============================================================================
  13890. // SSE Parsing Tests
  13891. //==============================================================================
  13892. class SSEParsingTest : public ::testing::Test {
  13893. protected:
  13894. // Test helper that mimics SSE parsing behavior
  13895. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13896. int &retry_ms) {
  13897. // Blank line signals end of event
  13898. if (line.empty() || line == "\r") { return true; }
  13899. // Lines starting with ':' are comments (ignored)
  13900. if (!line.empty() && line[0] == ':') { return false; }
  13901. // Find the colon separator
  13902. auto colon_pos = line.find(':');
  13903. if (colon_pos == std::string::npos) {
  13904. // Line with no colon is treated as field name with empty value
  13905. return false;
  13906. }
  13907. std::string field = line.substr(0, colon_pos);
  13908. std::string value;
  13909. // Value starts after colon, skip optional single space
  13910. if (colon_pos + 1 < line.size()) {
  13911. size_t value_start = colon_pos + 1;
  13912. if (line[value_start] == ' ') { value_start++; }
  13913. value = line.substr(value_start);
  13914. // Remove trailing \r if present
  13915. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13916. }
  13917. // Handle known fields
  13918. if (field == "event") {
  13919. msg.event = value;
  13920. } else if (field == "data") {
  13921. // Multiple data lines are concatenated with newlines
  13922. if (!msg.data.empty()) { msg.data += "\n"; }
  13923. msg.data += value;
  13924. } else if (field == "id") {
  13925. // Empty id is valid (clears the last event ID)
  13926. msg.id = value;
  13927. } else if (field == "retry") {
  13928. // Parse retry interval in milliseconds
  13929. {
  13930. int v = 0;
  13931. auto res =
  13932. detail::from_chars(value.data(), value.data() + value.size(), v);
  13933. if (res.ec == std::errc{}) { retry_ms = v; }
  13934. }
  13935. }
  13936. // Unknown fields are ignored per SSE spec
  13937. return false;
  13938. }
  13939. };
  13940. // Test: Single-line data
  13941. TEST_F(SSEParsingTest, SingleLineData) {
  13942. sse::SSEMessage msg;
  13943. int retry_ms = 3000;
  13944. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13945. EXPECT_EQ(msg.data, "hello");
  13946. EXPECT_EQ(msg.event, "message");
  13947. // Blank line ends event
  13948. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13949. }
  13950. // Test: Multi-line data
  13951. TEST_F(SSEParsingTest, MultiLineData) {
  13952. sse::SSEMessage msg;
  13953. int retry_ms = 3000;
  13954. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13955. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13956. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13957. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13958. }
  13959. // Test: Custom event types
  13960. TEST_F(SSEParsingTest, CustomEventType) {
  13961. sse::SSEMessage msg;
  13962. int retry_ms = 3000;
  13963. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13964. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13965. EXPECT_EQ(msg.event, "update");
  13966. EXPECT_EQ(msg.data, "payload");
  13967. }
  13968. // Test: Event ID handling
  13969. TEST_F(SSEParsingTest, EventIdHandling) {
  13970. sse::SSEMessage msg;
  13971. int retry_ms = 3000;
  13972. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13973. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13974. EXPECT_EQ(msg.id, "12345");
  13975. }
  13976. // Test: Empty event ID (clears last event ID)
  13977. TEST_F(SSEParsingTest, EmptyEventId) {
  13978. sse::SSEMessage msg;
  13979. msg.id = "previous";
  13980. int retry_ms = 3000;
  13981. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13982. EXPECT_EQ(msg.id, "");
  13983. }
  13984. // Test: Retry field parsing
  13985. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13986. sse::SSEMessage msg;
  13987. int retry_ms = 3000;
  13988. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13989. EXPECT_EQ(retry_ms, 5000);
  13990. }
  13991. // Test: Invalid retry value
  13992. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13993. sse::SSEMessage msg;
  13994. int retry_ms = 3000;
  13995. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13996. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13997. }
  13998. // Test: Comments (lines starting with :)
  13999. TEST_F(SSEParsingTest, CommentsIgnored) {
  14000. sse::SSEMessage msg;
  14001. int retry_ms = 3000;
  14002. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14003. EXPECT_EQ(msg.data, "");
  14004. EXPECT_EQ(msg.event, "message");
  14005. }
  14006. // Test: Colon in value
  14007. TEST_F(SSEParsingTest, ColonInValue) {
  14008. sse::SSEMessage msg;
  14009. int retry_ms = 3000;
  14010. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14011. EXPECT_EQ(msg.data, "hello:world:test");
  14012. }
  14013. // Test: Line with no colon (field name only)
  14014. TEST_F(SSEParsingTest, FieldNameOnly) {
  14015. sse::SSEMessage msg;
  14016. int retry_ms = 3000;
  14017. // According to SSE spec, this is treated as field name with empty value
  14018. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14019. // Since we don't recognize "data" without colon, data should be empty
  14020. EXPECT_EQ(msg.data, "");
  14021. }
  14022. // Test: Trailing \r handling
  14023. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14024. sse::SSEMessage msg;
  14025. int retry_ms = 3000;
  14026. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14027. EXPECT_EQ(msg.data, "hello");
  14028. }
  14029. // Test: Unknown fields ignored
  14030. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14031. sse::SSEMessage msg;
  14032. int retry_ms = 3000;
  14033. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14034. EXPECT_EQ(msg.data, "");
  14035. EXPECT_EQ(msg.event, "message");
  14036. }
  14037. // Test: Space after colon is optional
  14038. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14039. sse::SSEMessage msg1, msg2;
  14040. int retry_ms = 3000;
  14041. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14042. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14043. EXPECT_EQ(msg1.data, "hello");
  14044. EXPECT_EQ(msg2.data, "hello");
  14045. }
  14046. // Test: SSEMessage clear
  14047. TEST_F(SSEParsingTest, MessageClear) {
  14048. sse::SSEMessage msg;
  14049. msg.event = "custom";
  14050. msg.data = "some data";
  14051. msg.id = "123";
  14052. msg.clear();
  14053. EXPECT_EQ(msg.event, "message");
  14054. EXPECT_EQ(msg.data, "");
  14055. EXPECT_EQ(msg.id, "");
  14056. }
  14057. // Test: Complete event parsing
  14058. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14059. sse::SSEMessage msg;
  14060. int retry_ms = 3000;
  14061. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14062. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14063. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14064. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14065. // Blank line ends event
  14066. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14067. EXPECT_EQ(msg.event, "notification");
  14068. EXPECT_EQ(msg.id, "evt-42");
  14069. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14070. EXPECT_EQ(retry_ms, 1000);
  14071. }
  14072. //==============================================================================
  14073. // Integration Tests with Server
  14074. //==============================================================================
  14075. class SSEIntegrationTest : public ::testing::Test {
  14076. protected:
  14077. void SetUp() override {
  14078. stop_server_.store(false);
  14079. events_.clear();
  14080. server_ = httplib::detail::make_unique<Server>();
  14081. setup_server();
  14082. start_server();
  14083. }
  14084. void TearDown() override {
  14085. stop_server_.store(true);
  14086. event_cv_.notify_all();
  14087. server_->stop();
  14088. if (server_thread_.joinable()) { server_thread_.join(); }
  14089. }
  14090. void setup_server() {
  14091. // Simple SSE endpoint
  14092. server_->Get("/events", [this](const Request &req, Response &res) {
  14093. auto last_id = req.get_header_value("Last-Event-ID");
  14094. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14095. res.set_chunked_content_provider(
  14096. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14097. std::unique_lock<std::mutex> lock(event_mutex_);
  14098. if (event_cv_.wait_for(
  14099. lock, std::chrono::milliseconds(200), [this] {
  14100. return !events_.empty() || stop_server_.load();
  14101. })) {
  14102. if (stop_server_.load()) { return false; }
  14103. if (!events_.empty()) {
  14104. std::string event = events_.front();
  14105. events_.erase(events_.begin());
  14106. sink.write(event.data(), event.size());
  14107. return true;
  14108. }
  14109. }
  14110. return !stop_server_.load();
  14111. });
  14112. });
  14113. // Endpoint that returns error
  14114. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14115. res.status = 500;
  14116. res.set_content("Internal Server Error", "text/plain");
  14117. });
  14118. // Endpoint for custom event types
  14119. server_->Get("/custom-events", [](const Request &, Response &res) {
  14120. res.set_chunked_content_provider(
  14121. "text/event-stream", [](size_t offset, DataSink &sink) {
  14122. if (offset == 0) {
  14123. std::string event = "event: update\ndata: updated\n\n"
  14124. "event: delete\ndata: deleted\n\n";
  14125. sink.write(event.data(), event.size());
  14126. }
  14127. return false; // End stream after sending
  14128. });
  14129. });
  14130. }
  14131. void start_server() {
  14132. port_ = server_->bind_to_any_port(HOST);
  14133. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14134. // Wait for server to start
  14135. while (!server_->is_running()) {
  14136. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14137. }
  14138. }
  14139. int get_port() const { return port_; }
  14140. void send_event(const std::string &event) {
  14141. std::lock_guard<std::mutex> lock(event_mutex_);
  14142. events_.push_back(event);
  14143. event_cv_.notify_all();
  14144. }
  14145. std::unique_ptr<Server> server_;
  14146. std::thread server_thread_;
  14147. std::mutex event_mutex_;
  14148. std::condition_variable event_cv_;
  14149. std::vector<std::string> events_;
  14150. std::atomic<bool> stop_server_{false};
  14151. std::string last_received_event_id_;
  14152. int port_ = 0;
  14153. };
  14154. // Test: Successful connection and on_open callback
  14155. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14156. // Add a simple endpoint that sends one event and closes
  14157. server_->Get("/simple-event", [](const Request &, Response &res) {
  14158. res.set_chunked_content_provider(
  14159. "text/event-stream", [](size_t offset, DataSink &sink) {
  14160. if (offset == 0) {
  14161. std::string event = "data: hello\n\n";
  14162. sink.write(event.data(), event.size());
  14163. }
  14164. return false; // Close stream after sending
  14165. });
  14166. });
  14167. Client client("localhost", get_port());
  14168. sse::SSEClient sse(client, "/simple-event");
  14169. std::atomic<bool> open_called{false};
  14170. std::atomic<bool> message_received{false};
  14171. sse.on_open([&open_called]() { open_called.store(true); });
  14172. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14173. if (msg.data == "hello") { message_received.store(true); }
  14174. });
  14175. sse.set_reconnect_interval(100);
  14176. sse.set_max_reconnect_attempts(1);
  14177. // Start async
  14178. sse.start_async();
  14179. // Wait for message to be processed
  14180. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14181. sse.stop();
  14182. EXPECT_TRUE(open_called.load());
  14183. EXPECT_TRUE(message_received.load());
  14184. }
  14185. // Test: on_message callback
  14186. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14187. // Endpoint that sends multiple events then closes
  14188. server_->Get("/multi-event", [](const Request &, Response &res) {
  14189. res.set_chunked_content_provider(
  14190. "text/event-stream", [](size_t offset, DataSink &sink) {
  14191. if (offset == 0) {
  14192. std::string events = "data: message1\n\ndata: message2\n\n";
  14193. sink.write(events.data(), events.size());
  14194. }
  14195. return false;
  14196. });
  14197. });
  14198. Client client("localhost", get_port());
  14199. sse::SSEClient sse(client, "/multi-event");
  14200. std::vector<std::string> received_messages;
  14201. std::mutex messages_mutex;
  14202. sse.on_message([&](const sse::SSEMessage &msg) {
  14203. std::lock_guard<std::mutex> lock(messages_mutex);
  14204. received_messages.push_back(msg.data);
  14205. });
  14206. sse.set_reconnect_interval(100);
  14207. sse.set_max_reconnect_attempts(1);
  14208. sse.start_async();
  14209. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14210. sse.stop();
  14211. std::lock_guard<std::mutex> lock(messages_mutex);
  14212. EXPECT_GE(received_messages.size(), 2u);
  14213. if (received_messages.size() >= 2) {
  14214. EXPECT_EQ(received_messages[0], "message1");
  14215. EXPECT_EQ(received_messages[1], "message2");
  14216. }
  14217. }
  14218. // Test: on_event for specific types
  14219. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14220. Client client("localhost", get_port());
  14221. sse::SSEClient sse(client, "/custom-events");
  14222. std::atomic<bool> update_received{false};
  14223. std::atomic<bool> delete_received{false};
  14224. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14225. if (msg.data == "updated") { update_received.store(true); }
  14226. });
  14227. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14228. if (msg.data == "deleted") { delete_received.store(true); }
  14229. });
  14230. sse.set_max_reconnect_attempts(1);
  14231. sse.start_async();
  14232. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14233. sse.stop();
  14234. EXPECT_TRUE(update_received.load());
  14235. EXPECT_TRUE(delete_received.load());
  14236. }
  14237. // Test: on_error callback on connection failure
  14238. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14239. // Connect to a non-existent port
  14240. Client client("localhost", 59999);
  14241. sse::SSEClient sse(client, "/events");
  14242. std::atomic<bool> error_called{false};
  14243. Error received_error = Error::Success;
  14244. sse.on_error([&](Error err) {
  14245. error_called.store(true);
  14246. received_error = err;
  14247. });
  14248. sse.set_reconnect_interval(50);
  14249. sse.set_max_reconnect_attempts(1);
  14250. sse.start_async();
  14251. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14252. sse.stop();
  14253. EXPECT_TRUE(error_called.load());
  14254. EXPECT_NE(received_error, Error::Success);
  14255. }
  14256. // Test: Last-Event-ID header sent on reconnect
  14257. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14258. // Endpoint that sends event with ID
  14259. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14260. res.set_chunked_content_provider(
  14261. "text/event-stream", [](size_t offset, DataSink &sink) {
  14262. if (offset == 0) {
  14263. std::string event = "id: evt-123\ndata: test\n\n";
  14264. sink.write(event.data(), event.size());
  14265. }
  14266. return false;
  14267. });
  14268. });
  14269. Client client("localhost", get_port());
  14270. sse::SSEClient sse(client, "/event-with-id");
  14271. std::atomic<bool> id_received{false};
  14272. sse.on_message([&](const sse::SSEMessage &msg) {
  14273. if (!msg.id.empty()) { id_received.store(true); }
  14274. });
  14275. sse.set_reconnect_interval(100);
  14276. sse.set_max_reconnect_attempts(1);
  14277. sse.start_async();
  14278. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14279. sse.stop();
  14280. EXPECT_TRUE(id_received.load());
  14281. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14282. }
  14283. // Test: Manual stop
  14284. TEST_F(SSEIntegrationTest, ManualStop) {
  14285. // Endpoint that sends one event and stays open briefly
  14286. std::atomic<bool> handler_running{true};
  14287. server_->Get("/stay-open", [&handler_running](const Request &,
  14288. Response &res) {
  14289. res.set_chunked_content_provider(
  14290. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14291. if (offset == 0) {
  14292. std::string event = "data: connected\n\n";
  14293. sink.write(event.data(), event.size());
  14294. }
  14295. // Keep connection open while handler_running is true
  14296. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14297. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14298. }
  14299. return false;
  14300. });
  14301. });
  14302. Client client("localhost", get_port());
  14303. sse::SSEClient sse(client, "/stay-open");
  14304. std::atomic<bool> connected{false};
  14305. sse.on_open([&connected]() { connected.store(true); });
  14306. sse.set_reconnect_interval(100);
  14307. sse.set_max_reconnect_attempts(1);
  14308. sse.start_async();
  14309. // Wait for connection to establish
  14310. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14311. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14312. }
  14313. EXPECT_TRUE(connected.load());
  14314. EXPECT_TRUE(sse.is_connected());
  14315. // Signal handler to stop
  14316. handler_running.store(false);
  14317. // Stop SSE client
  14318. sse.stop();
  14319. EXPECT_FALSE(sse.is_connected());
  14320. }
  14321. // Test: SSEClient with custom headers
  14322. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14323. // Setup a server endpoint that checks for custom header
  14324. std::atomic<bool> header_received{false};
  14325. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14326. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14327. header_received.store(true);
  14328. }
  14329. res.set_chunked_content_provider("text/event-stream",
  14330. [](size_t, DataSink &) { return false; });
  14331. });
  14332. Client client("localhost", get_port());
  14333. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14334. sse::SSEClient sse(client, "/header-check", headers);
  14335. sse.set_max_reconnect_attempts(1);
  14336. sse.start_async();
  14337. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14338. sse.stop();
  14339. EXPECT_TRUE(header_received.load());
  14340. }
  14341. // Test: Reconnect interval configuration
  14342. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14343. Client client("localhost", get_port());
  14344. sse::SSEClient sse(client, "/events");
  14345. auto &result = sse.set_reconnect_interval(500);
  14346. // Builder pattern should return reference to self
  14347. EXPECT_EQ(&result, &sse);
  14348. }
  14349. // Test: Max reconnect attempts
  14350. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14351. // Connect to non-existent port to force reconnects
  14352. Client client("localhost", 59998);
  14353. sse::SSEClient sse(client, "/events");
  14354. std::atomic<int> error_count{0};
  14355. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14356. sse.set_reconnect_interval(50);
  14357. sse.set_max_reconnect_attempts(2);
  14358. auto start = std::chrono::steady_clock::now();
  14359. sse.start(); // Blocking call
  14360. auto end = std::chrono::steady_clock::now();
  14361. // Should have stopped after 2 failed attempts
  14362. EXPECT_GE(error_count.load(), 2);
  14363. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14364. auto duration =
  14365. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14366. #ifdef _WIN32
  14367. // Windows is much slower for socket connection failures
  14368. EXPECT_LT(duration.count(), 7000);
  14369. #else
  14370. EXPECT_LT(duration.count(), 1000);
  14371. #endif
  14372. }
  14373. // Test: Multi-line data in integration
  14374. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14375. // Endpoint with multi-line data
  14376. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14377. res.set_chunked_content_provider(
  14378. "text/event-stream", [](size_t offset, DataSink &sink) {
  14379. if (offset == 0) {
  14380. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14381. sink.write(event.data(), event.size());
  14382. }
  14383. return false;
  14384. });
  14385. });
  14386. Client client("localhost", get_port());
  14387. sse::SSEClient sse(client, "/multiline-data");
  14388. std::string received_data;
  14389. std::mutex data_mutex;
  14390. sse.on_message([&](const sse::SSEMessage &msg) {
  14391. std::lock_guard<std::mutex> lock(data_mutex);
  14392. received_data = msg.data;
  14393. });
  14394. sse.set_reconnect_interval(100);
  14395. sse.set_max_reconnect_attempts(1);
  14396. sse.start_async();
  14397. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14398. sse.stop();
  14399. std::lock_guard<std::mutex> lock(data_mutex);
  14400. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14401. }
  14402. // Test: Auto-reconnect after server disconnection
  14403. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14404. std::atomic<int> connection_count{0};
  14405. std::atomic<int> message_count{0};
  14406. // Endpoint that sends one event and closes, forcing reconnect
  14407. server_->Get("/reconnect-test",
  14408. [&connection_count](const Request &, Response &res) {
  14409. connection_count.fetch_add(1);
  14410. res.set_chunked_content_provider(
  14411. "text/event-stream", [](size_t offset, DataSink &sink) {
  14412. if (offset == 0) {
  14413. std::string event = "data: hello\n\n";
  14414. sink.write(event.data(), event.size());
  14415. }
  14416. return false; // Close connection after sending
  14417. });
  14418. });
  14419. Client client("localhost", get_port());
  14420. sse::SSEClient sse(client, "/reconnect-test");
  14421. sse.on_message([&message_count](const sse::SSEMessage &) {
  14422. message_count.fetch_add(1);
  14423. });
  14424. sse.set_reconnect_interval(100);
  14425. sse.set_max_reconnect_attempts(3);
  14426. sse.start_async();
  14427. // Wait long enough for multiple reconnects
  14428. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14429. sse.stop();
  14430. // Should have connected multiple times (initial + reconnects)
  14431. EXPECT_GE(connection_count.load(), 2);
  14432. // Should have received messages from multiple connections
  14433. EXPECT_GE(message_count.load(), 2);
  14434. }
  14435. // Test: Last-Event-ID sent on reconnect
  14436. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14437. std::atomic<int> connection_count{0};
  14438. std::vector<std::string> received_last_event_ids;
  14439. std::mutex id_mutex;
  14440. // Endpoint that checks Last-Event-ID header and sends event with ID
  14441. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14442. int conn = connection_count.fetch_add(1);
  14443. // Capture the Last-Event-ID header from each connection
  14444. {
  14445. std::lock_guard<std::mutex> lock(id_mutex);
  14446. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14447. }
  14448. res.set_chunked_content_provider(
  14449. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14450. if (offset == 0) {
  14451. std::string event =
  14452. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14453. sink.write(event.data(), event.size());
  14454. }
  14455. return false;
  14456. });
  14457. });
  14458. Client client("localhost", get_port());
  14459. sse::SSEClient sse(client, "/reconnect-with-id");
  14460. sse.set_reconnect_interval(100);
  14461. sse.set_max_reconnect_attempts(3);
  14462. sse.start_async();
  14463. // Wait for at least 2 connections
  14464. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14465. sse.stop();
  14466. // Verify behavior
  14467. std::lock_guard<std::mutex> lock(id_mutex);
  14468. EXPECT_GE(received_last_event_ids.size(), 2u);
  14469. // First connection should have no Last-Event-ID
  14470. if (!received_last_event_ids.empty()) {
  14471. EXPECT_EQ(received_last_event_ids[0], "");
  14472. }
  14473. // Second connection should have Last-Event-ID from first connection
  14474. if (received_last_event_ids.size() >= 2) {
  14475. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14476. }
  14477. }
  14478. // Test: set_headers updates headers used on reconnect
  14479. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14480. std::vector<std::string> received_tokens;
  14481. std::mutex token_mutex;
  14482. // Endpoint that captures Authorization header
  14483. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14484. {
  14485. std::lock_guard<std::mutex> lock(token_mutex);
  14486. received_tokens.push_back(req.get_header_value("Authorization"));
  14487. }
  14488. res.set_chunked_content_provider(
  14489. "text/event-stream", [](size_t offset, DataSink &sink) {
  14490. if (offset == 0) {
  14491. std::string event = "data: hello\n\n";
  14492. sink.write(event.data(), event.size());
  14493. }
  14494. return false; // Close connection to trigger reconnect
  14495. });
  14496. });
  14497. Client client("localhost", get_port());
  14498. Headers headers = {{"Authorization", "Bearer old-token"}};
  14499. sse::SSEClient sse(client, "/auth-check", headers);
  14500. // Update headers on each successful connection
  14501. sse.on_open(
  14502. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14503. sse.set_reconnect_interval(100);
  14504. sse.set_max_reconnect_attempts(3);
  14505. sse.start_async();
  14506. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14507. sse.stop();
  14508. std::lock_guard<std::mutex> lock(token_mutex);
  14509. ASSERT_GE(received_tokens.size(), 2u);
  14510. // First connection uses original header
  14511. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14512. // Second connection uses updated header from set_headers
  14513. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14514. }
  14515. // Test: 401 allows reconnection (so on_error can refresh headers)
  14516. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14517. std::atomic<int> connection_count{0};
  14518. // Endpoint: returns 401 on first attempt, 200 on second
  14519. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14520. int conn = connection_count.fetch_add(1);
  14521. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14522. res.status = StatusCode::Unauthorized_401;
  14523. res.set_content("Unauthorized", "text/plain");
  14524. return;
  14525. }
  14526. res.set_chunked_content_provider(
  14527. "text/event-stream", [](size_t offset, DataSink &sink) {
  14528. if (offset == 0) {
  14529. std::string event = "data: authenticated\n\n";
  14530. sink.write(event.data(), event.size());
  14531. }
  14532. return false;
  14533. });
  14534. });
  14535. Client client("localhost", get_port());
  14536. Headers headers = {{"Authorization", "Bearer expired"}};
  14537. sse::SSEClient sse(client, "/auth-retry", headers);
  14538. std::atomic<bool> message_received{false};
  14539. // Refresh token on error
  14540. sse.on_error(
  14541. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14542. sse.on_message([&](const sse::SSEMessage &msg) {
  14543. if (msg.data == "authenticated") { message_received.store(true); }
  14544. });
  14545. sse.set_reconnect_interval(100);
  14546. sse.set_max_reconnect_attempts(3);
  14547. sse.start_async();
  14548. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14549. sse.stop();
  14550. // Should have reconnected after 401 and succeeded with new token
  14551. EXPECT_GE(connection_count.load(), 2);
  14552. EXPECT_TRUE(message_received.load());
  14553. }
  14554. TEST(Issue2318Test, EmptyHostString) {
  14555. {
  14556. httplib::Client cli_empty("", PORT);
  14557. auto res = cli_empty.Get("/");
  14558. ASSERT_FALSE(res);
  14559. EXPECT_EQ(httplib::Error::Connection, res.error());
  14560. }
  14561. {
  14562. httplib::Client cli(" ", PORT);
  14563. auto res = cli.Get("/");
  14564. ASSERT_FALSE(res);
  14565. EXPECT_EQ(httplib::Error::Connection, res.error());
  14566. }
  14567. }
  14568. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14569. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14570. Server svr;
  14571. // Set a small payload limit (1KB)
  14572. svr.set_payload_max_length(1024);
  14573. svr.Post("/test", [&](const Request &req, Response &res) {
  14574. res.set_content("Body size: " + std::to_string(req.body.size()),
  14575. "text/plain");
  14576. });
  14577. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14578. auto se = detail::scope_exit([&] {
  14579. svr.stop();
  14580. listen_thread.join();
  14581. });
  14582. svr.wait_until_ready();
  14583. // Create data that compresses well but exceeds limit when decompressed
  14584. // 8KB of repeated null bytes compresses to a very small size
  14585. std::string original_data(8 * 1024, '\0');
  14586. // Compress the data using gzip
  14587. std::string compressed_data;
  14588. detail::gzip_compressor compressor;
  14589. compressor.compress(original_data.data(), original_data.size(), true,
  14590. [&](const char *data, size_t size) {
  14591. compressed_data.append(data, size);
  14592. return true;
  14593. });
  14594. // Verify compression worked (compressed should be much smaller)
  14595. ASSERT_LT(compressed_data.size(), original_data.size());
  14596. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14597. // Send compressed data with Content-Encoding: gzip
  14598. Client cli(HOST, PORT);
  14599. Headers headers = {{"Content-Encoding", "gzip"}};
  14600. auto res =
  14601. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14602. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14603. ASSERT_TRUE(res);
  14604. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14605. }
  14606. #endif
  14607. // ============================================================================
  14608. // OpenSSL-Specific Tests
  14609. // ============================================================================
  14610. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14611. X509 *readCertificate(const std::string &strFileName) {
  14612. std::ifstream inStream(strFileName);
  14613. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14614. std::istreambuf_iterator<char>());
  14615. if (strCertPEM.empty()) return (nullptr);
  14616. BIO *pbCert = BIO_new(BIO_s_mem());
  14617. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14618. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14619. BIO_free(pbCert);
  14620. return (pCert);
  14621. }
  14622. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14623. std::ifstream inStream(strFileName);
  14624. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14625. std::istreambuf_iterator<char>());
  14626. if (strPrivateKeyPEM.empty()) return (nullptr);
  14627. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14628. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14629. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14630. BIO_free(pbPrivKey);
  14631. return (pPrivateKey);
  14632. }
  14633. TEST(BindServerTest, UpdateCerts) {
  14634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14635. int port = svr.bind_to_any_port("0.0.0.0");
  14636. ASSERT_TRUE(svr.is_valid());
  14637. ASSERT_TRUE(port > 0);
  14638. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14639. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14640. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14641. ASSERT_TRUE(cert != nullptr);
  14642. ASSERT_TRUE(ca_cert != nullptr);
  14643. ASSERT_TRUE(key != nullptr);
  14644. X509_STORE *cert_store = X509_STORE_new();
  14645. X509_STORE_add_cert(cert_store, ca_cert);
  14646. // svr.update_certs(cert, key, cert_store); // deprecated
  14647. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14648. CLIENT_CA_CERT_FILE);
  14649. ASSERT_TRUE(svr.is_valid());
  14650. svr.stop();
  14651. X509_STORE_free(cert_store);
  14652. X509_free(cert);
  14653. X509_free(ca_cert);
  14654. EVP_PKEY_free(key);
  14655. }
  14656. // Test that update_certs() updates client CA list correctly
  14657. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14658. // Start with file-based constructor
  14659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14660. ASSERT_TRUE(svr.is_valid());
  14661. // Initially no client CA list should be set
  14662. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14663. ASSERT_TRUE(ssl_ctx != nullptr);
  14664. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14665. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14666. EXPECT_EQ(0, count_before);
  14667. // Now update with client CA (PEM string)
  14668. std::string cert_pem, key_pem, ca_pem;
  14669. read_file(SERVER_CERT_FILE, cert_pem);
  14670. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14671. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14672. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14673. ASSERT_TRUE(svr.is_valid());
  14674. // Now client CA list should be set
  14675. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14676. ASSERT_TRUE(ca_list_after != nullptr);
  14677. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14678. }
  14679. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14680. // Test that the file-path SSLServer constructor properly sets the client CA
  14681. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14683. ASSERT_TRUE(svr.is_valid());
  14684. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14685. ASSERT_TRUE(ssl_ctx != nullptr);
  14686. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14687. ASSERT_TRUE(ca_list != nullptr);
  14688. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14689. }
  14690. #endif
  14691. // ============================================================================
  14692. // MbedTLS-Specific Tests
  14693. // ============================================================================
  14694. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14695. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14696. using namespace httplib::tls;
  14697. // Track if callback was invoked
  14698. bool callback_invoked = false;
  14699. // The callback receives void* ctx which is actually MbedTlsContext*
  14700. // We can access the mbedtls_ssl_config via the context
  14701. auto setup_callback = [&callback_invoked](void *ctx) {
  14702. callback_invoked = true;
  14703. // Cast to MbedTlsContext* to access the ssl config
  14704. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14705. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14706. // Use static variables to hold certificate data (simplified for test)
  14707. static mbedtls_x509_crt own_cert;
  14708. static mbedtls_pk_context own_key;
  14709. static mbedtls_x509_crt ca_chain;
  14710. static bool initialized = false;
  14711. if (!initialized) {
  14712. mbedtls_x509_crt_init(&own_cert);
  14713. mbedtls_pk_init(&own_key);
  14714. mbedtls_x509_crt_init(&ca_chain);
  14715. // Load server certificate
  14716. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14717. return false;
  14718. }
  14719. // Load server private key
  14720. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14721. #if MBEDTLS_VERSION_MAJOR >= 3
  14722. ,
  14723. mbedtls_ctr_drbg_random, nullptr
  14724. #endif
  14725. ) != 0) {
  14726. return false;
  14727. }
  14728. // Load CA chain for client verification
  14729. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14730. return false;
  14731. }
  14732. initialized = true;
  14733. }
  14734. // Configure the SSL config
  14735. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14736. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14737. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14738. // Set minimum TLS version using mbedTLS native API
  14739. #if MBEDTLS_VERSION_MAJOR >= 3
  14740. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14741. #else
  14742. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14743. MBEDTLS_SSL_MINOR_VERSION_3);
  14744. #endif
  14745. return true;
  14746. };
  14747. SSLServer svr(setup_callback);
  14748. ASSERT_TRUE(svr.is_valid());
  14749. ASSERT_TRUE(callback_invoked);
  14750. svr.Get("/test", [&](const Request &req, Response &res) {
  14751. res.set_content("test", "text/plain");
  14752. auto cert = req.peer_cert();
  14753. ASSERT_TRUE(static_cast<bool>(cert));
  14754. auto common_name = cert.subject_cn();
  14755. EXPECT_EQ("Common Name", common_name);
  14756. });
  14757. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14758. auto se = detail::scope_exit([&] {
  14759. svr.stop();
  14760. t.join();
  14761. ASSERT_FALSE(svr.is_running());
  14762. });
  14763. svr.wait_until_ready();
  14764. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14765. cli.enable_server_certificate_verification(false);
  14766. cli.set_connection_timeout(30);
  14767. auto res = cli.Get("/test");
  14768. ASSERT_TRUE(res);
  14769. ASSERT_EQ(StatusCode::OK_200, res->status);
  14770. }
  14771. #endif
  14772. // WebSocket Tests
  14773. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14774. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14775. // defining the meaning of these bits has been negotiated.
  14776. auto make_frame = [](uint8_t first_byte) {
  14777. std::string frame;
  14778. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14779. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14780. frame += "Hello";
  14781. return frame;
  14782. };
  14783. // RSV1 set (0x40)
  14784. {
  14785. detail::BufferStream strm;
  14786. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14787. ws::Opcode opcode;
  14788. std::string payload;
  14789. bool fin;
  14790. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14791. false, 1024));
  14792. }
  14793. // RSV2 set (0x20)
  14794. {
  14795. detail::BufferStream strm;
  14796. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14797. ws::Opcode opcode;
  14798. std::string payload;
  14799. bool fin;
  14800. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14801. false, 1024));
  14802. }
  14803. // RSV3 set (0x10)
  14804. {
  14805. detail::BufferStream strm;
  14806. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14807. ws::Opcode opcode;
  14808. std::string payload;
  14809. bool fin;
  14810. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14811. false, 1024));
  14812. }
  14813. // No RSV bits set - should succeed
  14814. {
  14815. detail::BufferStream strm;
  14816. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14817. ws::Opcode opcode;
  14818. std::string payload;
  14819. bool fin;
  14820. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14821. false, 1024));
  14822. EXPECT_EQ(ws::Opcode::Text, opcode);
  14823. EXPECT_EQ("Hello", payload);
  14824. EXPECT_TRUE(fin);
  14825. }
  14826. }
  14827. TEST(WebSocketTest, ControlFrameValidation) {
  14828. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14829. // payload length <= 125.
  14830. // Ping with FIN=0 - must be rejected
  14831. {
  14832. detail::BufferStream strm;
  14833. std::string frame;
  14834. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14835. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14836. strm.write(frame.data(), frame.size());
  14837. ws::Opcode opcode;
  14838. std::string payload;
  14839. bool fin;
  14840. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14841. false, 1024));
  14842. }
  14843. // Close with FIN=0 - must be rejected
  14844. {
  14845. detail::BufferStream strm;
  14846. std::string frame;
  14847. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14848. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14849. strm.write(frame.data(), frame.size());
  14850. ws::Opcode opcode;
  14851. std::string payload;
  14852. bool fin;
  14853. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14854. false, 1024));
  14855. }
  14856. // Ping with payload_len=126 (extended length) - must be rejected
  14857. {
  14858. detail::BufferStream strm;
  14859. std::string frame;
  14860. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14861. frame += static_cast<char>(126); // payload_len=126 (>125)
  14862. frame += static_cast<char>(0x00); // extended length high byte
  14863. frame += static_cast<char>(126); // extended length low byte
  14864. frame += std::string(126, 'x');
  14865. strm.write(frame.data(), frame.size());
  14866. ws::Opcode opcode;
  14867. std::string payload;
  14868. bool fin;
  14869. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14870. false, 1024));
  14871. }
  14872. // Ping with FIN=1 and payload_len=125 - should succeed
  14873. {
  14874. detail::BufferStream strm;
  14875. std::string frame;
  14876. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14877. frame += static_cast<char>(125); // payload_len=125
  14878. frame += std::string(125, 'x');
  14879. strm.write(frame.data(), frame.size());
  14880. ws::Opcode opcode;
  14881. std::string payload;
  14882. bool fin;
  14883. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14884. false, 1024));
  14885. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14886. EXPECT_EQ(125u, payload.size());
  14887. EXPECT_TRUE(fin);
  14888. }
  14889. }
  14890. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14891. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14892. // length MUST be 0.
  14893. // MSB set - must be rejected
  14894. {
  14895. detail::BufferStream strm;
  14896. std::string frame;
  14897. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14898. frame += static_cast<char>(127); // 64-bit extended length
  14899. frame += static_cast<char>(0x80); // MSB set (invalid)
  14900. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14901. strm.write(frame.data(), frame.size());
  14902. ws::Opcode opcode;
  14903. std::string payload;
  14904. bool fin;
  14905. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14906. false, 1024));
  14907. }
  14908. // MSB clear - should pass length parsing (will be rejected by max_len,
  14909. // but that's a different check; use a small length to verify)
  14910. {
  14911. detail::BufferStream strm;
  14912. std::string frame;
  14913. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14914. frame += static_cast<char>(127); // 64-bit extended length
  14915. frame += std::string(7, '\0'); // high bytes = 0
  14916. frame += static_cast<char>(0x03); // length = 3
  14917. frame += "abc";
  14918. strm.write(frame.data(), frame.size());
  14919. ws::Opcode opcode;
  14920. std::string payload;
  14921. bool fin;
  14922. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14923. false, 1024));
  14924. EXPECT_EQ(ws::Opcode::Text, opcode);
  14925. EXPECT_EQ("abc", payload);
  14926. }
  14927. }
  14928. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14929. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14930. // Valid UTF-8
  14931. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14932. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14933. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14934. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14935. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14936. // Invalid UTF-8
  14937. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14938. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14939. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14940. EXPECT_FALSE(
  14941. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14942. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14943. }
  14944. TEST(WebSocketTest, ConnectAndDisconnect) {
  14945. Server svr;
  14946. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14947. std::string msg;
  14948. while (ws.read(msg)) {}
  14949. });
  14950. auto port = svr.bind_to_any_port(HOST);
  14951. std::thread t([&]() { svr.listen_after_bind(); });
  14952. svr.wait_until_ready();
  14953. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14954. ASSERT_TRUE(client.connect());
  14955. EXPECT_TRUE(client.is_open());
  14956. client.close();
  14957. EXPECT_FALSE(client.is_open());
  14958. svr.stop();
  14959. t.join();
  14960. }
  14961. TEST(WebSocketTest, ValidURL) {
  14962. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14963. EXPECT_TRUE(ws1.is_valid());
  14964. ws::WebSocketClient ws2("ws://example.com/path");
  14965. EXPECT_TRUE(ws2.is_valid());
  14966. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14967. EXPECT_TRUE(ws3.is_valid());
  14968. #ifdef CPPHTTPLIB_SSL_ENABLED
  14969. ws::WebSocketClient wss1("wss://example.com/path");
  14970. EXPECT_TRUE(wss1.is_valid());
  14971. ws::WebSocketClient wss2("wss://example.com:443/path");
  14972. EXPECT_TRUE(wss2.is_valid());
  14973. #endif
  14974. }
  14975. TEST(WebSocketTest, InvalidURL) {
  14976. // No scheme
  14977. ws::WebSocketClient ws1("localhost:8080/path");
  14978. EXPECT_FALSE(ws1.is_valid());
  14979. // No path
  14980. ws::WebSocketClient ws2("ws://localhost:8080");
  14981. EXPECT_FALSE(ws2.is_valid());
  14982. // Empty string
  14983. ws::WebSocketClient ws3("");
  14984. EXPECT_FALSE(ws3.is_valid());
  14985. // Missing host
  14986. ws::WebSocketClient ws4("ws://:8080/path");
  14987. EXPECT_FALSE(ws4.is_valid());
  14988. // Port number overflow — should not crash
  14989. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14990. EXPECT_FALSE(ws5.is_valid());
  14991. // Port out of range
  14992. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14993. EXPECT_FALSE(ws6.is_valid());
  14994. }
  14995. TEST(WebSocketTest, UnsupportedScheme) {
  14996. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14997. ws::WebSocketClient ws1("http://localhost:8080/path");
  14998. EXPECT_FALSE(ws1.is_valid());
  14999. ws::WebSocketClient ws2("https://localhost:8080/path");
  15000. EXPECT_FALSE(ws2.is_valid());
  15001. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15002. EXPECT_FALSE(ws3.is_valid());
  15003. #else
  15004. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15005. std::invalid_argument);
  15006. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15007. std::invalid_argument);
  15008. #endif
  15009. }
  15010. TEST(WebSocketTest, ConnectWhenInvalid) {
  15011. ws::WebSocketClient ws("not a valid url");
  15012. EXPECT_FALSE(ws.is_valid());
  15013. EXPECT_FALSE(ws.connect());
  15014. }
  15015. TEST(WebSocketTest, DefaultPort) {
  15016. ws::WebSocketClient ws1("ws://example.com/path");
  15017. EXPECT_TRUE(ws1.is_valid());
  15018. // ws:// defaults to port 80 (verified by successful parse)
  15019. #ifdef CPPHTTPLIB_SSL_ENABLED
  15020. ws::WebSocketClient ws2("wss://example.com/path");
  15021. EXPECT_TRUE(ws2.is_valid());
  15022. // wss:// defaults to port 443 (verified by successful parse)
  15023. #endif
  15024. }
  15025. TEST(WebSocketTest, IPv6LiteralAddress) {
  15026. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15027. EXPECT_TRUE(ws1.is_valid());
  15028. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15029. EXPECT_TRUE(ws2.is_valid());
  15030. }
  15031. TEST(WebSocketTest, ComplexPath) {
  15032. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15033. EXPECT_TRUE(ws1.is_valid());
  15034. ws::WebSocketClient ws2("ws://localhost:8080/");
  15035. EXPECT_TRUE(ws2.is_valid());
  15036. }
  15037. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15038. Server svr;
  15039. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15040. std::string msg;
  15041. while (ws.read(msg)) {}
  15042. });
  15043. auto port = svr.bind_to_any_port(HOST);
  15044. std::thread t([&]() { svr.listen_after_bind(); });
  15045. svr.wait_until_ready();
  15046. auto another_host = "example.com";
  15047. auto wrong_ip = "192.0.2.1";
  15048. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15049. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15050. ASSERT_TRUE(client.connect());
  15051. EXPECT_TRUE(client.is_open());
  15052. client.close();
  15053. svr.stop();
  15054. t.join();
  15055. }
  15056. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15057. Server svr;
  15058. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15059. std::string msg;
  15060. while (ws.read(msg)) {}
  15061. });
  15062. auto port = svr.bind_to_any_port(HOST);
  15063. std::thread t([&]() { svr.listen_after_bind(); });
  15064. svr.wait_until_ready();
  15065. auto wrong_ip = "192.0.2.1";
  15066. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15067. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15068. client.set_connection_timeout(1);
  15069. client.set_read_timeout(1);
  15070. client.set_write_timeout(1);
  15071. EXPECT_FALSE(client.connect());
  15072. EXPECT_FALSE(client.is_open());
  15073. svr.stop();
  15074. t.join();
  15075. }
  15076. class WebSocketIntegrationTest : public ::testing::Test {
  15077. protected:
  15078. void SetUp() override {
  15079. server_ = httplib::detail::make_unique<Server>();
  15080. setup_server();
  15081. start_server();
  15082. }
  15083. void TearDown() override {
  15084. server_->stop();
  15085. if (server_thread_.joinable()) { server_thread_.join(); }
  15086. }
  15087. void setup_server() {
  15088. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15089. std::string msg;
  15090. ws::ReadResult ret;
  15091. while ((ret = ws.read(msg))) {
  15092. if (ret == ws::Binary) {
  15093. ws.send(msg.data(), msg.size());
  15094. } else {
  15095. ws.send(msg);
  15096. }
  15097. }
  15098. });
  15099. server_->WebSocket("/ws-echo-string",
  15100. [](const Request &, ws::WebSocket &ws) {
  15101. std::string msg;
  15102. while (ws.read(msg)) {
  15103. ws.send("echo: " + msg);
  15104. }
  15105. });
  15106. server_->WebSocket(
  15107. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15108. // Echo back request metadata
  15109. ws.send("path:" + req.path);
  15110. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15111. std::string msg;
  15112. while (ws.read(msg)) {}
  15113. });
  15114. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15115. std::string msg;
  15116. ws.read(msg); // wait for a message
  15117. ws.close();
  15118. });
  15119. server_->WebSocket("/ws-close-status",
  15120. [](const Request &, ws::WebSocket &ws) {
  15121. std::string msg;
  15122. ws.read(msg); // wait for a message
  15123. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15124. });
  15125. server_->WebSocket(
  15126. "/ws-subprotocol",
  15127. [](const Request &, ws::WebSocket &ws) {
  15128. std::string msg;
  15129. while (ws.read(msg)) {
  15130. ws.send(msg);
  15131. }
  15132. },
  15133. [](const std::vector<std::string> &protocols) -> std::string {
  15134. for (const auto &p : protocols) {
  15135. if (p == "graphql-ws") { return p; }
  15136. }
  15137. return "";
  15138. });
  15139. }
  15140. void start_server() {
  15141. port_ = server_->bind_to_any_port(HOST);
  15142. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15143. server_->wait_until_ready();
  15144. }
  15145. std::unique_ptr<Server> server_;
  15146. std::thread server_thread_;
  15147. int port_ = 0;
  15148. };
  15149. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15150. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15151. "/ws-echo");
  15152. ASSERT_TRUE(client.connect());
  15153. ASSERT_TRUE(client.is_open());
  15154. ASSERT_TRUE(client.send("Hello WebSocket"));
  15155. std::string msg;
  15156. EXPECT_EQ(ws::Text, client.read(msg));
  15157. EXPECT_EQ("Hello WebSocket", msg);
  15158. client.close();
  15159. }
  15160. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15161. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15162. "/ws-echo");
  15163. ASSERT_TRUE(client.connect());
  15164. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15165. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15166. std::string msg;
  15167. EXPECT_EQ(ws::Binary, client.read(msg));
  15168. EXPECT_EQ(binary_data, msg);
  15169. client.close();
  15170. }
  15171. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15172. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15173. "/ws-echo");
  15174. ASSERT_TRUE(client.connect());
  15175. for (int i = 0; i < 10; i++) {
  15176. auto text = "message " + std::to_string(i);
  15177. ASSERT_TRUE(client.send(text));
  15178. std::string msg;
  15179. ASSERT_TRUE(client.read(msg));
  15180. EXPECT_EQ(text, msg);
  15181. }
  15182. client.close();
  15183. }
  15184. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15185. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15186. "/ws-close");
  15187. ASSERT_TRUE(client.connect());
  15188. // Send a message to trigger the server to close
  15189. ASSERT_TRUE(client.send("trigger close"));
  15190. // The server will close, so read should return false
  15191. std::string msg;
  15192. EXPECT_FALSE(client.read(msg));
  15193. EXPECT_FALSE(client.is_open());
  15194. }
  15195. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15196. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15197. "/ws-echo");
  15198. ASSERT_TRUE(client.connect());
  15199. // 128KB message
  15200. std::string large_data(128 * 1024, 'X');
  15201. ASSERT_TRUE(client.send(large_data));
  15202. std::string msg;
  15203. ASSERT_TRUE(client.read(msg));
  15204. EXPECT_EQ(large_data, msg);
  15205. client.close();
  15206. }
  15207. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15208. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15209. "/ws-echo");
  15210. ASSERT_TRUE(client.connect());
  15211. const int num_threads = 4;
  15212. std::vector<std::thread> threads;
  15213. std::atomic<int> send_count{0};
  15214. for (int t = 0; t < num_threads; t++) {
  15215. threads.emplace_back([&client, &send_count, t]() {
  15216. for (int i = 0; i < 5; i++) {
  15217. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15218. if (client.send(text)) { send_count++; }
  15219. }
  15220. });
  15221. }
  15222. for (auto &th : threads) {
  15223. th.join();
  15224. }
  15225. int received = 0;
  15226. std::string msg;
  15227. while (received < send_count.load()) {
  15228. if (!client.read(msg)) { break; }
  15229. received++;
  15230. }
  15231. EXPECT_EQ(send_count.load(), received);
  15232. client.close();
  15233. }
  15234. TEST_F(WebSocketIntegrationTest, ReadString) {
  15235. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15236. "/ws-echo-string");
  15237. ASSERT_TRUE(client.connect());
  15238. ASSERT_TRUE(client.send("hello"));
  15239. std::string msg;
  15240. ASSERT_TRUE(client.read(msg));
  15241. EXPECT_EQ("echo: hello", msg);
  15242. ASSERT_TRUE(client.send("world"));
  15243. ASSERT_TRUE(client.read(msg));
  15244. EXPECT_EQ("echo: world", msg);
  15245. client.close();
  15246. }
  15247. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15248. Headers headers = {{"X-Test-Header", "test-value"}};
  15249. ws::WebSocketClient client(
  15250. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15251. ASSERT_TRUE(client.connect());
  15252. std::string msg;
  15253. ASSERT_TRUE(client.read(msg));
  15254. EXPECT_EQ("path:/ws-request-info", msg);
  15255. ASSERT_TRUE(client.read(msg));
  15256. EXPECT_EQ("header:test-value", msg);
  15257. client.close();
  15258. }
  15259. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15260. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15261. "/ws-echo");
  15262. client.set_read_timeout(1, 0); // 1 second
  15263. ASSERT_TRUE(client.connect());
  15264. // Don't send anything — server echo handler waits for a message,
  15265. // so read() should time out and return false.
  15266. std::string msg;
  15267. EXPECT_FALSE(client.read(msg));
  15268. }
  15269. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15270. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15271. "/ws-echo");
  15272. client.set_read_timeout(5, 0);
  15273. ASSERT_TRUE(client.connect());
  15274. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15275. // The server should reject it and close the connection.
  15276. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15277. client.send(oversized);
  15278. // The server's read() should have failed due to payload limit,
  15279. // so our read() should return false (connection closed).
  15280. std::string msg;
  15281. EXPECT_FALSE(client.read(msg));
  15282. }
  15283. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15284. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15285. "/ws-echo");
  15286. client.set_read_timeout(10, 0);
  15287. ASSERT_TRUE(client.connect());
  15288. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15289. // This should succeed.
  15290. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15291. ASSERT_TRUE(client.send(at_limit));
  15292. std::string msg;
  15293. ASSERT_TRUE(client.read(msg));
  15294. EXPECT_EQ(at_limit.size(), msg.size());
  15295. client.close();
  15296. }
  15297. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15298. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15299. "/nonexistent");
  15300. EXPECT_FALSE(client.connect());
  15301. EXPECT_FALSE(client.is_open());
  15302. }
  15303. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15304. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15305. "/ws-echo");
  15306. ASSERT_TRUE(client.connect());
  15307. ASSERT_TRUE(client.send(""));
  15308. std::string msg;
  15309. EXPECT_EQ(ws::Text, client.read(msg));
  15310. EXPECT_EQ("", msg);
  15311. client.close();
  15312. }
  15313. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15314. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15315. "/ws-echo");
  15316. // First connection
  15317. ASSERT_TRUE(client.connect());
  15318. ASSERT_TRUE(client.send("first"));
  15319. std::string msg;
  15320. ASSERT_TRUE(client.read(msg));
  15321. EXPECT_EQ("first", msg);
  15322. client.close();
  15323. EXPECT_FALSE(client.is_open());
  15324. // Reconnect using the same client object
  15325. ASSERT_TRUE(client.connect());
  15326. ASSERT_TRUE(client.is_open());
  15327. ASSERT_TRUE(client.send("second"));
  15328. ASSERT_TRUE(client.read(msg));
  15329. EXPECT_EQ("second", msg);
  15330. client.close();
  15331. }
  15332. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15333. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15334. "/ws-close-status");
  15335. ASSERT_TRUE(client.connect());
  15336. // Trigger the server to close with GoingAway status
  15337. ASSERT_TRUE(client.send("trigger"));
  15338. // read() should return false after receiving the close frame
  15339. std::string msg;
  15340. EXPECT_FALSE(client.read(msg));
  15341. EXPECT_FALSE(client.is_open());
  15342. }
  15343. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15344. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15345. "/ws-echo");
  15346. ASSERT_TRUE(client.connect());
  15347. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15348. EXPECT_FALSE(client.is_open());
  15349. }
  15350. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15351. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15352. ws::WebSocketClient client(
  15353. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15354. ASSERT_TRUE(client.connect());
  15355. // Server should have selected graphql-ws
  15356. EXPECT_EQ("graphql-ws", client.subprotocol());
  15357. client.close();
  15358. }
  15359. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15360. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15361. ws::WebSocketClient client(
  15362. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15363. ASSERT_TRUE(client.connect());
  15364. // Server should not have selected any subprotocol
  15365. EXPECT_TRUE(client.subprotocol().empty());
  15366. client.close();
  15367. }
  15368. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15369. // Connect without requesting any subprotocol
  15370. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15371. "/ws-subprotocol");
  15372. ASSERT_TRUE(client.connect());
  15373. EXPECT_TRUE(client.subprotocol().empty());
  15374. client.close();
  15375. }
  15376. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15377. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15378. "/ws-echo");
  15379. client.set_tcp_nodelay(true);
  15380. client.set_connection_timeout(3, 0);
  15381. bool socket_options_called = false;
  15382. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15383. ASSERT_TRUE(client.connect());
  15384. ASSERT_TRUE(client.is_open());
  15385. EXPECT_TRUE(socket_options_called);
  15386. ASSERT_TRUE(client.send("hello"));
  15387. std::string msg;
  15388. auto result = client.read(msg);
  15389. EXPECT_EQ(result, ws::ReadResult::Text);
  15390. EXPECT_EQ(msg, "hello");
  15391. client.close();
  15392. }
  15393. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15394. Server svr;
  15395. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15396. if (!req.has_header("Authorization")) {
  15397. res.status = StatusCode::Unauthorized_401;
  15398. res.set_content("Unauthorized", "text/plain");
  15399. return Server::HandlerResponse::Handled;
  15400. }
  15401. return Server::HandlerResponse::Unhandled;
  15402. });
  15403. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15404. std::string msg;
  15405. while (ws.read(msg)) {
  15406. ws.send(msg);
  15407. }
  15408. });
  15409. auto port = svr.bind_to_any_port("localhost");
  15410. std::thread t([&]() { svr.listen_after_bind(); });
  15411. svr.wait_until_ready();
  15412. // Without Authorization header - should be rejected before upgrade
  15413. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15414. EXPECT_FALSE(client1.connect());
  15415. // With Authorization header - should succeed
  15416. Headers headers = {{"Authorization", "Bearer token123"}};
  15417. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15418. headers);
  15419. ASSERT_TRUE(client2.connect());
  15420. ASSERT_TRUE(client2.send("hello"));
  15421. std::string msg;
  15422. ASSERT_TRUE(client2.read(msg));
  15423. EXPECT_EQ("hello", msg);
  15424. client2.close();
  15425. svr.stop();
  15426. t.join();
  15427. }
  15428. TEST(WebSocketTest, QueryStringInHandshake) {
  15429. Server svr;
  15430. std::mutex mtx;
  15431. std::string received_target;
  15432. std::string received_token;
  15433. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15434. {
  15435. std::lock_guard<std::mutex> lock(mtx);
  15436. received_target = req.target;
  15437. if (req.has_param("token")) {
  15438. received_token = req.get_param_value("token");
  15439. }
  15440. }
  15441. std::string msg;
  15442. while (ws.read(msg)) {
  15443. ws.send(msg);
  15444. }
  15445. });
  15446. auto port = svr.bind_to_any_port("localhost");
  15447. std::thread t([&]() { svr.listen_after_bind(); });
  15448. svr.wait_until_ready();
  15449. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15450. "/ws?token=ABC&session=123");
  15451. ASSERT_TRUE(client.connect());
  15452. // Round-trip ensures the handler has run and captured the request.
  15453. ASSERT_TRUE(client.send("hello"));
  15454. std::string msg;
  15455. ASSERT_TRUE(client.read(msg));
  15456. EXPECT_EQ("hello", msg);
  15457. client.close();
  15458. {
  15459. std::lock_guard<std::mutex> lock(mtx);
  15460. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15461. EXPECT_EQ("ABC", received_token);
  15462. }
  15463. svr.stop();
  15464. t.join();
  15465. }
  15466. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15467. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15468. protected:
  15469. void SetUp() override {
  15470. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15471. SERVER_PRIVATE_KEY_FILE);
  15472. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15473. std::string msg;
  15474. ws::ReadResult ret;
  15475. while ((ret = ws.read(msg))) {
  15476. if (ret == ws::Binary) {
  15477. ws.send(msg.data(), msg.size());
  15478. } else {
  15479. ws.send(msg);
  15480. }
  15481. }
  15482. });
  15483. port_ = server_->bind_to_any_port(HOST);
  15484. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15485. server_->wait_until_ready();
  15486. }
  15487. void TearDown() override {
  15488. server_->stop();
  15489. if (server_thread_.joinable()) { server_thread_.join(); }
  15490. }
  15491. std::unique_ptr<SSLServer> server_;
  15492. std::thread server_thread_;
  15493. int port_ = 0;
  15494. };
  15495. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15496. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15497. "/ws-echo");
  15498. client.enable_server_certificate_verification(false);
  15499. ASSERT_TRUE(client.connect());
  15500. ASSERT_TRUE(client.is_open());
  15501. ASSERT_TRUE(client.send("Hello WSS"));
  15502. std::string msg;
  15503. EXPECT_EQ(ws::Text, client.read(msg));
  15504. EXPECT_EQ("Hello WSS", msg);
  15505. client.close();
  15506. }
  15507. #endif
  15508. #ifdef CPPHTTPLIB_SSL_ENABLED
  15509. class WebSocketSSLCATest : public ::testing::Test {
  15510. protected:
  15511. void SetUp() override {
  15512. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  15513. SERVER_PRIVATE_KEY_FILE);
  15514. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15515. std::string msg;
  15516. while (ws.read(msg)) {
  15517. ws.send(msg);
  15518. }
  15519. });
  15520. port_ = server_->bind_to_any_port("127.0.0.1");
  15521. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15522. server_->wait_until_ready();
  15523. }
  15524. void TearDown() override {
  15525. server_->stop();
  15526. if (server_thread_.joinable()) { server_thread_.join(); }
  15527. }
  15528. std::string url() const {
  15529. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  15530. }
  15531. std::unique_ptr<SSLServer> server_;
  15532. std::thread server_thread_;
  15533. int port_ = 0;
  15534. };
  15535. // A custom CA loaded as PEM verifies the server with full certificate
  15536. // verification enabled
  15537. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  15538. ws::WebSocketClient client(url());
  15539. std::string cert;
  15540. read_file(SERVER_CERT2_FILE, cert);
  15541. client.load_ca_cert_store(cert.c_str(), cert.size());
  15542. ASSERT_TRUE(client.connect());
  15543. ASSERT_TRUE(client.send("hello"));
  15544. std::string msg;
  15545. EXPECT_EQ(ws::Text, client.read(msg));
  15546. EXPECT_EQ("hello", msg);
  15547. client.close();
  15548. }
  15549. // A custom CA that does not cover the server must fail verification (the
  15550. // custom CA is exclusive; system certs are not loaded alongside it)
  15551. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  15552. ws::WebSocketClient client(url());
  15553. std::string cert;
  15554. read_file(CLIENT_CA_CERT_FILE, cert);
  15555. client.load_ca_cert_store(cert.c_str(), cert.size());
  15556. ASSERT_FALSE(client.connect());
  15557. }
  15558. // Regression test: reconnecting with a native custom CA store used to reuse
  15559. // a store handle the previous TLS context had already freed (use-after-free
  15560. // under the OpenSSL backend). The context now lives as long as the client.
  15561. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  15562. ws::WebSocketClient client(url());
  15563. std::string cert;
  15564. read_file(SERVER_CERT2_FILE, cert);
  15565. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15566. ASSERT_TRUE(client.connect());
  15567. client.close();
  15568. ASSERT_TRUE(client.connect());
  15569. ASSERT_TRUE(client.send("again"));
  15570. std::string msg;
  15571. EXPECT_EQ(ws::Text, client.read(msg));
  15572. EXPECT_EQ("again", msg);
  15573. client.close();
  15574. }
  15575. // Regression test: a certificate with a trusted chain but no identity match
  15576. // for the server IP must be rejected. The Mbed TLS backend used to skip
  15577. // verification entirely for IP hosts, so this connection succeeded there.
  15578. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  15579. // chain verification while the identity check must still fail.
  15580. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  15581. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15582. ASSERT_TRUE(svr.is_valid());
  15583. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15584. std::string msg;
  15585. while (ws.read(msg)) {
  15586. ws.send(msg);
  15587. }
  15588. });
  15589. auto port = svr.bind_to_any_port("127.0.0.1");
  15590. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15591. auto se = detail::scope_exit([&] {
  15592. svr.stop();
  15593. t.join();
  15594. });
  15595. svr.wait_until_ready();
  15596. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  15597. "/echo");
  15598. std::string cert;
  15599. read_file(SERVER_CERT_FILE, cert);
  15600. client.load_ca_cert_store(cert.c_str(), cert.size());
  15601. ASSERT_FALSE(client.connect());
  15602. }
  15603. #endif
  15604. #if !defined(_WIN32)
  15605. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  15606. auto secret_dir = std::string("./symlink_test_secret");
  15607. auto served_dir = std::string("./symlink_test_served");
  15608. auto secret_file = secret_dir + "/secret.txt";
  15609. auto symlink_path = served_dir + "/escape";
  15610. // Setup: create directories and files
  15611. mkdir(secret_dir.c_str(), 0755);
  15612. mkdir(served_dir.c_str(), 0755);
  15613. {
  15614. std::ofstream ofs(secret_file);
  15615. ofs << "SECRET_DATA";
  15616. }
  15617. // Create symlink using absolute path so it resolves correctly
  15618. #ifdef PATH_MAX
  15619. char abs_secret[PATH_MAX];
  15620. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  15621. #else
  15622. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  15623. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  15624. ASSERT_NE(nullptr, abs_secret);
  15625. #endif
  15626. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  15627. auto se = detail::scope_exit([&] {
  15628. unlink(symlink_path.c_str());
  15629. unlink(secret_file.c_str());
  15630. rmdir(served_dir.c_str());
  15631. rmdir(secret_dir.c_str());
  15632. });
  15633. Server svr;
  15634. svr.set_mount_point("/", served_dir);
  15635. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15636. auto se2 = detail::scope_exit([&] {
  15637. svr.stop();
  15638. listen_thread.join();
  15639. });
  15640. svr.wait_until_ready();
  15641. Client cli("localhost", PORT);
  15642. // Symlink pointing outside base dir should be blocked
  15643. auto res = cli.Get("/escape/secret.txt");
  15644. ASSERT_TRUE(res);
  15645. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15646. }
  15647. #endif
  15648. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15649. // A GET request with Content-Length to a static file handler must have its
  15650. // body drained before the keep-alive connection is reused. Otherwise the
  15651. // unread body bytes are interpreted as the next HTTP request.
  15652. //
  15653. // The body is sent AFTER receiving the first response (as in the original
  15654. // PoC) so that the stream_line_reader cannot buffer it together with the
  15655. // headers of the first request.
  15656. Server svr;
  15657. svr.set_mount_point("/", "./www");
  15658. std::atomic<int> smuggled_count(0);
  15659. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15660. smuggled_count++;
  15661. res.set_content("oops", "text/plain");
  15662. });
  15663. auto port = svr.bind_to_any_port("localhost");
  15664. thread t = thread([&] { svr.listen_after_bind(); });
  15665. auto se = detail::scope_exit([&] {
  15666. svr.stop();
  15667. t.join();
  15668. });
  15669. svr.wait_until_ready();
  15670. auto error = Error::Success;
  15671. auto sock = detail::create_client_socket(
  15672. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15673. /*connection_timeout_sec=*/2, 0,
  15674. /*read_timeout_sec=*/2, 0,
  15675. /*write_timeout_sec=*/2, 0, std::string(), error);
  15676. ASSERT_NE(INVALID_SOCKET, sock);
  15677. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15678. // The "smuggled" request will be sent as the body of the outer GET
  15679. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15680. "Host: localhost\r\n"
  15681. "Connection: close\r\n"
  15682. "\r\n";
  15683. // Step 1: Send only the outer request headers (no body yet)
  15684. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15685. "Host: localhost\r\n"
  15686. "Content-Length: " +
  15687. std::to_string(smuggled.size()) +
  15688. "\r\n"
  15689. "\r\n";
  15690. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15691. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15692. // Step 2: Read the first response (server serves file without reading body)
  15693. std::string first_response;
  15694. char buf[4096];
  15695. for (;;) {
  15696. auto n = recv(sock, buf, sizeof(buf), 0);
  15697. if (n <= 0) break;
  15698. first_response.append(buf, static_cast<size_t>(n));
  15699. // Stop once we have a complete response (headers + body)
  15700. auto hdr_end = first_response.find("\r\n\r\n");
  15701. if (hdr_end != std::string::npos) {
  15702. // Check for Content-Length to know when the body is complete
  15703. auto cl_pos = first_response.find("Content-Length:");
  15704. if (cl_pos != std::string::npos) {
  15705. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15706. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15707. auto cl = std::stoul(
  15708. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15709. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15710. } else {
  15711. break; // No Content-Length, assume headers-only response
  15712. }
  15713. }
  15714. }
  15715. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15716. // Step 3: Now send the body, which looks like a new HTTP request.
  15717. // On a vulnerable server the keep-alive loop reads this as a second request.
  15718. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15719. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15720. // Step 4: Try to read a second response (should NOT exist after fix)
  15721. std::string second_response;
  15722. for (;;) {
  15723. auto n = recv(sock, buf, sizeof(buf), 0);
  15724. if (n <= 0) break;
  15725. second_response.append(buf, static_cast<size_t>(n));
  15726. }
  15727. // The smuggled request must NOT have been processed
  15728. EXPECT_EQ(0, smuggled_count.load());
  15729. }
  15730. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15731. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15732. // must be rejected with 400 Bad Request.
  15733. Server svr;
  15734. svr.Post("/test", [&](const Request &, Response &res) {
  15735. res.set_content("ok", "text/plain");
  15736. });
  15737. thread t = thread([&] { svr.listen(HOST, PORT); });
  15738. auto se = detail::scope_exit([&] {
  15739. svr.stop();
  15740. t.join();
  15741. ASSERT_FALSE(svr.is_running());
  15742. });
  15743. svr.wait_until_ready();
  15744. // Exact "chunked"
  15745. {
  15746. auto req = "POST /test HTTP/1.1\r\n"
  15747. "Host: localhost\r\n"
  15748. "Content-Length: 5\r\n"
  15749. "Transfer-Encoding: chunked\r\n"
  15750. "Connection: close\r\n"
  15751. "\r\n"
  15752. "hello";
  15753. std::string response;
  15754. ASSERT_TRUE(send_request(1, req, &response));
  15755. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15756. response.substr(0, response.find("\r\n")));
  15757. }
  15758. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15759. {
  15760. auto req = "POST /test HTTP/1.1\r\n"
  15761. "Host: localhost\r\n"
  15762. "Content-Length: 5\r\n"
  15763. "Transfer-Encoding: gzip, chunked\r\n"
  15764. "Connection: close\r\n"
  15765. "\r\n"
  15766. "hello";
  15767. std::string response;
  15768. ASSERT_TRUE(send_request(1, req, &response));
  15769. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15770. response.substr(0, response.find("\r\n")));
  15771. }
  15772. }
  15773. // Regression for issue #2450: a DELETE without Content-Length on a
  15774. // keep-alive connection must not let the post-response drain consume the
  15775. // next request's bytes.
  15776. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  15777. Server svr;
  15778. std::atomic<int> delete_count(0);
  15779. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  15780. delete_count++;
  15781. res.status = StatusCode::NoContent_204;
  15782. });
  15783. auto port = svr.bind_to_any_port(HOST);
  15784. thread t = thread([&] { svr.listen_after_bind(); });
  15785. auto se = detail::scope_exit([&] {
  15786. svr.stop();
  15787. t.join();
  15788. });
  15789. svr.wait_until_ready();
  15790. auto error = Error::Success;
  15791. auto sock = detail::create_client_socket(
  15792. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15793. /*connection_timeout_sec=*/2, 0,
  15794. /*read_timeout_sec=*/2, 0,
  15795. /*write_timeout_sec=*/2, 0, std::string(), error);
  15796. ASSERT_NE(INVALID_SOCKET, sock);
  15797. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15798. auto send_request_and_read_response = [&](const std::string &req,
  15799. std::string &out) -> bool {
  15800. auto sent = send(sock, req.data(), req.size(), 0);
  15801. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  15802. char buf[4096];
  15803. for (;;) {
  15804. auto n = recv(sock, buf, sizeof(buf), 0);
  15805. if (n <= 0) { return !out.empty(); }
  15806. out.append(buf, static_cast<size_t>(n));
  15807. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  15808. }
  15809. };
  15810. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  15811. "Host: localhost\r\n"
  15812. "\r\n";
  15813. std::string resp1;
  15814. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  15815. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  15816. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  15817. "Host: localhost\r\n"
  15818. "Connection: close\r\n"
  15819. "\r\n";
  15820. std::string resp2;
  15821. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  15822. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  15823. EXPECT_EQ(2, delete_count.load());
  15824. }
  15825. namespace no_proxy_test {
  15826. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  15827. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  15828. // calling listen().
  15829. class ScopedServer {
  15830. public:
  15831. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  15832. ~ScopedServer() {
  15833. svr_.stop();
  15834. if (th_.joinable()) { th_.join(); }
  15835. }
  15836. Server &svr() { return svr_; }
  15837. int port() const { return port_; }
  15838. void listen() {
  15839. th_ = std::thread([this] { svr_.listen_after_bind(); });
  15840. svr_.wait_until_ready();
  15841. }
  15842. private:
  15843. Server svr_;
  15844. std::thread th_;
  15845. int port_ = 0;
  15846. };
  15847. class ProxyAndTargetServers {
  15848. public:
  15849. ProxyAndTargetServers() {
  15850. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  15851. proxy_hits_++;
  15852. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15853. res.set_content("via-proxy", "text/plain");
  15854. });
  15855. target_.Get(".*", [this](const Request &req, Response &res) {
  15856. target_hits_++;
  15857. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15858. res.set_content("direct", "text/plain");
  15859. });
  15860. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  15861. target_port_ = target_.bind_to_any_port("127.0.0.1");
  15862. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  15863. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  15864. proxy_mock_.wait_until_ready();
  15865. target_.wait_until_ready();
  15866. }
  15867. ~ProxyAndTargetServers() {
  15868. proxy_mock_.stop();
  15869. target_.stop();
  15870. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  15871. if (target_thread_.joinable()) { target_thread_.join(); }
  15872. }
  15873. Server &proxy_mock() { return proxy_mock_; }
  15874. Server &target() { return target_; }
  15875. int proxy_port() const { return proxy_port_; }
  15876. int target_port() const { return target_port_; }
  15877. int proxy_hits() const { return proxy_hits_.load(); }
  15878. int target_hits() const { return target_hits_.load(); }
  15879. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  15880. void reset_counters() {
  15881. proxy_hits_ = 0;
  15882. target_hits_ = 0;
  15883. last_had_proxy_authz_ = false;
  15884. }
  15885. private:
  15886. Server proxy_mock_;
  15887. Server target_;
  15888. std::thread proxy_thread_;
  15889. std::thread target_thread_;
  15890. int proxy_port_ = 0;
  15891. int target_port_ = 0;
  15892. std::atomic<int> proxy_hits_{0};
  15893. std::atomic<int> target_hits_{0};
  15894. std::atomic<bool> last_had_proxy_authz_{false};
  15895. };
  15896. inline std::unique_ptr<Client> make_client(const std::string &host,
  15897. ProxyAndTargetServers &s) {
  15898. auto cli = detail::make_unique<Client>(host, s.target_port());
  15899. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  15900. cli->set_proxy("127.0.0.1", s.proxy_port());
  15901. return cli;
  15902. }
  15903. } // namespace no_proxy_test
  15904. using no_proxy_test::make_client;
  15905. using no_proxy_test::ProxyAndTargetServers;
  15906. TEST(NoProxyTest, ExactHostnameBypasses) {
  15907. ProxyAndTargetServers s;
  15908. auto cli = make_client("example.com", s);
  15909. cli->set_no_proxy({"example.com"});
  15910. auto res = cli->Get("/");
  15911. ASSERT_TRUE(res);
  15912. EXPECT_EQ(0, s.proxy_hits());
  15913. EXPECT_EQ(1, s.target_hits());
  15914. }
  15915. TEST(NoProxyTest, SubdomainBypasses) {
  15916. ProxyAndTargetServers s;
  15917. auto cli = make_client("foo.example.com", s);
  15918. cli->set_no_proxy({"example.com"});
  15919. auto res = cli->Get("/");
  15920. ASSERT_TRUE(res);
  15921. EXPECT_EQ(0, s.proxy_hits());
  15922. EXPECT_EQ(1, s.target_hits());
  15923. }
  15924. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  15925. // Regression guard: "evilexample.com" must not be considered a subdomain
  15926. // of "example.com". Without the dot-boundary rule, a naive endsWith
  15927. // check would let traffic bypass the proxy and leak credentials direct
  15928. // to the attacker host.
  15929. ProxyAndTargetServers s;
  15930. auto cli = make_client("evilexample.com", s);
  15931. cli->set_no_proxy({"example.com"});
  15932. auto res = cli->Get("/");
  15933. ASSERT_TRUE(res);
  15934. EXPECT_GE(s.proxy_hits(), 1);
  15935. EXPECT_EQ(0, s.target_hits());
  15936. }
  15937. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  15938. ProxyAndTargetServers s;
  15939. auto cli = make_client("example.com.evil.com", s);
  15940. cli->set_no_proxy({"example.com"});
  15941. auto res = cli->Get("/");
  15942. ASSERT_TRUE(res);
  15943. EXPECT_GE(s.proxy_hits(), 1);
  15944. EXPECT_EQ(0, s.target_hits());
  15945. }
  15946. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  15947. ProxyAndTargetServers s;
  15948. auto cli = make_client("example.com", s);
  15949. cli->set_no_proxy({".example.com"});
  15950. auto res = cli->Get("/");
  15951. ASSERT_TRUE(res);
  15952. EXPECT_EQ(0, s.proxy_hits());
  15953. EXPECT_EQ(1, s.target_hits());
  15954. }
  15955. TEST(NoProxyTest, CaseInsensitiveHostname) {
  15956. ProxyAndTargetServers s;
  15957. auto cli = make_client("Example.COM", s);
  15958. cli->set_no_proxy({"EXAMPLE.com"});
  15959. auto res = cli->Get("/");
  15960. ASSERT_TRUE(res);
  15961. EXPECT_EQ(0, s.proxy_hits());
  15962. EXPECT_EQ(1, s.target_hits());
  15963. }
  15964. TEST(NoProxyTest, TrailingDotIsNormalized) {
  15965. ProxyAndTargetServers s;
  15966. auto cli = make_client("example.com.", s);
  15967. cli->set_no_proxy({"example.com"});
  15968. auto res = cli->Get("/");
  15969. ASSERT_TRUE(res);
  15970. EXPECT_EQ(0, s.proxy_hits());
  15971. EXPECT_EQ(1, s.target_hits());
  15972. }
  15973. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  15974. // Trailing dots must be normalized on BOTH sides — host and entry.
  15975. // An implementation that only strips the host-side trailing dot would
  15976. // fail to match host "example.com" against entry "example.com." because
  15977. // a literal substring search would compare 11 chars against 12.
  15978. ProxyAndTargetServers s;
  15979. auto cli = make_client("example.com", s);
  15980. cli->set_no_proxy({"example.com."});
  15981. auto res = cli->Get("/");
  15982. ASSERT_TRUE(res);
  15983. EXPECT_EQ(0, s.proxy_hits());
  15984. EXPECT_EQ(1, s.target_hits());
  15985. }
  15986. TEST(NoProxyTest, WildcardBypassesEverything) {
  15987. ProxyAndTargetServers s;
  15988. auto cli = make_client("anything.invalid.test", s);
  15989. cli->set_no_proxy({"*"});
  15990. auto res = cli->Get("/");
  15991. ASSERT_TRUE(res);
  15992. EXPECT_EQ(0, s.proxy_hits());
  15993. EXPECT_EQ(1, s.target_hits());
  15994. }
  15995. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  15996. ProxyAndTargetServers s;
  15997. Client cli("127.0.0.1", s.target_port());
  15998. cli.set_proxy("127.0.0.1", s.proxy_port());
  15999. cli.set_no_proxy({"127.0.0.1"});
  16000. auto res = cli.Get("/");
  16001. ASSERT_TRUE(res);
  16002. EXPECT_EQ(0, s.proxy_hits());
  16003. EXPECT_EQ(1, s.target_hits());
  16004. }
  16005. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16006. ProxyAndTargetServers s;
  16007. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16008. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16009. cli.set_proxy("127.0.0.1", s.proxy_port());
  16010. cli.set_no_proxy({"::1"});
  16011. auto res = cli.Get("/");
  16012. ASSERT_TRUE(res);
  16013. EXPECT_EQ(0, s.proxy_hits());
  16014. EXPECT_EQ(1, s.target_hits());
  16015. }
  16016. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16017. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16018. // must still be recognized as IPv6 for CIDR matching. Implementations
  16019. // that detect IPv6 only when the host begins with '[' would parse the
  16020. // host as a hostname and miss the match.
  16021. ProxyAndTargetServers s;
  16022. Client cli("fe80::1", s.target_port());
  16023. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16024. cli.set_proxy("127.0.0.1", s.proxy_port());
  16025. cli.set_no_proxy({"fe80::/10"});
  16026. auto res = cli.Get("/");
  16027. ASSERT_TRUE(res);
  16028. EXPECT_EQ(0, s.proxy_hits());
  16029. EXPECT_EQ(1, s.target_hits());
  16030. }
  16031. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16032. ProxyAndTargetServers s;
  16033. Client cli("::1", s.target_port());
  16034. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16035. cli.set_proxy("127.0.0.1", s.proxy_port());
  16036. cli.set_no_proxy({"[::1]"});
  16037. auto res = cli.Get("/");
  16038. ASSERT_TRUE(res);
  16039. EXPECT_EQ(0, s.proxy_hits());
  16040. EXPECT_EQ(1, s.target_hits());
  16041. }
  16042. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16043. ProxyAndTargetServers s;
  16044. Client cli("fe80::1", s.target_port());
  16045. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16046. cli.set_proxy("127.0.0.1", s.proxy_port());
  16047. cli.set_no_proxy({"[fe80::]/10"});
  16048. auto res = cli.Get("/");
  16049. ASSERT_TRUE(res);
  16050. EXPECT_EQ(0, s.proxy_hits());
  16051. EXPECT_EQ(1, s.target_hits());
  16052. }
  16053. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16054. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16055. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16056. // tricks via address-family conversion.
  16057. ProxyAndTargetServers s;
  16058. Client cli("::ffff:127.0.0.1", s.target_port());
  16059. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16060. cli.set_proxy("127.0.0.1", s.proxy_port());
  16061. cli.set_no_proxy({"127.0.0.1"});
  16062. auto res = cli.Get("/");
  16063. ASSERT_TRUE(res);
  16064. EXPECT_GE(s.proxy_hits(), 1);
  16065. EXPECT_EQ(0, s.target_hits());
  16066. }
  16067. TEST(NoProxyTest, IPv4CidrMatch) {
  16068. ProxyAndTargetServers s;
  16069. Client cli("127.0.0.1", s.target_port());
  16070. cli.set_proxy("127.0.0.1", s.proxy_port());
  16071. cli.set_no_proxy({"127.0.0.0/8"});
  16072. auto res = cli.Get("/");
  16073. ASSERT_TRUE(res);
  16074. EXPECT_EQ(0, s.proxy_hits());
  16075. EXPECT_EQ(1, s.target_hits());
  16076. }
  16077. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16078. ProxyAndTargetServers s;
  16079. Client cli("127.0.0.1", s.target_port());
  16080. cli.set_proxy("127.0.0.1", s.proxy_port());
  16081. cli.set_no_proxy({"10.0.0.0/8"});
  16082. auto res = cli.Get("/");
  16083. ASSERT_TRUE(res);
  16084. EXPECT_GE(s.proxy_hits(), 1);
  16085. EXPECT_EQ(0, s.target_hits());
  16086. }
  16087. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16088. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16089. // IPv4 target matches.
  16090. ProxyAndTargetServers s;
  16091. Client cli("127.0.0.1", s.target_port());
  16092. cli.set_proxy("127.0.0.1", s.proxy_port());
  16093. cli.set_no_proxy({"0.0.0.0/0"});
  16094. auto res = cli.Get("/");
  16095. ASSERT_TRUE(res);
  16096. EXPECT_EQ(0, s.proxy_hits());
  16097. EXPECT_EQ(1, s.target_hits());
  16098. }
  16099. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16100. ProxyAndTargetServers s;
  16101. Client cli("127.0.0.1", s.target_port());
  16102. cli.set_proxy("127.0.0.1", s.proxy_port());
  16103. cli.set_no_proxy({"127.0.0.1"});
  16104. auto res = cli.Get("/");
  16105. ASSERT_TRUE(res);
  16106. EXPECT_EQ(0, s.proxy_hits());
  16107. EXPECT_EQ(1, s.target_hits());
  16108. }
  16109. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16110. ProxyAndTargetServers s;
  16111. Client cli("127.0.0.1", s.target_port());
  16112. cli.set_proxy("127.0.0.1", s.proxy_port());
  16113. cli.set_no_proxy({"127.0.0.0/33"});
  16114. auto res = cli.Get("/");
  16115. ASSERT_TRUE(res);
  16116. EXPECT_GE(s.proxy_hits(), 1);
  16117. EXPECT_EQ(0, s.target_hits());
  16118. }
  16119. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16120. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16121. ProxyAndTargetServers s;
  16122. Client cli("127.0.0.1", s.target_port());
  16123. cli.set_proxy("127.0.0.1", s.proxy_port());
  16124. cli.set_no_proxy({"127.0.0.1/"});
  16125. auto res = cli.Get("/");
  16126. ASSERT_TRUE(res);
  16127. EXPECT_GE(s.proxy_hits(), 1);
  16128. EXPECT_EQ(0, s.target_hits());
  16129. }
  16130. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16131. ProxyAndTargetServers s;
  16132. auto cli = make_client("internal.corp", s);
  16133. cli->set_proxy_basic_auth("u", "p");
  16134. cli->set_no_proxy({"internal.corp"});
  16135. auto res = cli->Get("/");
  16136. ASSERT_TRUE(res);
  16137. EXPECT_EQ(1, s.target_hits());
  16138. EXPECT_EQ(0, s.proxy_hits());
  16139. EXPECT_FALSE(s.last_had_proxy_authz())
  16140. << "Proxy-Authorization must not be sent direct to the target";
  16141. }
  16142. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16143. ProxyAndTargetServers s;
  16144. auto cli = make_client("public.example", s);
  16145. cli->set_proxy_basic_auth("u", "p");
  16146. cli->set_no_proxy({"internal.corp"}); // does not match
  16147. auto res = cli->Get("/");
  16148. ASSERT_TRUE(res);
  16149. EXPECT_GE(s.proxy_hits(), 1);
  16150. EXPECT_TRUE(s.last_had_proxy_authz());
  16151. }
  16152. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16153. ProxyAndTargetServers s;
  16154. auto cli = make_client("anything.test", s);
  16155. auto res = cli->Get("/");
  16156. ASSERT_TRUE(res);
  16157. EXPECT_GE(s.proxy_hits(), 1);
  16158. EXPECT_EQ(0, s.target_hits());
  16159. }
  16160. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16161. ProxyAndTargetServers s;
  16162. auto cli = make_client("example.com", s);
  16163. cli->set_no_proxy({"example.com:8080"});
  16164. auto res = cli->Get("/");
  16165. ASSERT_TRUE(res);
  16166. EXPECT_GE(s.proxy_hits(), 1);
  16167. EXPECT_EQ(0, s.target_hits());
  16168. }
  16169. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16170. ProxyAndTargetServers s;
  16171. auto cli = make_client("anything.test", s);
  16172. cli->set_no_proxy({"", " ", "\t"});
  16173. auto res = cli->Get("/");
  16174. ASSERT_TRUE(res);
  16175. EXPECT_GE(s.proxy_hits(), 1);
  16176. EXPECT_EQ(0, s.target_hits());
  16177. }
  16178. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16179. // An entry with leading/trailing whitespace must still match — env-style
  16180. // values are commonly pasted with stray spaces and an implementation
  16181. // that feeds the raw token directly to inet_pton would fail to match
  16182. // valid CIDRs because of the spaces.
  16183. ProxyAndTargetServers s;
  16184. Client cli("127.0.0.1", s.target_port());
  16185. cli.set_proxy("127.0.0.1", s.proxy_port());
  16186. cli.set_no_proxy({" 127.0.0.0/8 "});
  16187. auto res = cli.Get("/");
  16188. ASSERT_TRUE(res);
  16189. EXPECT_EQ(0, s.proxy_hits());
  16190. EXPECT_EQ(1, s.target_hits());
  16191. }
  16192. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16193. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16194. // go direct and must NOT carry Proxy-Authorization.
  16195. std::atomic<int> proxy_hits{0};
  16196. std::atomic<int> target_hits{0};
  16197. std::atomic<bool> target_saw_authz{false};
  16198. no_proxy_test::ScopedServer proxy_mock, target;
  16199. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16200. proxy_hits++;
  16201. res.status = 302;
  16202. res.set_header("Location", "http://127.0.0.1:" +
  16203. std::to_string(target.port()) + "/landed");
  16204. });
  16205. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16206. target_hits++;
  16207. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16208. res.set_content("direct", "text/plain");
  16209. });
  16210. proxy_mock.listen();
  16211. target.listen();
  16212. Client cli("public.example", target.port());
  16213. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16214. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16215. cli.set_proxy_basic_auth("u", "p");
  16216. cli.set_no_proxy({"127.0.0.1"});
  16217. cli.set_follow_location(true);
  16218. auto res = cli.Get("/redir");
  16219. ASSERT_TRUE(res);
  16220. EXPECT_GE(proxy_hits.load(), 1);
  16221. EXPECT_GE(target_hits.load(), 1);
  16222. EXPECT_FALSE(target_saw_authz.load());
  16223. }
  16224. #ifdef CPPHTTPLIB_SSL_ENABLED
  16225. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16226. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16227. // proxy creds would be sent to the (possibly hostile) origin.
  16228. std::atomic<int> target_hits{0};
  16229. std::atomic<bool> target_saw_proxy_authz{false};
  16230. no_proxy_test::ScopedServer target;
  16231. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16232. target_hits++;
  16233. if (req.has_header("Proxy-Authorization")) {
  16234. target_saw_proxy_authz = true;
  16235. }
  16236. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16237. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16238. "nonce=\"abc\", algorithm=MD5");
  16239. });
  16240. target.listen();
  16241. // The proxy address is set to the target's port: the bypass MUST kick in;
  16242. // if it doesn't, the test still routes "via proxy" to the same server and
  16243. // the Proxy-Authorization assertion below catches the leak.
  16244. Client cli("evil.example", target.port());
  16245. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16246. cli.set_proxy("127.0.0.1", target.port());
  16247. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16248. cli.set_no_proxy({"evil.example"});
  16249. auto res = cli.Get("/x");
  16250. ASSERT_TRUE(res);
  16251. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16252. EXPECT_EQ(1, target_hits.load());
  16253. EXPECT_FALSE(target_saw_proxy_authz.load());
  16254. }
  16255. #endif
  16256. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16257. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16258. std::atomic<int> proxy_hits{0};
  16259. std::atomic<int> bypass_hits{0};
  16260. std::atomic<bool> proxy_saw_c_url{false};
  16261. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16262. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16263. proxy_hits++;
  16264. if (req.path.find("/start") != std::string::npos) {
  16265. res.status = 302;
  16266. res.set_header("Location", "http://127.0.0.1:" +
  16267. std::to_string(bypass_server.port()) +
  16268. "/middle");
  16269. return;
  16270. }
  16271. if (req.path.find("/end") != std::string::npos) {
  16272. proxy_saw_c_url = true;
  16273. res.set_content("c-via-proxy", "text/plain");
  16274. return;
  16275. }
  16276. res.set_content("unexpected", "text/plain");
  16277. });
  16278. // public.example's "advertised" port is arbitrary (the request never lands
  16279. // there — it goes through the proxy), but use a dynamic value to stay
  16280. // friendly with sharded parallel runs.
  16281. int public_port = bypass_server.port();
  16282. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16283. bypass_hits++;
  16284. res.status = 302;
  16285. res.set_header("Location", "http://public.example:" +
  16286. std::to_string(public_port) + "/end");
  16287. });
  16288. proxy_mock.listen();
  16289. bypass_server.listen();
  16290. Client cli("public.example", public_port);
  16291. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16292. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16293. cli.set_no_proxy({"127.0.0.1"});
  16294. cli.set_follow_location(true);
  16295. auto res = cli.Get("/start");
  16296. ASSERT_TRUE(res);
  16297. EXPECT_EQ(StatusCode::OK_200, res->status);
  16298. EXPECT_EQ("c-via-proxy", res->body);
  16299. EXPECT_GE(proxy_hits.load(), 2);
  16300. EXPECT_GE(bypass_hits.load(), 1);
  16301. EXPECT_TRUE(proxy_saw_c_url.load());
  16302. }
  16303. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16304. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16305. // request reconnects to the correct endpoint.
  16306. std::atomic<int> proxy_hits{0};
  16307. std::atomic<int> target_hits{0};
  16308. no_proxy_test::ScopedServer proxy_mock, target;
  16309. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16310. proxy_hits++;
  16311. res.set_content("via-proxy", "text/plain");
  16312. });
  16313. target.svr().Get(".*", [&](const Request &, Response &res) {
  16314. target_hits++;
  16315. res.set_content("direct", "text/plain");
  16316. });
  16317. proxy_mock.listen();
  16318. target.listen();
  16319. Client cli("public.example", target.port());
  16320. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16321. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16322. cli.set_keep_alive(true);
  16323. auto res1 = cli.Get("/a");
  16324. ASSERT_TRUE(res1);
  16325. EXPECT_EQ("via-proxy", res1->body);
  16326. EXPECT_EQ(1, proxy_hits.load());
  16327. EXPECT_EQ(0, target_hits.load());
  16328. cli.set_no_proxy({"public.example"});
  16329. auto res2 = cli.Get("/b");
  16330. ASSERT_TRUE(res2);
  16331. EXPECT_EQ("direct", res2->body);
  16332. EXPECT_EQ(1, proxy_hits.load());
  16333. EXPECT_EQ(1, target_hits.load());
  16334. }
  16335. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16336. namespace proxy_tunnel_test {
  16337. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16338. class ScopedSSLServer {
  16339. public:
  16340. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16341. port_ = svr_.bind_to_any_port("127.0.0.1");
  16342. }
  16343. ~ScopedSSLServer() {
  16344. svr_.stop();
  16345. if (th_.joinable()) { th_.join(); }
  16346. }
  16347. SSLServer &svr() { return svr_; }
  16348. int port() const { return port_; }
  16349. void listen() {
  16350. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16351. svr_.wait_until_ready();
  16352. }
  16353. private:
  16354. SSLServer svr_;
  16355. std::thread th_;
  16356. int port_ = 0;
  16357. };
  16358. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16359. class ScopedConnectProxy {
  16360. public:
  16361. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16362. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16363. if (listen_fd_ < 0) { return; }
  16364. int yes = 1;
  16365. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16366. sockaddr_in a{};
  16367. a.sin_family = AF_INET;
  16368. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16369. a.sin_port = 0;
  16370. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16371. return;
  16372. }
  16373. socklen_t alen = sizeof(a);
  16374. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16375. 0) {
  16376. return;
  16377. }
  16378. port_ = ntohs(a.sin_port);
  16379. if (::listen(listen_fd_, 1) != 0) { return; }
  16380. th_ = std::thread([this] { run(); });
  16381. }
  16382. ~ScopedConnectProxy() {
  16383. stop_ = true;
  16384. if (listen_fd_ >= 0) {
  16385. ::shutdown(listen_fd_, SHUT_RDWR);
  16386. ::close(listen_fd_);
  16387. }
  16388. if (th_.joinable()) { th_.join(); }
  16389. }
  16390. int port() const { return port_; }
  16391. int connect_hits() const { return connect_hits_.load(); }
  16392. private:
  16393. void run() {
  16394. while (!stop_.load()) {
  16395. fd_set rfds;
  16396. FD_ZERO(&rfds);
  16397. FD_SET(listen_fd_, &rfds);
  16398. timeval tv{0, 100 * 1000};
  16399. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16400. if (sel <= 0) { continue; }
  16401. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16402. if (client_fd < 0) { continue; }
  16403. std::string req;
  16404. char buf[2048];
  16405. while (req.find("\r\n\r\n") == std::string::npos) {
  16406. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16407. if (n <= 0) { break; }
  16408. req.append(buf, static_cast<size_t>(n));
  16409. }
  16410. if (req.compare(0, 7, "CONNECT") != 0) {
  16411. ::close(client_fd);
  16412. continue;
  16413. }
  16414. connect_hits_++;
  16415. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16416. ::send(client_fd, ok, std::strlen(ok), 0);
  16417. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16418. sockaddr_in o{};
  16419. o.sin_family = AF_INET;
  16420. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16421. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16422. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16423. 0) {
  16424. ::close(client_fd);
  16425. ::close(origin_fd);
  16426. continue;
  16427. }
  16428. auto forward = [](int from, int to) {
  16429. char b[8192];
  16430. for (;;) {
  16431. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16432. if (n <= 0) { break; }
  16433. ssize_t off = 0;
  16434. while (off < n) {
  16435. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16436. if (s <= 0) {
  16437. off = n;
  16438. break;
  16439. }
  16440. off += s;
  16441. }
  16442. }
  16443. ::shutdown(to, SHUT_WR);
  16444. };
  16445. std::thread t1([&] { forward(client_fd, origin_fd); });
  16446. std::thread t2([&] { forward(origin_fd, client_fd); });
  16447. t1.join();
  16448. t2.join();
  16449. ::close(client_fd);
  16450. ::close(origin_fd);
  16451. }
  16452. }
  16453. int forward_port_ = -1;
  16454. int listen_fd_ = -1;
  16455. int port_ = 0;
  16456. std::thread th_;
  16457. std::atomic<bool> stop_{false};
  16458. std::atomic<int> connect_hits_{0};
  16459. };
  16460. } // namespace proxy_tunnel_test
  16461. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  16462. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  16463. // retry; otherwise proxy creds would be sent to the origin.
  16464. std::atomic<int> origin_hits{0};
  16465. std::atomic<bool> origin_saw_proxy_authz{false};
  16466. proxy_tunnel_test::ScopedSSLServer origin;
  16467. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  16468. origin_hits++;
  16469. if (req.has_header("Proxy-Authorization")) {
  16470. origin_saw_proxy_authz = true;
  16471. }
  16472. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16473. res.set_header("Proxy-Authenticate",
  16474. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  16475. "algorithm=MD5");
  16476. });
  16477. origin.listen();
  16478. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  16479. ASSERT_NE(0, proxy.port());
  16480. SSLClient cli(HOST, origin.port());
  16481. cli.enable_server_certificate_verification(false);
  16482. cli.set_proxy(HOST, proxy.port());
  16483. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16484. auto res = cli.Get("/x");
  16485. ASSERT_TRUE(res);
  16486. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16487. EXPECT_EQ(1, origin_hits.load());
  16488. EXPECT_FALSE(origin_saw_proxy_authz.load());
  16489. EXPECT_EQ(1, proxy.connect_hits());
  16490. }
  16491. #endif