test.cc 616 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974
  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_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  38. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  39. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  40. #define CA_CERT_FILE "./ca-bundle.crt"
  41. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  42. #define CLIENT_CA_CERT_DIR "."
  43. #define CLIENT_CERT_FILE "./client.cert.pem"
  44. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  45. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  46. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  47. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  48. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  49. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  50. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  51. #ifdef CPPHTTPLIB_SSL_ENABLED
  52. namespace httplib {
  53. namespace tls {
  54. // Declared here for the split build, where the TLS abstraction declarations
  55. // live below the split border; the definition is linked from httplib.cc.
  56. ca_store_t create_ca_store(const char *pem, size_t len);
  57. } // namespace tls
  58. } // namespace httplib
  59. #endif
  60. using namespace std;
  61. using namespace httplib;
  62. const char *HOST = "localhost";
  63. static int get_base_port() {
  64. const char *shard = getenv("GTEST_SHARD_INDEX");
  65. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  66. }
  67. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  68. // New standalone tests MUST use svr.bind_to_any_port() instead.
  69. const int PORT = get_base_port();
  70. const string LONG_QUERY_VALUE = string(25000, '@');
  71. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  72. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  73. const string TOO_LONG_QUERY_URL =
  74. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  75. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  76. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  77. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  78. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  79. return file.name == key;
  80. });
  81. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  82. return *it;
  83. #else
  84. if (it != items.end()) { return *it; }
  85. throw std::runtime_error("invalid multipart form data name error");
  86. #endif
  87. }
  88. static void read_file(const std::string &path, std::string &out) {
  89. std::ifstream fs(path, std::ios_base::binary);
  90. if (!fs) {
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return;
  93. #else
  94. throw std::runtime_error("File not found: " + path);
  95. #endif
  96. }
  97. fs.seekg(0, std::ios_base::end);
  98. auto size = fs.tellg();
  99. fs.seekg(0);
  100. out.resize(static_cast<size_t>(size));
  101. fs.read(&out[0], static_cast<std::streamsize>(size));
  102. }
  103. class UnixSocketTest : public ::testing::Test {
  104. protected:
  105. void TearDown() override { std::remove(pathname_.c_str()); }
  106. void client_GET(const std::string &addr) {
  107. httplib::Client cli{addr};
  108. cli.set_address_family(AF_UNIX);
  109. ASSERT_TRUE(cli.is_valid());
  110. const auto &result = cli.Get(pattern_);
  111. ASSERT_TRUE(result) << "error: " << result.error();
  112. const auto &resp = result.value();
  113. EXPECT_EQ(resp.status, StatusCode::OK_200);
  114. EXPECT_EQ(resp.body, content_);
  115. }
  116. static std::string make_sock_path() {
  117. const char *shard = getenv("GTEST_SHARD_INDEX");
  118. return shard ? std::string("./httplib-server-") + shard + ".sock"
  119. : "./httplib-server.sock";
  120. }
  121. const std::string pathname_{make_sock_path()};
  122. const std::string pattern_{"/hi"};
  123. const std::string content_{"Hello World!"};
  124. };
  125. TEST_F(UnixSocketTest, pathname) {
  126. httplib::Server svr;
  127. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  128. res.set_content(content_, "text/plain");
  129. });
  130. std::thread t{[&] {
  131. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  132. }};
  133. auto se = detail::scope_exit([&] {
  134. svr.stop();
  135. t.join();
  136. ASSERT_FALSE(svr.is_running());
  137. });
  138. svr.wait_until_ready();
  139. ASSERT_TRUE(svr.is_running());
  140. client_GET(pathname_);
  141. }
  142. #if defined(__linux__) || \
  143. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  144. TEST_F(UnixSocketTest, PeerPid) {
  145. httplib::Server svr;
  146. std::string remote_port_val;
  147. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  148. res.set_content(content_, "text/plain");
  149. remote_port_val = std::to_string(req.remote_port);
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  163. }
  164. #endif
  165. #ifdef __linux__
  166. TEST_F(UnixSocketTest, abstract) {
  167. constexpr char svr_path[]{"\x00httplib-server.sock"};
  168. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  169. httplib::Server svr;
  170. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  171. res.set_content(content_, "text/plain");
  172. });
  173. std::thread t{[&] {
  174. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  175. }};
  176. auto se = detail::scope_exit([&] {
  177. svr.stop();
  178. t.join();
  179. ASSERT_FALSE(svr.is_running());
  180. });
  181. svr.wait_until_ready();
  182. ASSERT_TRUE(svr.is_running());
  183. client_GET(abstract_addr);
  184. }
  185. #endif
  186. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  187. httplib::Server svr;
  188. std::string received_host_header;
  189. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  190. // Capture the Host header sent by the client
  191. auto host_iter = req.headers.find("Host");
  192. if (host_iter != req.headers.end()) {
  193. received_host_header = host_iter->second;
  194. }
  195. res.set_content(content_, "text/plain");
  196. });
  197. std::thread t{[&] {
  198. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  199. }};
  200. auto se = detail::scope_exit([&] {
  201. svr.stop();
  202. t.join();
  203. ASSERT_FALSE(svr.is_running());
  204. });
  205. svr.wait_until_ready();
  206. ASSERT_TRUE(svr.is_running());
  207. // Test that Host header is automatically set to "localhost" for Unix socket
  208. // connections
  209. httplib::Client cli{pathname_};
  210. cli.set_address_family(AF_UNIX);
  211. ASSERT_TRUE(cli.is_valid());
  212. const auto &result = cli.Get(pattern_);
  213. ASSERT_TRUE(result) << "error: " << result.error();
  214. const auto &resp = result.value();
  215. EXPECT_EQ(resp.status, StatusCode::OK_200);
  216. EXPECT_EQ(resp.body, content_);
  217. // Verify that Host header was automatically set to "localhost"
  218. EXPECT_EQ(received_host_header, "localhost");
  219. }
  220. #ifndef _WIN32
  221. TEST(SocketStream, wait_writable_UNIX) {
  222. int fds[2];
  223. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  224. const auto asSocketStream = [&](socket_t fd,
  225. std::function<bool(Stream &)> func) {
  226. return detail::process_client_socket(
  227. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  228. };
  229. asSocketStream(fds[0], [&](Stream &s0) {
  230. EXPECT_EQ(s0.socket(), fds[0]);
  231. EXPECT_TRUE(s0.wait_writable());
  232. EXPECT_TRUE(s0.is_peer_alive());
  233. EXPECT_EQ(0, close(fds[1]));
  234. EXPECT_FALSE(s0.is_peer_alive());
  235. return true;
  236. });
  237. EXPECT_EQ(0, close(fds[0]));
  238. }
  239. TEST(SocketStream, wait_writable_INET) {
  240. sockaddr_in addr;
  241. memset(&addr, 0, sizeof(addr));
  242. addr.sin_family = AF_INET;
  243. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  244. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  245. int disconnected_svr_sock = -1;
  246. std::thread svr{[&] {
  247. const int s = socket(AF_INET, SOCK_STREAM, 0);
  248. ASSERT_LE(0, s);
  249. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  250. ASSERT_EQ(0, listen(s, 1));
  251. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  252. ASSERT_EQ(0, close(s));
  253. }};
  254. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  255. std::thread cli{[&] {
  256. const int s = socket(AF_INET, SOCK_STREAM, 0);
  257. ASSERT_LE(0, s);
  258. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  259. ASSERT_EQ(0, close(s));
  260. }};
  261. cli.join();
  262. svr.join();
  263. ASSERT_NE(disconnected_svr_sock, -1);
  264. const auto asSocketStream = [&](socket_t fd,
  265. std::function<bool(Stream &)> func) {
  266. return detail::process_client_socket(
  267. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  268. };
  269. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  270. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  271. // wait_writable() returns true because select_write() only checks if the
  272. // send buffer has space. Peer disconnection is detected later by send().
  273. EXPECT_TRUE(ss.wait_writable());
  274. return true;
  275. });
  276. ASSERT_EQ(0, close(disconnected_svr_sock));
  277. }
  278. #endif // #ifndef _WIN32
  279. TEST(SetSocketOptTest, TcpNoDelay) {
  280. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  281. ASSERT_NE(sock, INVALID_SOCKET);
  282. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  283. int val = 0;
  284. socklen_t len = sizeof(val);
  285. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  286. reinterpret_cast<char *>(&val), &len));
  287. EXPECT_NE(val, 0);
  288. detail::close_socket(sock);
  289. }
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. U8("descrip=Gastos áéíóúñÑ 6"));
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(DecodePathTest, UnicodeEncoding) {
  319. // %u0041 = 'A' (1-byte UTF-8)
  320. EXPECT_EQ("A", decode_path_component("%u0041"));
  321. // %u00E9 = 'é' (2-byte UTF-8)
  322. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  323. // %u3042 = 'あ' (3-byte UTF-8)
  324. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  325. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  326. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  327. // %uD800 = surrogate (invalid, silently dropped)
  328. EXPECT_EQ("", decode_path_component("%uD800"));
  329. }
  330. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  331. // A sign or whitespace inside the two-character escape window must not be
  332. // accepted as a valid percent-encoding; the sequence is passed through
  333. // literally, matching decode_uri_component / decode_path_component.
  334. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  335. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  336. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  337. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  338. // Well-formed escapes still decode.
  339. EXPECT_EQ("-", decode_query_component("%2D", false));
  340. EXPECT_EQ("A", decode_query_component("%41", false));
  341. }
  342. TEST(SanitizeFilenameTest, VariousPatterns) {
  343. // Path traversal
  344. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  345. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  346. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  347. // Normal and edge cases
  348. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  349. EXPECT_EQ("filename.txt",
  350. httplib::sanitize_filename("/path/to/filename.txt"));
  351. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  352. EXPECT_EQ("", httplib::sanitize_filename(".."));
  353. EXPECT_EQ("", httplib::sanitize_filename(""));
  354. // Null bytes stripped
  355. EXPECT_EQ("safe.txt",
  356. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  357. // Whitespace-only rejected
  358. EXPECT_EQ("", httplib::sanitize_filename(" "));
  359. }
  360. // Forward declaration: in split builds split.py strips `inline` and moves the
  361. // definition into httplib.cc, so detail::base64_encode is not visible from the
  362. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  363. // in both header-only and split builds.
  364. namespace httplib {
  365. namespace detail {
  366. std::string base64_encode(const std::string &in);
  367. } // namespace detail
  368. } // namespace httplib
  369. TEST(Base64EncodeTest, KnownAnswers) {
  370. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  371. // where the accumulator's top bit is already set before the next shift.
  372. EXPECT_EQ("", detail::base64_encode(""));
  373. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  374. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  375. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  376. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  377. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  378. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  379. // High bytes keep the top bit set across several rounds.
  380. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  381. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  382. }
  383. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  384. string unescapedCharacters = "-_.!~*'()";
  385. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  386. }
  387. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  388. string reservedCharacters = ";,/?:@&=+$";
  389. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  390. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  391. }
  392. TEST(ClientQueryOrder, PreserveOrder) {
  393. // This test reproduces Issue #2259: client may reorder query parameters
  394. // when sending a GET request. The expected behavior is that the client
  395. // preserves the original query string order when the caller supplied it
  396. // as part of the path.
  397. Server svr;
  398. svr.Get("/", [&](const Request &req, Response &res) {
  399. // Echo back the raw target so the test can assert ordering
  400. res.set_content(req.target, "text/plain");
  401. });
  402. std::thread t{[&] { svr.listen(HOST, PORT); }};
  403. auto se = detail::scope_exit([&] {
  404. svr.stop();
  405. t.join();
  406. ASSERT_FALSE(svr.is_running());
  407. });
  408. svr.wait_until_ready();
  409. Client cli(HOST, PORT);
  410. ASSERT_TRUE(cli.is_valid());
  411. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  412. auto res = cli.Get(original);
  413. ASSERT_TRUE(res);
  414. // Expect the echoed target to exactly match the original path (order
  415. // preserved)
  416. EXPECT_EQ(res->body, original);
  417. }
  418. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  419. string chineseCharacters = U8("中国語");
  420. string russianCharacters = U8("дом");
  421. string brazilianCharacters = U8("óculos");
  422. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  423. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  424. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  425. "%D0%B4%D0%BE%D0%BC");
  426. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  427. }
  428. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  429. string unescapedCharacters = "-_.!~*'()";
  430. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  431. }
  432. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  433. string reservedCharacters = ";,/?:@&=+$";
  434. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  435. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  436. }
  437. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  438. string chineseCharacters = U8("中国語");
  439. string russianCharacters = U8("дом");
  440. string brazilianCharacters = U8("óculos");
  441. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  442. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  443. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  444. "%D0%B4%D0%BE%D0%BC");
  445. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  446. }
  447. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  448. // Issue #2082 use case: encoding path component with ampersand
  449. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  450. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  451. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  452. }
  453. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  454. string unescapedCharacters = "-_.!~*'()";
  455. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  456. }
  457. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  458. string reservedCharacters = ";,/?:@&=+$#";
  459. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  460. }
  461. TEST(EncodeUriTest, TestUTF8Characters) {
  462. string chineseCharacters = U8("中国語");
  463. string russianCharacters = U8("дом");
  464. string brazilianCharacters = U8("óculos");
  465. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  466. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  467. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  468. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  469. }
  470. TEST(EncodeUriTest, TestCompleteUri) {
  471. string uri =
  472. "https://example.com/path/to/resource?query=value&param=test#fragment";
  473. EXPECT_EQ(
  474. httplib::encode_uri(uri),
  475. "https://example.com/path/to/resource?query=value&param=test#fragment");
  476. }
  477. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  478. string uri =
  479. "https://example.com/path with spaces/file name.html?q=hello world";
  480. EXPECT_EQ(httplib::encode_uri(uri),
  481. "https://example.com/path%20with%20spaces/"
  482. "file%20name.html?q=hello%20world");
  483. }
  484. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  485. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  486. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  487. }
  488. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  489. string unescapedCharacters = "-_.!~*'()";
  490. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  491. }
  492. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  493. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  494. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  495. string encodedBrazilian = "%C3%B3culos";
  496. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  497. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  498. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  499. }
  500. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  501. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  502. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  503. "Piri Tommy Villiers - on & on");
  504. }
  505. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  506. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  507. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  508. }
  509. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  510. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  511. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  512. }
  513. TEST(DecodeUriTest, TestUTF8Characters) {
  514. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  515. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  516. string encodedBrazilian = "%C3%B3culos";
  517. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  518. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  519. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  520. }
  521. TEST(DecodeUriTest, TestCompleteUri) {
  522. string encodedUri = "https://example.com/path%20with%20spaces/"
  523. "file%20name.html?q=hello%20world";
  524. EXPECT_EQ(
  525. httplib::decode_uri(encodedUri),
  526. "https://example.com/path with spaces/file name.html?q=hello world");
  527. }
  528. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  529. string original =
  530. "https://example.com/path with spaces/file name.html?q=hello world";
  531. string encoded = httplib::encode_uri(original);
  532. string decoded = httplib::decode_uri(encoded);
  533. EXPECT_EQ(decoded, original);
  534. }
  535. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  536. string original = "Piri Tommy Villiers - on & on";
  537. string encoded = httplib::encode_uri_component(original);
  538. string decoded = httplib::decode_uri_component(encoded);
  539. EXPECT_EQ(decoded, original);
  540. }
  541. TEST(TrimTests, TrimStringTests) {
  542. EXPECT_EQ("abc", detail::trim_copy("abc"));
  543. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  544. EXPECT_TRUE(detail::trim_copy("").empty());
  545. }
  546. TEST(FromCharsTest, Double) {
  547. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  548. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  549. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  550. auto parse = [](const std::string &s, double &v) {
  551. return detail::from_chars(s.data(), s.data() + s.size(), v);
  552. };
  553. double v = -1.0;
  554. // Representative quality values.
  555. EXPECT_EQ(parse("0", v).ec, std::errc{});
  556. EXPECT_DOUBLE_EQ(v, 0.0);
  557. EXPECT_EQ(parse("1", v).ec, std::errc{});
  558. EXPECT_DOUBLE_EQ(v, 1.0);
  559. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  560. EXPECT_DOUBLE_EQ(v, 0.8);
  561. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  562. EXPECT_DOUBLE_EQ(v, 0.001);
  563. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  564. EXPECT_DOUBLE_EQ(v, 1.0);
  565. // A missing integer or fractional part is tolerated.
  566. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  567. EXPECT_DOUBLE_EQ(v, 0.5);
  568. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  569. EXPECT_DOUBLE_EQ(v, 5.0);
  570. // Values outside [0, 1] still parse; the caller range-checks them.
  571. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  572. EXPECT_DOUBLE_EQ(v, 123.456);
  573. // Stops at the first byte that is not part of the number and reports where.
  574. std::string trailing = "0.9, text/html";
  575. auto r = parse(trailing, v);
  576. EXPECT_EQ(r.ec, std::errc{});
  577. EXPECT_DOUBLE_EQ(v, 0.9);
  578. EXPECT_EQ(*r.ptr, ',');
  579. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  580. // outright, and an 'e'/'E' simply ends the number.
  581. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  582. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  583. std::string exp_input = "1.5e3";
  584. r = parse(exp_input, v);
  585. EXPECT_EQ(r.ec, std::errc{});
  586. EXPECT_DOUBLE_EQ(v, 1.5);
  587. EXPECT_EQ(*r.ptr, 'e');
  588. // Invalid inputs.
  589. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  590. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  591. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  592. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  593. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  594. // Pathological but well-formed inputs must stay bounded (no overflow, no
  595. // out-of-bounds table access) and stay within [0, 1] for the caller.
  596. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  597. std::errc{});
  598. EXPECT_DOUBLE_EQ(v, 0.0);
  599. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  600. std::errc{});
  601. EXPECT_GE(v, 0.0);
  602. EXPECT_LE(v, 1.0);
  603. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  604. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  605. }
  606. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  607. // Simple case without quality values
  608. std::vector<std::string> result1;
  609. EXPECT_TRUE(detail::parse_accept_header(
  610. "text/html,application/json,text/plain", result1));
  611. EXPECT_EQ(result1.size(), 3U);
  612. EXPECT_EQ(result1[0], "text/html");
  613. EXPECT_EQ(result1[1], "application/json");
  614. EXPECT_EQ(result1[2], "text/plain");
  615. // With quality values
  616. std::vector<std::string> result2;
  617. EXPECT_TRUE(detail::parse_accept_header(
  618. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  619. EXPECT_EQ(result2.size(), 3U);
  620. EXPECT_EQ(result2[0], "application/json"); // highest q value
  621. EXPECT_EQ(result2[1], "text/html");
  622. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  623. }
  624. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  625. // Mixed with and without quality values
  626. std::vector<std::string> result;
  627. EXPECT_TRUE(detail::parse_accept_header(
  628. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  629. EXPECT_EQ(result.size(), 3U);
  630. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  631. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  632. EXPECT_EQ(result[2], "application/json"); // q=0.5
  633. }
  634. TEST(ParseAcceptHeaderTest, EdgeCases) {
  635. // Empty header
  636. std::vector<std::string> empty_result;
  637. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  638. EXPECT_TRUE(empty_result.empty());
  639. // Single type
  640. std::vector<std::string> single_result;
  641. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  642. EXPECT_EQ(single_result.size(), 1U);
  643. EXPECT_EQ(single_result[0], "application/json");
  644. // Wildcard types
  645. std::vector<std::string> wildcard_result;
  646. EXPECT_TRUE(detail::parse_accept_header(
  647. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  648. EXPECT_EQ(wildcard_result.size(), 3U);
  649. EXPECT_EQ(wildcard_result[0], "application/json");
  650. EXPECT_EQ(wildcard_result[1], "text/*");
  651. EXPECT_EQ(wildcard_result[2], "*/*");
  652. }
  653. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  654. // Common browser Accept header
  655. std::vector<std::string> browser_result;
  656. EXPECT_TRUE(
  657. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  658. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  659. browser_result));
  660. EXPECT_EQ(browser_result.size(), 6U);
  661. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  662. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  663. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  664. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  665. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  666. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  667. // API client header
  668. std::vector<std::string> api_result;
  669. EXPECT_TRUE(detail::parse_accept_header(
  670. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  671. api_result));
  672. EXPECT_EQ(api_result.size(), 3U);
  673. EXPECT_EQ(api_result[0], "application/json");
  674. EXPECT_EQ(api_result[1], "application/xml");
  675. EXPECT_EQ(api_result[2], "text/plain");
  676. }
  677. TEST(ParseAcceptHeaderTest, SpecialCases) {
  678. // Quality value with 3 decimal places
  679. std::vector<std::string> decimal_result;
  680. EXPECT_TRUE(detail::parse_accept_header(
  681. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  682. EXPECT_EQ(decimal_result.size(), 2U);
  683. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  684. EXPECT_EQ(decimal_result[1], "text/html");
  685. // Zero quality (should still be included but with lowest priority)
  686. std::vector<std::string> zero_q_result;
  687. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  688. zero_q_result));
  689. EXPECT_EQ(zero_q_result.size(), 2U);
  690. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  691. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  692. // No spaces around commas
  693. std::vector<std::string> no_space_result;
  694. EXPECT_TRUE(detail::parse_accept_header(
  695. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  696. no_space_result));
  697. EXPECT_EQ(no_space_result.size(), 3U);
  698. EXPECT_EQ(no_space_result[0], "text/html");
  699. EXPECT_EQ(no_space_result[1], "application/json");
  700. EXPECT_EQ(no_space_result[2], "text/plain");
  701. }
  702. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  703. // Quality values always use '.' as the decimal separator, so parsing must
  704. // not depend on the process locale. An embedding application may have
  705. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  706. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  707. std::string saved = cur ? cur : "C";
  708. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  709. "fr_FR.UTF-8"};
  710. bool switched = false;
  711. for (const auto loc : comma_locales) {
  712. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  713. std::localeconv()->decimal_point[0] == ',') {
  714. switched = true;
  715. break;
  716. }
  717. }
  718. if (!switched) {
  719. std::setlocale(LC_NUMERIC, saved.c_str());
  720. GTEST_SKIP() << "no comma-decimal locale available on this host";
  721. }
  722. // The higher-weighted type appears later in the list, so a correct parse
  723. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  724. // sensitive parse reads both weights as 0 and leaves the original order.
  725. std::vector<std::string> result;
  726. EXPECT_TRUE(detail::parse_accept_header(
  727. "application/json;q=0.1,text/html;q=0.9", result));
  728. ASSERT_EQ(result.size(), 2U);
  729. EXPECT_EQ(result[0], "text/html");
  730. EXPECT_EQ(result[1], "application/json");
  731. std::setlocale(LC_NUMERIC, saved.c_str());
  732. }
  733. TEST(ParseAcceptHeaderTest, InvalidCases) {
  734. std::vector<std::string> result;
  735. // Invalid quality value (> 1.0)
  736. EXPECT_FALSE(
  737. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  738. // Invalid quality value (< 0.0)
  739. EXPECT_FALSE(
  740. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  741. // Invalid quality value (not a number)
  742. EXPECT_FALSE(detail::parse_accept_header(
  743. "text/html;q=invalid,application/json", result));
  744. // Empty quality value
  745. EXPECT_FALSE(
  746. detail::parse_accept_header("text/html;q=,application/json", result));
  747. // Invalid media type format (no slash and not wildcard)
  748. EXPECT_FALSE(
  749. detail::parse_accept_header("invalidtype,application/json", result));
  750. // Empty media type
  751. result.clear();
  752. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  753. // Only commas
  754. result.clear();
  755. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  756. // Valid cases should still work
  757. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  758. EXPECT_EQ(result.size(), 1U);
  759. EXPECT_EQ(result[0], "*/*");
  760. EXPECT_TRUE(detail::parse_accept_header("*", result));
  761. EXPECT_EQ(result.size(), 1U);
  762. EXPECT_EQ(result[0], "*");
  763. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  764. EXPECT_EQ(result.size(), 1U);
  765. EXPECT_EQ(result[0], "text/*");
  766. }
  767. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  768. Server svr;
  769. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  770. EXPECT_EQ(req.accept_content_types.size(), 3U);
  771. EXPECT_EQ(req.accept_content_types[0], "application/json");
  772. EXPECT_EQ(req.accept_content_types[1], "text/html");
  773. EXPECT_EQ(req.accept_content_types[2], "*/*");
  774. res.set_content("ok", "text/plain");
  775. });
  776. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  777. EXPECT_TRUE(false);
  778. res.set_content("bad request", "text/plain");
  779. });
  780. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  781. auto se = detail::scope_exit([&] {
  782. svr.stop();
  783. listen_thread.join();
  784. ASSERT_FALSE(svr.is_running());
  785. });
  786. svr.wait_until_ready();
  787. Client cli("localhost", PORT);
  788. {
  789. auto res =
  790. cli.Get("/accept_ok",
  791. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  792. ASSERT_TRUE(res);
  793. EXPECT_EQ(StatusCode::OK_200, res->status);
  794. }
  795. {
  796. auto res = cli.Get("/accept_bad_request",
  797. {{"Accept", "text/html;q=abc,application/json"}});
  798. ASSERT_TRUE(res);
  799. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  800. }
  801. }
  802. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  803. Server svr;
  804. svr.Get("/", [](const Request & /*req*/, Response &res) {
  805. res.set_content("ok", "text/plain");
  806. });
  807. std::atomic<int> start_count{0};
  808. std::atomic<bool> running_when_called{false};
  809. svr.set_start_handler([&]() {
  810. running_when_called = svr.is_running();
  811. start_count++;
  812. });
  813. auto port = svr.bind_to_any_port(HOST);
  814. std::thread t([&]() { svr.listen_after_bind(); });
  815. auto se = detail::scope_exit([&] {
  816. svr.stop();
  817. t.join();
  818. ASSERT_FALSE(svr.is_running());
  819. });
  820. svr.wait_until_ready();
  821. // A successful request proves the accept loop is running, which the start
  822. // handler precedes; so by now the handler must have run exactly once.
  823. Client cli(HOST, port);
  824. cli.set_connection_timeout(std::chrono::seconds(5));
  825. auto res = cli.Get("/");
  826. ASSERT_TRUE(res);
  827. EXPECT_EQ(StatusCode::OK_200, res->status);
  828. EXPECT_EQ(1, start_count.load());
  829. EXPECT_TRUE(running_when_called.load());
  830. }
  831. TEST(DivideTest, DivideStringTests) {
  832. auto divide = [](const std::string &str, char d) {
  833. std::string lhs;
  834. std::string rhs;
  835. detail::divide(str, d,
  836. [&](const char *lhs_data, std::size_t lhs_size,
  837. const char *rhs_data, std::size_t rhs_size) {
  838. lhs.assign(lhs_data, lhs_size);
  839. rhs.assign(rhs_data, rhs_size);
  840. });
  841. return std::make_pair(std::move(lhs), std::move(rhs));
  842. };
  843. {
  844. const auto res = divide("", '=');
  845. EXPECT_EQ(res.first, "");
  846. EXPECT_EQ(res.second, "");
  847. }
  848. {
  849. const auto res = divide("=", '=');
  850. EXPECT_EQ(res.first, "");
  851. EXPECT_EQ(res.second, "");
  852. }
  853. {
  854. const auto res = divide(" ", '=');
  855. EXPECT_EQ(res.first, " ");
  856. EXPECT_EQ(res.second, "");
  857. }
  858. {
  859. const auto res = divide("a", '=');
  860. EXPECT_EQ(res.first, "a");
  861. EXPECT_EQ(res.second, "");
  862. }
  863. {
  864. const auto res = divide("a=", '=');
  865. EXPECT_EQ(res.first, "a");
  866. EXPECT_EQ(res.second, "");
  867. }
  868. {
  869. const auto res = divide("=b", '=');
  870. EXPECT_EQ(res.first, "");
  871. EXPECT_EQ(res.second, "b");
  872. }
  873. {
  874. const auto res = divide("a=b", '=');
  875. EXPECT_EQ(res.first, "a");
  876. EXPECT_EQ(res.second, "b");
  877. }
  878. {
  879. const auto res = divide("a=b=", '=');
  880. EXPECT_EQ(res.first, "a");
  881. EXPECT_EQ(res.second, "b=");
  882. }
  883. {
  884. const auto res = divide("a=b=c", '=');
  885. EXPECT_EQ(res.first, "a");
  886. EXPECT_EQ(res.second, "b=c");
  887. }
  888. }
  889. TEST(SplitTest, ParseQueryString) {
  890. string s = "key1=val1&key2=val2&key3=val3";
  891. Params dic;
  892. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  893. [&](const char *b, const char *e) {
  894. string key, val;
  895. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  896. if (key.empty()) {
  897. key.assign(b2, e2);
  898. } else {
  899. val.assign(b2, e2);
  900. }
  901. });
  902. dic.emplace(key, val);
  903. });
  904. EXPECT_EQ("val1", dic.find("key1")->second);
  905. EXPECT_EQ("val2", dic.find("key2")->second);
  906. EXPECT_EQ("val3", dic.find("key3")->second);
  907. }
  908. TEST(SplitTest, ParseInvalidQueryTests) {
  909. {
  910. string s = " ";
  911. Params dict;
  912. detail::parse_query_text(s, dict);
  913. EXPECT_TRUE(dict.empty());
  914. }
  915. {
  916. string s = " = =";
  917. Params dict;
  918. detail::parse_query_text(s, dict);
  919. EXPECT_TRUE(dict.empty());
  920. }
  921. }
  922. TEST(ParseQueryTest, ParseQueryString) {
  923. {
  924. std::string s = "key1=val1&key2=val2&key3=val3";
  925. Params dic;
  926. detail::parse_query_text(s, dic);
  927. EXPECT_EQ("val1", dic.find("key1")->second);
  928. EXPECT_EQ("val2", dic.find("key2")->second);
  929. EXPECT_EQ("val3", dic.find("key3")->second);
  930. }
  931. {
  932. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  933. Params dic;
  934. detail::parse_query_text(s, dic);
  935. EXPECT_EQ("", dic.find("key1")->second);
  936. EXPECT_EQ("val1", dic.find("key2")->second);
  937. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  938. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  939. }
  940. }
  941. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  942. Params dic;
  943. EXPECT_EQ(detail::params_to_query_str(dic), "");
  944. dic.emplace("key1", "val1");
  945. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  946. dic.emplace("key2", "val2");
  947. dic.emplace("key3", "val3");
  948. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  949. }
  950. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  951. string content_type = "multipart/form-data; boundary=something";
  952. string boundary;
  953. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  954. EXPECT_TRUE(ret);
  955. EXPECT_EQ(boundary, "something");
  956. }
  957. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  958. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  959. string boundary;
  960. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  961. EXPECT_TRUE(ret);
  962. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  963. }
  964. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  965. string content_type =
  966. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  967. string boundary;
  968. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  969. EXPECT_TRUE(ret);
  970. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  971. }
  972. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  973. string content_type =
  974. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  975. string boundary;
  976. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  977. EXPECT_TRUE(ret);
  978. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  979. }
  980. TEST(GetHeaderValueTest, DefaultValue) {
  981. Headers headers = {{"Dummy", "Dummy"}};
  982. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  983. EXPECT_STREQ("text/plain", val);
  984. }
  985. TEST(GetHeaderValueTest, DefaultValueInt) {
  986. Headers headers = {{"Dummy", "Dummy"}};
  987. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  988. EXPECT_EQ(100ull, val);
  989. }
  990. TEST(GetHeaderValueTest, RegularValue) {
  991. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  992. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  993. EXPECT_STREQ("text/html", val);
  994. }
  995. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  996. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  997. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  998. EXPECT_STREQ("text/html", val);
  999. }
  1000. TEST(GetHeaderValueTest, SetContent) {
  1001. Response res;
  1002. res.set_content("html", "text/html");
  1003. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1004. res.set_content("text", "text/plain");
  1005. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1006. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1007. }
  1008. TEST(GetHeaderValueTest, RegularValueInt) {
  1009. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1010. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1011. EXPECT_EQ(100ull, val);
  1012. }
  1013. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1014. Headers headers = {{"Content-Length", "x"}};
  1015. auto is_invalid_value = false;
  1016. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1017. is_invalid_value);
  1018. EXPECT_EQ(0ull, val);
  1019. EXPECT_TRUE(is_invalid_value);
  1020. }
  1021. TEST(GetHeaderValueTest, Range) {
  1022. {
  1023. Headers headers = {make_range_header({{1, -1}})};
  1024. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1025. EXPECT_STREQ("bytes=1-", val);
  1026. }
  1027. {
  1028. Headers headers = {make_range_header({{-1, 1}})};
  1029. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1030. EXPECT_STREQ("bytes=-1", val);
  1031. }
  1032. {
  1033. Headers headers = {make_range_header({{1, 10}})};
  1034. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1035. EXPECT_STREQ("bytes=1-10", val);
  1036. }
  1037. {
  1038. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1039. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1040. EXPECT_STREQ("bytes=1-10, 100-", val);
  1041. }
  1042. {
  1043. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1044. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1045. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1046. }
  1047. {
  1048. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1049. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1050. EXPECT_STREQ("bytes=0-0, -1", val);
  1051. }
  1052. }
  1053. TEST(ParseHeaderValueTest, Range) {
  1054. {
  1055. Ranges ranges;
  1056. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1057. EXPECT_TRUE(ret);
  1058. EXPECT_EQ(1u, ranges.size());
  1059. EXPECT_EQ(1u, ranges[0].first);
  1060. EXPECT_EQ(-1, ranges[0].second);
  1061. }
  1062. {
  1063. Ranges ranges;
  1064. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1065. EXPECT_TRUE(ret);
  1066. EXPECT_EQ(1u, ranges.size());
  1067. EXPECT_EQ(-1, ranges[0].first);
  1068. EXPECT_EQ(1u, ranges[0].second);
  1069. }
  1070. {
  1071. Ranges ranges;
  1072. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1073. EXPECT_TRUE(ret);
  1074. EXPECT_EQ(1u, ranges.size());
  1075. EXPECT_EQ(1u, ranges[0].first);
  1076. EXPECT_EQ(10u, ranges[0].second);
  1077. }
  1078. {
  1079. Ranges ranges;
  1080. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1081. EXPECT_FALSE(ret);
  1082. }
  1083. {
  1084. Ranges ranges;
  1085. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1086. EXPECT_TRUE(ret);
  1087. EXPECT_EQ(2u, ranges.size());
  1088. EXPECT_EQ(1u, ranges[0].first);
  1089. EXPECT_EQ(10u, ranges[0].second);
  1090. EXPECT_EQ(100u, ranges[1].first);
  1091. EXPECT_EQ(-1, ranges[1].second);
  1092. }
  1093. {
  1094. Ranges ranges;
  1095. auto ret =
  1096. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1097. EXPECT_TRUE(ret);
  1098. EXPECT_EQ(3u, ranges.size());
  1099. EXPECT_EQ(1u, ranges[0].first);
  1100. EXPECT_EQ(10u, ranges[0].second);
  1101. EXPECT_EQ(100u, ranges[1].first);
  1102. EXPECT_EQ(200u, ranges[1].second);
  1103. EXPECT_EQ(300u, ranges[2].first);
  1104. EXPECT_EQ(400u, ranges[2].second);
  1105. }
  1106. {
  1107. Ranges ranges;
  1108. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1109. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1110. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1111. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1112. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1113. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1114. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1115. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1116. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1117. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1118. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1119. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1120. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1121. EXPECT_TRUE(ranges.empty());
  1122. }
  1123. }
  1124. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1125. Request req;
  1126. req.set_header("Accept-Encoding", "gzip");
  1127. Response res;
  1128. res.set_header("Content-Type", "text/plain");
  1129. auto ret = detail::encoding_type(req, res);
  1130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1131. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1132. #else
  1133. EXPECT_TRUE(ret == detail::EncodingType::None);
  1134. #endif
  1135. }
  1136. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1137. Request req;
  1138. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1139. Response res;
  1140. res.set_header("Content-Type", "text/plain");
  1141. auto ret = detail::encoding_type(req, res);
  1142. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1143. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1144. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1145. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1146. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1147. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1148. #else
  1149. EXPECT_TRUE(ret == detail::EncodingType::None);
  1150. #endif
  1151. }
  1152. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1153. Request req;
  1154. req.set_header("Accept-Encoding",
  1155. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1156. Response res;
  1157. res.set_header("Content-Type", "text/plain");
  1158. auto ret = detail::encoding_type(req, res);
  1159. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1160. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1161. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1162. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1163. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1164. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1165. #else
  1166. EXPECT_TRUE(ret == detail::EncodingType::None);
  1167. #endif
  1168. }
  1169. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1170. // All supported encodings rejected with q=0 should return None
  1171. Request req;
  1172. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1173. Response res;
  1174. res.set_header("Content-Type", "text/plain");
  1175. auto ret = detail::encoding_type(req, res);
  1176. EXPECT_TRUE(ret == detail::EncodingType::None);
  1177. }
  1178. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1179. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1180. Request req;
  1181. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1182. Response res;
  1183. res.set_header("Content-Type", "text/plain");
  1184. auto ret = detail::encoding_type(req, res);
  1185. EXPECT_TRUE(ret == detail::EncodingType::None);
  1186. }
  1187. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1188. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1189. Request req;
  1190. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1191. Response res;
  1192. res.set_header("Content-Type", "text/plain");
  1193. auto ret = detail::encoding_type(req, res);
  1194. EXPECT_TRUE(ret == detail::EncodingType::None);
  1195. }
  1196. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1197. // RFC 7231: Accept-Encoding values are case-insensitive
  1198. Request req;
  1199. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1200. Response res;
  1201. res.set_header("Content-Type", "text/plain");
  1202. auto ret = detail::encoding_type(req, res);
  1203. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1204. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1205. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1206. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1207. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1208. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1209. #else
  1210. EXPECT_TRUE(ret == detail::EncodingType::None);
  1211. #endif
  1212. }
  1213. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1214. // q value should determine priority, not hardcoded order
  1215. Request req;
  1216. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1217. Response res;
  1218. res.set_header("Content-Type", "text/plain");
  1219. auto ret = detail::encoding_type(req, res);
  1220. // gzip has highest q=1.0, so it should be selected even though
  1221. // br and zstd are also supported
  1222. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1223. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1224. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1225. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1226. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1227. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1228. #else
  1229. EXPECT_TRUE(ret == detail::EncodingType::None);
  1230. #endif
  1231. }
  1232. TEST(BufferStreamTest, read) {
  1233. detail::BufferStream strm1;
  1234. Stream &strm = strm1;
  1235. EXPECT_EQ(5, strm.write("hello"));
  1236. char buf[512];
  1237. EXPECT_EQ(2, strm.read(buf, 2));
  1238. EXPECT_EQ('h', buf[0]);
  1239. EXPECT_EQ('e', buf[1]);
  1240. EXPECT_EQ(2, strm.read(buf, 2));
  1241. EXPECT_EQ('l', buf[0]);
  1242. EXPECT_EQ('l', buf[1]);
  1243. EXPECT_EQ(1, strm.read(buf, 1));
  1244. EXPECT_EQ('o', buf[0]);
  1245. EXPECT_EQ(0, strm.read(buf, 1));
  1246. }
  1247. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1248. auto host = "www.httpwatch.com";
  1249. auto ip = hosted_at(host);
  1250. EXPECT_EQ("23.96.13.243", ip);
  1251. std::vector<std::string> addrs;
  1252. hosted_at(host, addrs);
  1253. EXPECT_EQ(1u, addrs.size());
  1254. }
  1255. #if 0 // It depends on each test environment...
  1256. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1257. auto host = "www.youtube.com";
  1258. std::vector<std::string> addrs;
  1259. hosted_at(host, addrs);
  1260. EXPECT_EQ(20u, addrs.size());
  1261. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1262. EXPECT_TRUE(it != addrs.end());
  1263. }
  1264. #endif
  1265. class ChunkedEncodingTest : public ::testing::Test {
  1266. protected:
  1267. ChunkedEncodingTest()
  1268. : cli_(HOST, PORT)
  1269. #ifdef CPPHTTPLIB_SSL_ENABLED
  1270. ,
  1271. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1272. #endif
  1273. {
  1274. cli_.set_connection_timeout(2);
  1275. #ifdef CPPHTTPLIB_SSL_ENABLED
  1276. cli_.enable_server_certificate_verification(false);
  1277. #endif
  1278. }
  1279. virtual void SetUp() {
  1280. read_file("./image.jpg", image_data_);
  1281. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1282. res.set_content("Hello World!", "text/plain");
  1283. });
  1284. svr_.Get(
  1285. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1286. res.set_chunked_content_provider(
  1287. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1288. size_t remaining = image_data_.size() - offset;
  1289. if (remaining == 0) {
  1290. sink.done();
  1291. } else {
  1292. constexpr size_t CHUNK_SIZE = 1024;
  1293. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1294. sink.write(&image_data_[offset], send_size);
  1295. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1296. }
  1297. return true;
  1298. });
  1299. });
  1300. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1301. svr_.wait_until_ready();
  1302. }
  1303. virtual void TearDown() {
  1304. svr_.stop();
  1305. if (!request_threads_.empty()) {
  1306. std::this_thread::sleep_for(std::chrono::seconds(1));
  1307. for (auto &t : request_threads_) {
  1308. t.join();
  1309. }
  1310. }
  1311. t_.join();
  1312. }
  1313. #ifdef CPPHTTPLIB_SSL_ENABLED
  1314. SSLClient cli_;
  1315. SSLServer svr_;
  1316. #else
  1317. Client cli_;
  1318. Server svr_;
  1319. #endif
  1320. thread t_;
  1321. std::vector<thread> request_threads_;
  1322. std::string image_data_;
  1323. };
  1324. TEST_F(ChunkedEncodingTest, NormalGet) {
  1325. auto res = cli_.Get("/chunked");
  1326. ASSERT_TRUE(res);
  1327. std::string out;
  1328. read_file("./image.jpg", out);
  1329. EXPECT_EQ(StatusCode::OK_200, res->status);
  1330. EXPECT_EQ(out, res->body);
  1331. }
  1332. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1333. std::string body;
  1334. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1335. body.append(data, data_length);
  1336. return true;
  1337. });
  1338. ASSERT_TRUE(res);
  1339. std::string out;
  1340. read_file("./image.jpg", out);
  1341. EXPECT_EQ(StatusCode::OK_200, res->status);
  1342. EXPECT_EQ(out, body);
  1343. }
  1344. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1345. std::string body;
  1346. auto res = cli_.Get(
  1347. "/chunked",
  1348. [&](const Response &response) {
  1349. EXPECT_EQ(StatusCode::OK_200, response.status);
  1350. return true;
  1351. },
  1352. [&](const char *data, size_t data_length) {
  1353. body.append(data, data_length);
  1354. return true;
  1355. });
  1356. ASSERT_TRUE(res);
  1357. std::string out;
  1358. read_file("./image.jpg", out);
  1359. EXPECT_EQ(StatusCode::OK_200, res->status);
  1360. EXPECT_EQ(out, body);
  1361. }
  1362. TEST(RangeTest, FromHTTPBin_Online) {
  1363. auto host = "httpbingo.org";
  1364. auto path = std::string{"/range/32"};
  1365. #ifdef CPPHTTPLIB_SSL_ENABLED
  1366. auto port = 443;
  1367. SSLClient cli(host, port);
  1368. #else
  1369. auto port = 80;
  1370. Client cli(host, port);
  1371. #endif
  1372. cli.set_connection_timeout(5);
  1373. {
  1374. auto res = cli.Get(path);
  1375. ASSERT_TRUE(res);
  1376. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1377. EXPECT_EQ(StatusCode::OK_200, res->status);
  1378. }
  1379. {
  1380. Headers headers = {make_range_header({{1, -1}})};
  1381. auto res = cli.Get(path, headers);
  1382. ASSERT_TRUE(res);
  1383. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1384. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1385. }
  1386. {
  1387. Headers headers = {make_range_header({{1, 10}})};
  1388. auto res = cli.Get(path, headers);
  1389. ASSERT_TRUE(res);
  1390. EXPECT_EQ("bcdefghijk", res->body);
  1391. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1392. }
  1393. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1394. // entire resource, while the original httpbin returned 200. Both are
  1395. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1396. {
  1397. Headers headers = {make_range_header({{0, 31}})};
  1398. auto res = cli.Get(path, headers);
  1399. ASSERT_TRUE(res);
  1400. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1401. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1402. res->status == StatusCode::PartialContent_206);
  1403. }
  1404. {
  1405. Headers headers = {make_range_header({{0, -1}})};
  1406. auto res = cli.Get(path, headers);
  1407. ASSERT_TRUE(res);
  1408. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1409. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1410. res->status == StatusCode::PartialContent_206);
  1411. }
  1412. // go-httpbin returns 206 with clamped range for over-range requests,
  1413. // while the original httpbin returned 416. Both behaviors are observed
  1414. // in real servers, so we only verify the request succeeds.
  1415. {
  1416. Headers headers = {make_range_header({{0, 32}})};
  1417. auto res = cli.Get(path, headers);
  1418. ASSERT_TRUE(res);
  1419. }
  1420. }
  1421. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1422. auto host = "unresolvableaddress.local";
  1423. auto path = std::string{"/"};
  1424. #ifdef CPPHTTPLIB_SSL_ENABLED
  1425. auto port = 443;
  1426. SSLClient cli(host, port);
  1427. #else
  1428. auto port = 80;
  1429. Client cli(host, port);
  1430. #endif
  1431. cli.set_connection_timeout(1);
  1432. {
  1433. auto res = cli.Get(path);
  1434. ASSERT_FALSE(res);
  1435. }
  1436. std::this_thread::sleep_for(std::chrono::seconds(8));
  1437. }
  1438. #if defined(__linux__) && defined(__GLIBC__) && \
  1439. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1440. // Forward declaration: in split builds split.py strips `inline` and moves the
  1441. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1442. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1443. // against the symbol in both header-only and split builds.
  1444. namespace httplib {
  1445. namespace detail {
  1446. int getaddrinfo_with_timeout(const char *node, const char *service,
  1447. const struct addrinfo *hints,
  1448. struct addrinfo **res, time_t timeout_sec);
  1449. } // namespace detail
  1450. } // namespace httplib
  1451. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1452. //
  1453. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1454. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1455. // gai_suspend() call hits the connection timeout the function calls
  1456. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1457. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1458. // still alive and still references the now-destroyed stack frame.
  1459. //
  1460. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1461. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1462. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1463. // and runs them in a container.
  1464. namespace {
  1465. bool should_run_issue_2431_tests() {
  1466. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1467. return v && *v && std::string(v) != "0";
  1468. }
  1469. std::string unique_unresolvable_host(int n) {
  1470. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1471. // glibc still asks the configured nameserver — which is exactly the path
  1472. // we want to exercise. A unique label per call avoids the resolver cache.
  1473. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1474. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1475. std::to_string(n) + ".invalid";
  1476. }
  1477. } // namespace
  1478. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1479. if (!should_run_issue_2431_tests()) {
  1480. GTEST_SKIP()
  1481. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1482. }
  1483. for (int i = 0; i < 8; ++i) {
  1484. struct addrinfo hints;
  1485. memset(&hints, 0, sizeof(hints));
  1486. hints.ai_family = AF_UNSPEC;
  1487. hints.ai_socktype = SOCK_STREAM;
  1488. auto host = unique_unresolvable_host(i);
  1489. struct addrinfo *result = nullptr;
  1490. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1491. &result, /*timeout_sec=*/1);
  1492. if (rc == 0 && result) { freeaddrinfo(result); }
  1493. }
  1494. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1495. // stack region they still believe holds their gaicb.
  1496. std::this_thread::sleep_for(std::chrono::seconds(3));
  1497. }
  1498. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1499. if (!should_run_issue_2431_tests()) {
  1500. GTEST_SKIP()
  1501. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1502. }
  1503. std::atomic<bool> stop{false};
  1504. std::vector<std::thread> threads;
  1505. for (int t = 0; t < 8; ++t) {
  1506. threads.emplace_back([t, &stop] {
  1507. int i = 0;
  1508. while (!stop.load(std::memory_order_relaxed)) {
  1509. struct addrinfo hints;
  1510. memset(&hints, 0, sizeof(hints));
  1511. hints.ai_family = AF_UNSPEC;
  1512. hints.ai_socktype = SOCK_STREAM;
  1513. auto host = unique_unresolvable_host(t * 100000 + i++);
  1514. struct addrinfo *result = nullptr;
  1515. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1516. &result, /*timeout_sec=*/1);
  1517. if (rc == 0 && result) { freeaddrinfo(result); }
  1518. }
  1519. });
  1520. }
  1521. std::this_thread::sleep_for(std::chrono::seconds(8));
  1522. stop.store(true, std::memory_order_relaxed);
  1523. for (auto &th : threads) {
  1524. th.join();
  1525. }
  1526. std::this_thread::sleep_for(std::chrono::seconds(3));
  1527. }
  1528. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1529. if (!should_run_issue_2431_tests()) {
  1530. GTEST_SKIP()
  1531. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1532. }
  1533. std::atomic<bool> stop{false};
  1534. std::vector<std::thread> threads;
  1535. for (int t = 0; t < 8; ++t) {
  1536. threads.emplace_back([t, &stop] {
  1537. int i = 0;
  1538. while (!stop.load(std::memory_order_relaxed)) {
  1539. auto host = unique_unresolvable_host(t * 100000 + i++);
  1540. Client cli(host, 80);
  1541. cli.set_connection_timeout(1, 0);
  1542. cli.set_read_timeout(1, 0);
  1543. cli.set_write_timeout(1, 0);
  1544. (void)cli.Get("/");
  1545. }
  1546. });
  1547. }
  1548. std::this_thread::sleep_for(std::chrono::seconds(8));
  1549. stop.store(true, std::memory_order_relaxed);
  1550. for (auto &th : threads) {
  1551. th.join();
  1552. }
  1553. std::this_thread::sleep_for(std::chrono::seconds(3));
  1554. }
  1555. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1556. TEST(ConnectionErrorTest, InvalidHost) {
  1557. auto host = "-abcde.com";
  1558. #ifdef CPPHTTPLIB_SSL_ENABLED
  1559. auto port = 443;
  1560. SSLClient cli(host, port);
  1561. #else
  1562. auto port = 80;
  1563. Client cli(host, port);
  1564. #endif
  1565. cli.set_connection_timeout(std::chrono::seconds(2));
  1566. auto res = cli.Get("/");
  1567. ASSERT_TRUE(!res);
  1568. EXPECT_EQ(Error::Connection, res.error());
  1569. }
  1570. TEST(ConnectionErrorTest, InvalidHost2) {
  1571. auto host = "httpcan.org/";
  1572. #ifdef CPPHTTPLIB_SSL_ENABLED
  1573. SSLClient cli(host);
  1574. #else
  1575. Client cli(host);
  1576. #endif
  1577. cli.set_connection_timeout(std::chrono::seconds(2));
  1578. auto res = cli.Get("/");
  1579. ASSERT_TRUE(!res);
  1580. EXPECT_EQ(Error::Connection, res.error());
  1581. }
  1582. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1583. auto host = "httpcan.org/";
  1584. #ifdef CPPHTTPLIB_SSL_ENABLED
  1585. SSLClient cli(host);
  1586. #else
  1587. Client cli(host);
  1588. #endif
  1589. cli.set_connection_timeout(std::chrono::seconds(2));
  1590. auto res = cli.Get("/");
  1591. ASSERT_TRUE(!res);
  1592. stringstream s;
  1593. s << "error code: " << res.error();
  1594. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1595. }
  1596. TEST(ConnectionErrorTest, InvalidPort) {
  1597. auto host = "localhost";
  1598. auto port = 44380;
  1599. #ifdef CPPHTTPLIB_SSL_ENABLED
  1600. SSLClient cli(host, port);
  1601. #else
  1602. Client cli(host, port);
  1603. #endif
  1604. cli.set_connection_timeout(std::chrono::seconds(2));
  1605. auto res = cli.Get("/");
  1606. ASSERT_TRUE(!res);
  1607. EXPECT_TRUE(Error::Connection == res.error() ||
  1608. Error::ConnectionTimeout == res.error());
  1609. }
  1610. TEST(ConnectionErrorTest, Timeout_Online) {
  1611. auto host = "google.com";
  1612. #ifdef CPPHTTPLIB_SSL_ENABLED
  1613. auto port = 44380;
  1614. SSLClient cli(host, port);
  1615. #else
  1616. auto port = 8080;
  1617. Client cli(host, port);
  1618. #endif
  1619. cli.set_connection_timeout(std::chrono::seconds(2));
  1620. // only probe one address type so that the error reason
  1621. // correlates to the timed-out IPv4, not the unsupported
  1622. // IPv6 connection attempt
  1623. cli.set_address_family(AF_INET);
  1624. auto res = cli.Get("/");
  1625. ASSERT_TRUE(!res);
  1626. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1627. }
  1628. TEST(CancelTest, NoCancel_Online) {
  1629. auto host = "httpbingo.org";
  1630. auto path = std::string{"/range/32"};
  1631. #ifdef CPPHTTPLIB_SSL_ENABLED
  1632. auto port = 443;
  1633. SSLClient cli(host, port);
  1634. #else
  1635. auto port = 80;
  1636. Client cli(host, port);
  1637. #endif
  1638. cli.set_connection_timeout(std::chrono::seconds(5));
  1639. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1640. ASSERT_TRUE(res);
  1641. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1642. EXPECT_EQ(StatusCode::OK_200, res->status);
  1643. }
  1644. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1645. // Use /bytes with a large payload so that the DownloadProgress callback
  1646. // (which only fires for Content-Length responses) is invoked before the
  1647. // entire body is received, giving cancellation a chance to fire.
  1648. auto host = "httpbingo.org";
  1649. auto path = std::string{"/bytes/524288"};
  1650. #ifdef CPPHTTPLIB_SSL_ENABLED
  1651. auto port = 443;
  1652. SSLClient cli(host, port);
  1653. #else
  1654. auto port = 80;
  1655. Client cli(host, port);
  1656. #endif
  1657. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1658. cli.set_connection_timeout(std::chrono::seconds(5));
  1659. ASSERT_TRUE(!res);
  1660. EXPECT_EQ(Error::Canceled, res.error());
  1661. }
  1662. TEST(CancelTest, WithCancelLargePayload_Online) {
  1663. auto host = "httpbingo.org";
  1664. auto path = std::string{"/bytes/524288"};
  1665. #ifdef CPPHTTPLIB_SSL_ENABLED
  1666. auto port = 443;
  1667. SSLClient cli(host, port);
  1668. #else
  1669. auto port = 80;
  1670. Client cli(host, port);
  1671. #endif
  1672. cli.set_connection_timeout(std::chrono::seconds(5));
  1673. uint32_t count = 0;
  1674. auto res =
  1675. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1676. ASSERT_TRUE(!res);
  1677. EXPECT_EQ(Error::Canceled, res.error());
  1678. }
  1679. TEST(CancelTest, NoCancelPost) {
  1680. Server svr;
  1681. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1682. res.set_content("Hello World!", "text/plain");
  1683. });
  1684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1685. auto se = detail::scope_exit([&] {
  1686. svr.stop();
  1687. thread.join();
  1688. ASSERT_FALSE(svr.is_running());
  1689. });
  1690. svr.wait_until_ready();
  1691. Client cli(HOST, PORT);
  1692. cli.set_connection_timeout(std::chrono::seconds(5));
  1693. auto res =
  1694. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1695. "application/json", [](uint64_t, uint64_t) { return true; });
  1696. ASSERT_TRUE(res);
  1697. EXPECT_EQ("Hello World!", res->body);
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1701. Server svr;
  1702. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1703. res.set_content("Hello World!", "text/plain");
  1704. });
  1705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1706. auto se = detail::scope_exit([&] {
  1707. svr.stop();
  1708. thread.join();
  1709. ASSERT_FALSE(svr.is_running());
  1710. });
  1711. svr.wait_until_ready();
  1712. Client cli(HOST, PORT);
  1713. cli.set_connection_timeout(std::chrono::seconds(5));
  1714. auto res =
  1715. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1716. "application/json", [](uint64_t, uint64_t) { return false; });
  1717. ASSERT_TRUE(!res);
  1718. EXPECT_EQ(Error::Canceled, res.error());
  1719. }
  1720. TEST(CancelTest, WithCancelLargePayloadPost) {
  1721. Server svr;
  1722. svr.set_payload_max_length(200 * 1024 * 1024);
  1723. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1724. res.set_content(LARGE_DATA, "text/plain");
  1725. });
  1726. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. thread.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. Client cli(HOST, PORT);
  1734. cli.set_payload_max_length(200 * 1024 * 1024);
  1735. cli.set_connection_timeout(std::chrono::seconds(5));
  1736. auto res =
  1737. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1738. "application/json", [](uint64_t, uint64_t) { return false; });
  1739. ASSERT_TRUE(!res);
  1740. EXPECT_EQ(Error::Canceled, res.error());
  1741. }
  1742. TEST(CancelTest, NoCancelPut) {
  1743. Server svr;
  1744. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content("Hello World!", "text/plain");
  1746. });
  1747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1748. auto se = detail::scope_exit([&] {
  1749. svr.stop();
  1750. thread.join();
  1751. ASSERT_FALSE(svr.is_running());
  1752. });
  1753. svr.wait_until_ready();
  1754. Client cli(HOST, PORT);
  1755. cli.set_connection_timeout(std::chrono::seconds(5));
  1756. auto res =
  1757. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1758. "application/json", [](uint64_t, uint64_t) { return true; });
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ("Hello World!", res->body);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. }
  1763. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1764. Server svr;
  1765. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1766. res.set_content("Hello World!", "text/plain");
  1767. });
  1768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1769. auto se = detail::scope_exit([&] {
  1770. svr.stop();
  1771. thread.join();
  1772. ASSERT_FALSE(svr.is_running());
  1773. });
  1774. svr.wait_until_ready();
  1775. Client cli(HOST, PORT);
  1776. cli.set_connection_timeout(std::chrono::seconds(5));
  1777. auto res =
  1778. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1779. "application/json", [](uint64_t, uint64_t) { return false; });
  1780. ASSERT_TRUE(!res);
  1781. EXPECT_EQ(Error::Canceled, res.error());
  1782. }
  1783. TEST(CancelTest, WithCancelLargePayloadPut) {
  1784. Server svr;
  1785. svr.set_payload_max_length(200 * 1024 * 1024);
  1786. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1787. res.set_content(LARGE_DATA, "text/plain");
  1788. });
  1789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1790. auto se = detail::scope_exit([&] {
  1791. svr.stop();
  1792. thread.join();
  1793. ASSERT_FALSE(svr.is_running());
  1794. });
  1795. svr.wait_until_ready();
  1796. Client cli(HOST, PORT);
  1797. cli.set_payload_max_length(200 * 1024 * 1024);
  1798. cli.set_connection_timeout(std::chrono::seconds(5));
  1799. auto res =
  1800. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1801. "application/json", [](uint64_t, uint64_t) { return false; });
  1802. ASSERT_TRUE(!res);
  1803. EXPECT_EQ(Error::Canceled, res.error());
  1804. }
  1805. TEST(CancelTest, NoCancelPatch) {
  1806. Server svr;
  1807. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1808. res.set_content("Hello World!", "text/plain");
  1809. });
  1810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1811. auto se = detail::scope_exit([&] {
  1812. svr.stop();
  1813. thread.join();
  1814. ASSERT_FALSE(svr.is_running());
  1815. });
  1816. svr.wait_until_ready();
  1817. Client cli(HOST, PORT);
  1818. cli.set_connection_timeout(std::chrono::seconds(5));
  1819. auto res =
  1820. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1821. "application/json", [](uint64_t, uint64_t) { return true; });
  1822. ASSERT_TRUE(res);
  1823. EXPECT_EQ("Hello World!", res->body);
  1824. EXPECT_EQ(StatusCode::OK_200, res->status);
  1825. }
  1826. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1827. Server svr;
  1828. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1829. res.set_content("Hello World!", "text/plain");
  1830. });
  1831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1832. auto se = detail::scope_exit([&] {
  1833. svr.stop();
  1834. thread.join();
  1835. ASSERT_FALSE(svr.is_running());
  1836. });
  1837. svr.wait_until_ready();
  1838. Client cli(HOST, PORT);
  1839. cli.set_connection_timeout(std::chrono::seconds(5));
  1840. auto res =
  1841. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1842. "application/json", [](uint64_t, uint64_t) { return false; });
  1843. ASSERT_TRUE(!res);
  1844. EXPECT_EQ(Error::Canceled, res.error());
  1845. }
  1846. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1847. Server svr;
  1848. svr.set_payload_max_length(200 * 1024 * 1024);
  1849. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1850. res.set_content(LARGE_DATA, "text/plain");
  1851. });
  1852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1853. auto se = detail::scope_exit([&] {
  1854. svr.stop();
  1855. thread.join();
  1856. ASSERT_FALSE(svr.is_running());
  1857. });
  1858. svr.wait_until_ready();
  1859. Client cli(HOST, PORT);
  1860. cli.set_payload_max_length(200 * 1024 * 1024);
  1861. cli.set_connection_timeout(std::chrono::seconds(5));
  1862. auto res =
  1863. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1864. "application/json", [](uint64_t, uint64_t) { return false; });
  1865. ASSERT_TRUE(!res);
  1866. EXPECT_EQ(Error::Canceled, res.error());
  1867. }
  1868. TEST(CancelTest, NoCancelDelete) {
  1869. Server svr;
  1870. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1871. res.set_content("Hello World!", "text/plain");
  1872. });
  1873. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1874. auto se = detail::scope_exit([&] {
  1875. svr.stop();
  1876. thread.join();
  1877. ASSERT_FALSE(svr.is_running());
  1878. });
  1879. svr.wait_until_ready();
  1880. Client cli(HOST, PORT);
  1881. cli.set_connection_timeout(std::chrono::seconds(5));
  1882. auto res =
  1883. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1884. "application/json", [](uint64_t, uint64_t) { return true; });
  1885. ASSERT_TRUE(res);
  1886. EXPECT_EQ("Hello World!", res->body);
  1887. EXPECT_EQ(StatusCode::OK_200, res->status);
  1888. }
  1889. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1890. Server svr;
  1891. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1892. res.set_content("Hello World!", "text/plain");
  1893. });
  1894. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1895. auto se = detail::scope_exit([&] {
  1896. svr.stop();
  1897. thread.join();
  1898. ASSERT_FALSE(svr.is_running());
  1899. });
  1900. svr.wait_until_ready();
  1901. Client cli(HOST, PORT);
  1902. cli.set_connection_timeout(std::chrono::seconds(5));
  1903. auto res =
  1904. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1905. "application/json", [](uint64_t, uint64_t) { return false; });
  1906. ASSERT_TRUE(!res);
  1907. EXPECT_EQ(Error::Canceled, res.error());
  1908. }
  1909. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1910. Server svr;
  1911. svr.set_payload_max_length(200 * 1024 * 1024);
  1912. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1913. res.set_content(LARGE_DATA, "text/plain");
  1914. });
  1915. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1916. auto se = detail::scope_exit([&] {
  1917. svr.stop();
  1918. thread.join();
  1919. ASSERT_FALSE(svr.is_running());
  1920. });
  1921. svr.wait_until_ready();
  1922. Client cli(HOST, PORT);
  1923. cli.set_payload_max_length(200 * 1024 * 1024);
  1924. cli.set_connection_timeout(std::chrono::seconds(5));
  1925. auto res =
  1926. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1927. "application/json", [](uint64_t, uint64_t) { return false; });
  1928. ASSERT_TRUE(!res);
  1929. EXPECT_EQ(Error::Canceled, res.error());
  1930. }
  1931. static std::string remove_whitespace(const std::string &input) {
  1932. std::string output;
  1933. output.reserve(input.size());
  1934. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1935. [](unsigned char c) { return !std::isspace(c); });
  1936. return output;
  1937. }
  1938. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1939. auto host = "httpbingo.org";
  1940. auto path = std::string{"/basic-auth/hello/world"};
  1941. #ifdef CPPHTTPLIB_SSL_ENABLED
  1942. auto port = 443;
  1943. SSLClient cli(host, port);
  1944. #else
  1945. auto port = 80;
  1946. Client cli(host, port);
  1947. #endif
  1948. {
  1949. auto res = cli.Get(path);
  1950. ASSERT_TRUE(res);
  1951. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1952. }
  1953. {
  1954. auto res =
  1955. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1956. ASSERT_TRUE(res);
  1957. auto body = remove_whitespace(res->body);
  1958. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1959. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1960. EXPECT_EQ(StatusCode::OK_200, res->status);
  1961. }
  1962. {
  1963. cli.set_basic_auth("hello", "world");
  1964. auto res = cli.Get(path);
  1965. ASSERT_TRUE(res);
  1966. auto body = remove_whitespace(res->body);
  1967. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1968. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1969. EXPECT_EQ(StatusCode::OK_200, res->status);
  1970. }
  1971. {
  1972. cli.set_basic_auth("hello", "bad");
  1973. auto res = cli.Get(path);
  1974. ASSERT_TRUE(res);
  1975. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1976. }
  1977. {
  1978. cli.set_basic_auth("bad", "world");
  1979. auto res = cli.Get(path);
  1980. ASSERT_TRUE(res);
  1981. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1982. }
  1983. }
  1984. #ifdef CPPHTTPLIB_SSL_ENABLED
  1985. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1986. auto host = "httpbingo.org";
  1987. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1988. auto paths = std::vector<std::string>{
  1989. "/digest-auth/auth/hello/world/MD5",
  1990. "/digest-auth/auth/hello/world/SHA-256",
  1991. };
  1992. auto port = 443;
  1993. SSLClient cli(host, port);
  1994. {
  1995. auto res = cli.Get(unauth_path);
  1996. ASSERT_TRUE(res);
  1997. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1998. }
  1999. {
  2000. cli.set_digest_auth("hello", "world");
  2001. for (const auto &path : paths) {
  2002. auto res = cli.Get(path.c_str());
  2003. ASSERT_TRUE(res);
  2004. auto body = remove_whitespace(res->body);
  2005. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2006. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2007. EXPECT_EQ(StatusCode::OK_200, res->status);
  2008. }
  2009. cli.set_digest_auth("hello", "bad");
  2010. for (const auto &path : paths) {
  2011. auto res = cli.Get(path.c_str());
  2012. ASSERT_TRUE(res);
  2013. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2014. }
  2015. }
  2016. }
  2017. #endif
  2018. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2019. auto host = "google.com";
  2020. auto another_host = "example.com";
  2021. auto wrong_ip = "0.0.0.0";
  2022. #ifdef CPPHTTPLIB_SSL_ENABLED
  2023. SSLClient cli(host);
  2024. #else
  2025. Client cli(host);
  2026. #endif
  2027. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2028. auto res = cli.Get("/");
  2029. ASSERT_TRUE(res);
  2030. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2031. }
  2032. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2033. auto host = "google.com";
  2034. auto wrong_ip = "0.0.0.0";
  2035. #ifdef CPPHTTPLIB_SSL_ENABLED
  2036. SSLClient cli(host);
  2037. #else
  2038. Client cli(host);
  2039. #endif
  2040. cli.set_hostname_addr_map({{host, wrong_ip}});
  2041. auto res = cli.Get("/");
  2042. ASSERT_TRUE(!res);
  2043. EXPECT_EQ(Error::Connection, res.error());
  2044. }
  2045. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2046. auto host = "httpbingo.org";
  2047. auto path = std::string{"/absolute-redirect/3"};
  2048. #ifdef CPPHTTPLIB_SSL_ENABLED
  2049. SSLClient cli(host);
  2050. #else
  2051. Client cli(host);
  2052. #endif
  2053. cli.set_follow_location(true);
  2054. auto res = cli.Get(path);
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(StatusCode::OK_200, res->status);
  2057. }
  2058. TEST(RedirectTest, Redirect_Online) {
  2059. auto host = "httpbingo.org";
  2060. auto path = std::string{"/redirect/3"};
  2061. #ifdef CPPHTTPLIB_SSL_ENABLED
  2062. SSLClient cli(host);
  2063. #else
  2064. Client cli(host);
  2065. #endif
  2066. cli.set_follow_location(true);
  2067. auto res = cli.Get(path);
  2068. ASSERT_TRUE(res);
  2069. EXPECT_EQ(StatusCode::OK_200, res->status);
  2070. }
  2071. TEST(RelativeRedirectTest, Redirect_Online) {
  2072. auto host = "httpbingo.org";
  2073. auto path = std::string{"/relative-redirect/3"};
  2074. #ifdef CPPHTTPLIB_SSL_ENABLED
  2075. SSLClient cli(host);
  2076. #else
  2077. Client cli(host);
  2078. #endif
  2079. cli.set_follow_location(true);
  2080. auto res = cli.Get(path);
  2081. ASSERT_TRUE(res);
  2082. EXPECT_EQ(StatusCode::OK_200, res->status);
  2083. }
  2084. TEST(TooManyRedirectTest, Redirect_Online) {
  2085. auto host = "httpbingo.org";
  2086. auto path = std::string{"/redirect/21"};
  2087. #ifdef CPPHTTPLIB_SSL_ENABLED
  2088. SSLClient cli(host);
  2089. #else
  2090. Client cli(host);
  2091. #endif
  2092. cli.set_follow_location(true);
  2093. auto res = cli.Get(path);
  2094. ASSERT_TRUE(!res);
  2095. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2096. }
  2097. #ifdef CPPHTTPLIB_SSL_ENABLED
  2098. TEST(YahooRedirectTest, Redirect_Online) {
  2099. Client cli("yahoo.com");
  2100. auto res = cli.Get("/");
  2101. ASSERT_TRUE(res);
  2102. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2103. cli.set_follow_location(true);
  2104. res = cli.Get("/");
  2105. ASSERT_TRUE(res);
  2106. EXPECT_EQ(StatusCode::OK_200, res->status);
  2107. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2108. }
  2109. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2110. #define REDIR_HOST "httpbingo.org"
  2111. #define REDIR_PATH "/redirect-to"
  2112. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2113. SSLClient cli(REDIR_HOST);
  2114. cli.set_follow_location(true);
  2115. auto res =
  2116. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2117. ASSERT_TRUE(res);
  2118. EXPECT_EQ(StatusCode::OK_200, res->status);
  2119. }
  2120. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2121. SSLClient cli(REDIR_HOST);
  2122. cli.set_follow_location(true);
  2123. Params params;
  2124. params.emplace("url", "http://example.com");
  2125. params.emplace("status_code", "302");
  2126. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2127. ASSERT_TRUE(res);
  2128. EXPECT_EQ(StatusCode::OK_200, res->status);
  2129. }
  2130. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2131. SSLClient cli(REDIR_HOST);
  2132. cli.set_follow_location(true);
  2133. Params params;
  2134. params.emplace("url", "http://example.com");
  2135. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2136. ASSERT_TRUE(res);
  2137. EXPECT_EQ(StatusCode::OK_200, res->status);
  2138. }
  2139. TEST(UrlWithSpace, Redirect_Online) {
  2140. SSLClient cli("edge.forgecdn.net");
  2141. cli.set_follow_location(true);
  2142. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2143. ASSERT_TRUE(res);
  2144. EXPECT_EQ(StatusCode::OK_200, res->status);
  2145. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2146. }
  2147. #endif
  2148. #if !defined(_WIN32) && !defined(_WIN64)
  2149. TEST(ReceiveSignals, Signal) {
  2150. auto setupSignalHandlers = []() {
  2151. struct sigaction act;
  2152. sigemptyset(&act.sa_mask);
  2153. act.sa_flags = SA_SIGINFO;
  2154. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2155. switch (sig) {
  2156. case SIGINT:
  2157. default: break;
  2158. }
  2159. };
  2160. ::sigaction(SIGINT, &act, nullptr);
  2161. };
  2162. Server svr;
  2163. int port = 0;
  2164. auto thread = std::thread([&]() {
  2165. setupSignalHandlers();
  2166. port = svr.bind_to_any_port(HOST);
  2167. svr.listen_after_bind();
  2168. });
  2169. auto se = detail::scope_exit([&] {
  2170. svr.stop();
  2171. thread.join();
  2172. ASSERT_FALSE(svr.is_running());
  2173. });
  2174. svr.wait_until_ready();
  2175. ASSERT_TRUE(svr.is_running());
  2176. pthread_kill(thread.native_handle(), SIGINT);
  2177. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2178. ASSERT_TRUE(svr.is_running());
  2179. }
  2180. #endif
  2181. TEST(RedirectToDifferentPort, Redirect) {
  2182. Server svr1;
  2183. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2184. res.set_content("Hello World!", "text/plain");
  2185. });
  2186. int svr1_port = 0;
  2187. auto thread1 = std::thread([&]() {
  2188. svr1_port = svr1.bind_to_any_port(HOST);
  2189. svr1.listen_after_bind();
  2190. });
  2191. Server svr2;
  2192. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2193. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2194. });
  2195. int svr2_port = 0;
  2196. auto thread2 = std::thread([&]() {
  2197. svr2_port = svr2.bind_to_any_port(HOST);
  2198. svr2.listen_after_bind();
  2199. });
  2200. auto se = detail::scope_exit([&] {
  2201. svr2.stop();
  2202. thread2.join();
  2203. svr1.stop();
  2204. thread1.join();
  2205. ASSERT_FALSE(svr2.is_running());
  2206. ASSERT_FALSE(svr1.is_running());
  2207. });
  2208. svr1.wait_until_ready();
  2209. svr2.wait_until_ready();
  2210. Client cli("localhost", svr2_port);
  2211. cli.set_follow_location(true);
  2212. auto res = cli.Get("/2");
  2213. ASSERT_TRUE(res);
  2214. EXPECT_EQ(StatusCode::OK_200, res->status);
  2215. EXPECT_EQ("Hello World!", res->body);
  2216. }
  2217. static void
  2218. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2219. Server svr1;
  2220. std::string captured_authorization;
  2221. svr1.Get("/target", [&](const Request &req, Response &res) {
  2222. captured_authorization = req.get_header_value("Authorization");
  2223. res.set_content("OK", "text/plain");
  2224. });
  2225. int svr1_port = 0;
  2226. auto thread1 = std::thread([&]() {
  2227. svr1_port = svr1.bind_to_any_port(HOST);
  2228. svr1.listen_after_bind();
  2229. });
  2230. Server svr2;
  2231. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2232. res.set_redirect(
  2233. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2234. });
  2235. int svr2_port = 0;
  2236. auto thread2 = std::thread([&]() {
  2237. svr2_port = svr2.bind_to_any_port(HOST);
  2238. svr2.listen_after_bind();
  2239. });
  2240. auto se = detail::scope_exit([&] {
  2241. svr2.stop();
  2242. thread2.join();
  2243. svr1.stop();
  2244. thread1.join();
  2245. ASSERT_FALSE(svr2.is_running());
  2246. ASSERT_FALSE(svr1.is_running());
  2247. });
  2248. svr1.wait_until_ready();
  2249. svr2.wait_until_ready();
  2250. Client cli("localhost", svr2_port);
  2251. cli.set_follow_location(true);
  2252. set_auth(cli);
  2253. auto res = cli.Get("/redir");
  2254. ASSERT_TRUE(res);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2257. EXPECT_TRUE(captured_authorization.empty());
  2258. }
  2259. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2260. TestDoNotForwardCredentialsOnRedirect(
  2261. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2262. }
  2263. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2264. TestDoNotForwardCredentialsOnRedirect(
  2265. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2266. }
  2267. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2268. Server svr;
  2269. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2270. // Port number that overflows int — should not crash
  2271. res.set_redirect("http://localhost:99999999999999999999/target");
  2272. });
  2273. auto port = svr.bind_to_any_port(HOST);
  2274. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2275. auto se = detail::scope_exit([&] {
  2276. svr.stop();
  2277. thread.join();
  2278. ASSERT_FALSE(svr.is_running());
  2279. });
  2280. svr.wait_until_ready();
  2281. Client cli(HOST, port);
  2282. cli.set_follow_location(true);
  2283. auto res = cli.Get("/redir");
  2284. // Should fail gracefully, not crash (no valid response due to bad port)
  2285. EXPECT_FALSE(res);
  2286. }
  2287. TEST(RedirectFromPageWithContent, Redirect) {
  2288. Server svr;
  2289. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2290. res.set_content("___", "text/plain");
  2291. res.set_redirect("/2");
  2292. });
  2293. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2294. res.set_content("Hello World!", "text/plain");
  2295. });
  2296. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2297. auto se = detail::scope_exit([&] {
  2298. svr.stop();
  2299. th.join();
  2300. ASSERT_FALSE(svr.is_running());
  2301. });
  2302. svr.wait_until_ready();
  2303. {
  2304. Client cli("localhost", PORT);
  2305. cli.set_follow_location(true);
  2306. std::string body;
  2307. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2308. body.append(data, data_length);
  2309. return true;
  2310. });
  2311. ASSERT_TRUE(res);
  2312. EXPECT_EQ(StatusCode::OK_200, res->status);
  2313. EXPECT_EQ("Hello World!", body);
  2314. }
  2315. {
  2316. Client cli("localhost", PORT);
  2317. std::string body;
  2318. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2319. body.append(data, data_length);
  2320. return true;
  2321. });
  2322. ASSERT_TRUE(res);
  2323. EXPECT_EQ(StatusCode::Found_302, res->status);
  2324. EXPECT_EQ("___", body);
  2325. }
  2326. }
  2327. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2328. Server svr;
  2329. auto port_str = std::to_string(PORT);
  2330. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2331. auto expected_host = "[::1]:" + port_str;
  2332. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2333. res.set_content("___", "text/plain");
  2334. // res.set_redirect("/2");
  2335. res.set_redirect(redirect_url);
  2336. });
  2337. svr.Get("/2", [&](const Request &req, Response &res) {
  2338. auto host_header = req.headers.find("Host");
  2339. ASSERT_TRUE(host_header != req.headers.end());
  2340. EXPECT_EQ(expected_host, host_header->second);
  2341. res.set_content("Hello World!", "text/plain");
  2342. });
  2343. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2344. auto se = detail::scope_exit([&] {
  2345. svr.stop();
  2346. th.join();
  2347. ASSERT_FALSE(svr.is_running());
  2348. });
  2349. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2350. // actually starts anything, so the condition !svr.is_running() will
  2351. // always remain true, and the loop never stops.
  2352. // This basically counts how many milliseconds have passed since the
  2353. // call to svr.listen(), and if after 5 seconds nothing started yet
  2354. // aborts the test.
  2355. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2356. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2357. ASSERT_LT(milliseconds, 5000U);
  2358. }
  2359. {
  2360. Client cli("::1", PORT);
  2361. cli.set_follow_location(true);
  2362. std::string body;
  2363. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2364. body.append(data, data_length);
  2365. return true;
  2366. });
  2367. ASSERT_TRUE(res);
  2368. EXPECT_EQ(StatusCode::OK_200, res->status);
  2369. EXPECT_EQ("Hello World!", body);
  2370. }
  2371. {
  2372. Client cli("::1", PORT);
  2373. std::string body;
  2374. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2375. body.append(data, data_length);
  2376. return true;
  2377. });
  2378. ASSERT_TRUE(res);
  2379. EXPECT_EQ(StatusCode::Found_302, res->status);
  2380. EXPECT_EQ("___", body);
  2381. }
  2382. }
  2383. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2384. Server svr;
  2385. svr.Get("/foo", [](const Request &req, Response &res) {
  2386. auto a = req.params.find("a");
  2387. if (a != req.params.end()) {
  2388. res.set_content((*a).second, "text/plain");
  2389. res.status = StatusCode::OK_200;
  2390. } else {
  2391. res.status = StatusCode::BadRequest_400;
  2392. }
  2393. });
  2394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2395. auto se = detail::scope_exit([&] {
  2396. svr.stop();
  2397. thread.join();
  2398. ASSERT_FALSE(svr.is_running());
  2399. });
  2400. svr.wait_until_ready();
  2401. {
  2402. Client cli(HOST, PORT);
  2403. cli.set_path_encode(false);
  2404. auto res = cli.Get("/foo?a=explicitly+encoded");
  2405. ASSERT_TRUE(res);
  2406. EXPECT_EQ(StatusCode::OK_200, res->status);
  2407. // This expects it back with a space, as the `+` won't have been
  2408. // url-encoded, and server-side the params get decoded turning `+`
  2409. // into spaces.
  2410. EXPECT_EQ("explicitly encoded", res->body);
  2411. }
  2412. }
  2413. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2414. Server svr;
  2415. svr.Get("/", [](const Request &req, Response &) {
  2416. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2417. });
  2418. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2419. auto se = detail::scope_exit([&] {
  2420. svr.stop();
  2421. thread.join();
  2422. ASSERT_FALSE(svr.is_running());
  2423. });
  2424. svr.wait_until_ready();
  2425. {
  2426. Client cli(HOST, PORT);
  2427. cli.set_path_encode(false);
  2428. auto res = cli.Get("/?something=%0A");
  2429. ASSERT_TRUE(res);
  2430. EXPECT_EQ(StatusCode::OK_200, res->status);
  2431. }
  2432. }
  2433. TEST(BindServerTest, BindDualStack) {
  2434. Server svr;
  2435. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2436. res.set_content("Hello World!", "text/plain");
  2437. });
  2438. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. {
  2446. Client cli("127.0.0.1", PORT);
  2447. auto res = cli.Get("/1");
  2448. ASSERT_TRUE(res);
  2449. EXPECT_EQ(StatusCode::OK_200, res->status);
  2450. EXPECT_EQ("Hello World!", res->body);
  2451. }
  2452. {
  2453. Client cli("::1", PORT);
  2454. auto res = cli.Get("/1");
  2455. ASSERT_TRUE(res);
  2456. EXPECT_EQ(StatusCode::OK_200, res->status);
  2457. EXPECT_EQ("Hello World!", res->body);
  2458. }
  2459. }
  2460. TEST(BindServerTest, BindAndListenSeparately) {
  2461. Server svr;
  2462. int port = svr.bind_to_any_port("0.0.0.0");
  2463. ASSERT_TRUE(svr.is_valid());
  2464. ASSERT_TRUE(port > 0);
  2465. svr.stop();
  2466. }
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2469. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2470. CLIENT_CA_CERT_DIR);
  2471. int port = svr.bind_to_any_port("0.0.0.0");
  2472. ASSERT_TRUE(svr.is_valid());
  2473. ASSERT_TRUE(port > 0);
  2474. svr.stop();
  2475. }
  2476. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2477. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2478. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2479. int port = svr.bind_to_any_port("0.0.0.0");
  2480. ASSERT_TRUE(svr.is_valid());
  2481. ASSERT_TRUE(port > 0);
  2482. svr.stop();
  2483. }
  2484. TEST(BindServerTest, UpdateCertsPem) {
  2485. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2486. int port = svr.bind_to_any_port("0.0.0.0");
  2487. ASSERT_TRUE(svr.is_valid());
  2488. ASSERT_TRUE(port > 0);
  2489. // Read PEM files
  2490. std::string cert_pem, key_pem, ca_pem;
  2491. read_file(SERVER_CERT_FILE, cert_pem);
  2492. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2493. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2494. // Update server certificates using PEM API
  2495. ASSERT_TRUE(
  2496. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2497. ASSERT_TRUE(svr.is_valid());
  2498. svr.stop();
  2499. }
  2500. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2501. // Start server with client CA (enables client auth)
  2502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2503. ASSERT_TRUE(svr.is_valid());
  2504. bool handler_called = false;
  2505. svr.Get("/test", [&](const Request &req, Response &res) {
  2506. handler_called = true;
  2507. // Verify client certificate is present
  2508. auto cert = req.peer_cert();
  2509. EXPECT_TRUE(static_cast<bool>(cert));
  2510. res.set_content("ok", "text/plain");
  2511. });
  2512. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2513. auto se = detail::scope_exit([&] {
  2514. svr.stop();
  2515. t.join();
  2516. ASSERT_FALSE(svr.is_running());
  2517. });
  2518. svr.wait_until_ready();
  2519. // Read PEM files
  2520. std::string cert_pem, key_pem, ca_pem;
  2521. read_file(SERVER_CERT_FILE, cert_pem);
  2522. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2523. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2524. // Update server certificates and client CA using PEM API while server running
  2525. ASSERT_TRUE(
  2526. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2527. // Connect with client certificate
  2528. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2529. cli.enable_server_certificate_verification(false);
  2530. cli.set_connection_timeout(30);
  2531. auto res = cli.Get("/test");
  2532. ASSERT_TRUE(res);
  2533. ASSERT_EQ(StatusCode::OK_200, res->status);
  2534. ASSERT_TRUE(handler_called);
  2535. EXPECT_EQ("ok", res->body);
  2536. }
  2537. #endif
  2538. TEST(ErrorHandlerTest, ContentLength) {
  2539. Server svr;
  2540. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2541. res.status = StatusCode::OK_200;
  2542. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2543. "text/html"); // <= Content-Length still 13
  2544. });
  2545. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2546. res.set_content("Hello World!\n", "text/plain");
  2547. res.status = 524;
  2548. });
  2549. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2550. auto se = detail::scope_exit([&] {
  2551. svr.stop();
  2552. thread.join();
  2553. ASSERT_FALSE(svr.is_running());
  2554. });
  2555. svr.wait_until_ready();
  2556. {
  2557. Client cli(HOST, PORT);
  2558. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2559. ASSERT_TRUE(res);
  2560. EXPECT_EQ(StatusCode::OK_200, res->status);
  2561. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2562. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2563. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2564. }
  2565. }
  2566. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2567. TEST(ExceptionTest, WithoutExceptionHandler) {
  2568. Server svr;
  2569. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2570. throw std::runtime_error("exception...");
  2571. });
  2572. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2573. throw std::runtime_error("exception\r\n...");
  2574. });
  2575. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2576. auto se = detail::scope_exit([&] {
  2577. svr.stop();
  2578. listen_thread.join();
  2579. ASSERT_FALSE(svr.is_running());
  2580. });
  2581. svr.wait_until_ready();
  2582. Client cli("localhost", PORT);
  2583. {
  2584. auto res = cli.Get("/exception");
  2585. ASSERT_TRUE(res);
  2586. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2587. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2588. }
  2589. {
  2590. auto res = cli.Get("/unknown");
  2591. ASSERT_TRUE(res);
  2592. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2593. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2594. }
  2595. }
  2596. TEST(ExceptionTest, WithExceptionHandler) {
  2597. Server svr;
  2598. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2599. std::exception_ptr ep) {
  2600. EXPECT_FALSE(ep == nullptr);
  2601. try {
  2602. std::rethrow_exception(ep);
  2603. } catch (std::exception &e) {
  2604. EXPECT_EQ("abc", std::string(e.what()));
  2605. } catch (...) {}
  2606. res.status = StatusCode::InternalServerError_500;
  2607. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2608. "text/html"); // <= Content-Length still 13 at this point
  2609. });
  2610. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2611. res.set_content("Hello World!\n", "text/plain");
  2612. throw std::runtime_error("abc");
  2613. });
  2614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2615. auto se = detail::scope_exit([&] {
  2616. svr.stop();
  2617. thread.join();
  2618. ASSERT_FALSE(svr.is_running());
  2619. });
  2620. svr.wait_until_ready();
  2621. for (size_t i = 0; i < 10; i++) {
  2622. Client cli(HOST, PORT);
  2623. for (size_t j = 0; j < 100; j++) {
  2624. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2625. ASSERT_TRUE(res);
  2626. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2627. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2628. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2629. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2630. }
  2631. cli.set_keep_alive(true);
  2632. for (size_t j = 0; j < 100; j++) {
  2633. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2634. ASSERT_TRUE(res);
  2635. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2636. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2637. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2638. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2639. }
  2640. }
  2641. }
  2642. TEST(ExceptionTest, AndErrorHandler) {
  2643. Server svr;
  2644. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2645. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2646. });
  2647. svr.set_exception_handler(
  2648. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2649. EXPECT_FALSE(ep == nullptr);
  2650. try {
  2651. std::rethrow_exception(ep);
  2652. } catch (std::exception &e) {
  2653. res.set_content(e.what(), "text/html");
  2654. } catch (...) {}
  2655. res.status = StatusCode::InternalServerError_500;
  2656. });
  2657. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2658. throw std::runtime_error("EXCEPTION");
  2659. });
  2660. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2661. res.set_content("ERROR", "text/html");
  2662. res.status = StatusCode::InternalServerError_500;
  2663. });
  2664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2665. auto se = detail::scope_exit([&] {
  2666. svr.stop();
  2667. thread.join();
  2668. ASSERT_FALSE(svr.is_running());
  2669. });
  2670. svr.wait_until_ready();
  2671. Client cli(HOST, PORT);
  2672. {
  2673. auto res = cli.Get("/exception");
  2674. ASSERT_TRUE(res);
  2675. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2676. EXPECT_EQ("EXCEPTION", res->body);
  2677. }
  2678. {
  2679. auto res = cli.Get("/error");
  2680. ASSERT_TRUE(res);
  2681. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2682. EXPECT_EQ("ERROR", res->body);
  2683. }
  2684. {
  2685. auto res = cli.Get("/invalid");
  2686. ASSERT_TRUE(res);
  2687. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2688. EXPECT_EQ("NOT_FOUND", res->body);
  2689. }
  2690. }
  2691. #endif
  2692. TEST(NoContentTest, ContentLength) {
  2693. Server svr;
  2694. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2695. res.status = StatusCode::NoContent_204;
  2696. });
  2697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2698. auto se = detail::scope_exit([&] {
  2699. svr.stop();
  2700. thread.join();
  2701. ASSERT_FALSE(svr.is_running());
  2702. });
  2703. svr.wait_until_ready();
  2704. {
  2705. Client cli(HOST, PORT);
  2706. auto res = cli.Get("/hi");
  2707. ASSERT_TRUE(res);
  2708. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2709. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2710. }
  2711. }
  2712. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2713. #ifdef CPPHTTPLIB_SSL_ENABLED
  2714. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2715. ASSERT_TRUE(svr.is_valid());
  2716. #else
  2717. Server svr;
  2718. #endif
  2719. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2720. if (req.path == "/routing_handler") {
  2721. res.set_header("PRE_ROUTING", "on");
  2722. res.set_content("Routing Handler", "text/plain");
  2723. return httplib::Server::HandlerResponse::Handled;
  2724. }
  2725. return httplib::Server::HandlerResponse::Unhandled;
  2726. });
  2727. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2728. res.set_content("Error", "text/html");
  2729. });
  2730. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2731. if (req.path == "/routing_handler") {
  2732. res.set_header("POST_ROUTING", "on");
  2733. }
  2734. });
  2735. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2736. res.set_content("Hello World!\n", "text/plain");
  2737. });
  2738. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2739. auto se = detail::scope_exit([&] {
  2740. svr.stop();
  2741. thread.join();
  2742. ASSERT_FALSE(svr.is_running());
  2743. });
  2744. svr.wait_until_ready();
  2745. {
  2746. #ifdef CPPHTTPLIB_SSL_ENABLED
  2747. SSLClient cli(HOST, PORT);
  2748. cli.enable_server_certificate_verification(false);
  2749. #else
  2750. Client cli(HOST, PORT);
  2751. #endif
  2752. auto res = cli.Get("/routing_handler");
  2753. ASSERT_TRUE(res);
  2754. EXPECT_EQ(StatusCode::OK_200, res->status);
  2755. EXPECT_EQ("Routing Handler", res->body);
  2756. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2757. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2758. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2759. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2760. }
  2761. {
  2762. #ifdef CPPHTTPLIB_SSL_ENABLED
  2763. SSLClient cli(HOST, PORT);
  2764. cli.enable_server_certificate_verification(false);
  2765. #else
  2766. Client cli(HOST, PORT);
  2767. #endif
  2768. auto res = cli.Get("/hi");
  2769. ASSERT_TRUE(res);
  2770. EXPECT_EQ(StatusCode::OK_200, res->status);
  2771. EXPECT_EQ("Hello World!\n", res->body);
  2772. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2773. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2774. }
  2775. {
  2776. #ifdef CPPHTTPLIB_SSL_ENABLED
  2777. SSLClient cli(HOST, PORT);
  2778. cli.enable_server_certificate_verification(false);
  2779. #else
  2780. Client cli(HOST, PORT);
  2781. #endif
  2782. auto res = cli.Get("/aaa");
  2783. ASSERT_TRUE(res);
  2784. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2785. EXPECT_EQ("Error", res->body);
  2786. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2787. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2788. }
  2789. }
  2790. TEST(RequestHandlerTest, PreRequestHandler) {
  2791. auto route_path = "/user/:user";
  2792. Server svr;
  2793. svr.Get("/hi", [](const Request &, Response &res) {
  2794. res.set_content("hi", "text/plain");
  2795. });
  2796. svr.Get(route_path, [](const Request &req, Response &res) {
  2797. res.set_content(req.path_params.at("user"), "text/plain");
  2798. });
  2799. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2800. if (req.matched_route == route_path) {
  2801. auto user = req.path_params.at("user");
  2802. if (user != "john") {
  2803. res.status = StatusCode::Forbidden_403;
  2804. res.set_content("error", "text/html");
  2805. return Server::HandlerResponse::Handled;
  2806. }
  2807. }
  2808. return Server::HandlerResponse::Unhandled;
  2809. });
  2810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2811. auto se = detail::scope_exit([&] {
  2812. svr.stop();
  2813. thread.join();
  2814. ASSERT_FALSE(svr.is_running());
  2815. });
  2816. svr.wait_until_ready();
  2817. Client cli(HOST, PORT);
  2818. {
  2819. auto res = cli.Get("/hi");
  2820. ASSERT_TRUE(res);
  2821. EXPECT_EQ(StatusCode::OK_200, res->status);
  2822. EXPECT_EQ("hi", res->body);
  2823. }
  2824. {
  2825. auto res = cli.Get("/user/john");
  2826. ASSERT_TRUE(res);
  2827. EXPECT_EQ(StatusCode::OK_200, res->status);
  2828. EXPECT_EQ("john", res->body);
  2829. }
  2830. {
  2831. auto res = cli.Get("/user/invalid-user");
  2832. ASSERT_TRUE(res);
  2833. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2834. EXPECT_EQ("error", res->body);
  2835. }
  2836. }
  2837. // The pre-request handler must run before the request body is read, so a
  2838. // rejected request never forces the server to buffer a (potentially large)
  2839. // body. Here the posted body is larger than the payload limit: if the body
  2840. // were read first the server would answer 413, but because the pre-request
  2841. // handler runs first it answers 403 and the body is never read.
  2842. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2843. Server svr;
  2844. svr.set_payload_max_length(8);
  2845. auto handler_ran = false;
  2846. svr.Post("/reject", [&](const Request &req, Response &res) {
  2847. handler_ran = true;
  2848. res.set_content(req.body, "text/plain");
  2849. });
  2850. svr.Post("/accept", [](const Request &req, Response &res) {
  2851. res.set_content(req.body, "text/plain");
  2852. });
  2853. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2854. if (req.matched_route == "/reject") {
  2855. res.status = StatusCode::Forbidden_403;
  2856. res.set_content("denied", "text/plain");
  2857. return Server::HandlerResponse::Handled;
  2858. }
  2859. return Server::HandlerResponse::Unhandled;
  2860. });
  2861. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2862. auto se = detail::scope_exit([&] {
  2863. svr.stop();
  2864. thread.join();
  2865. ASSERT_FALSE(svr.is_running());
  2866. });
  2867. svr.wait_until_ready();
  2868. Client cli(HOST, PORT);
  2869. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2870. // rejects with 403 before the body is read, so 413 is never reached.
  2871. {
  2872. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2873. ASSERT_TRUE(res);
  2874. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2875. EXPECT_EQ("denied", res->body);
  2876. EXPECT_FALSE(handler_ran);
  2877. }
  2878. // An approved route still reads the body and enforces the payload limit.
  2879. {
  2880. auto res = cli.Post("/accept", "0123456789", "text/plain");
  2881. ASSERT_TRUE(res);
  2882. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  2883. }
  2884. }
  2885. TEST(UserDataTest, BasicOperations) {
  2886. httplib::UserData ud;
  2887. // Initially empty
  2888. EXPECT_FALSE(ud.has("key"));
  2889. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2890. // set and get
  2891. ud.set("key", 42);
  2892. EXPECT_TRUE(ud.has("key"));
  2893. auto *p = ud.get<int>("key");
  2894. ASSERT_NE(nullptr, p);
  2895. EXPECT_EQ(42, *p);
  2896. // Type mismatch → nullptr
  2897. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2898. // Overwrite with different type
  2899. ud.set("key", std::string("hello"));
  2900. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2901. auto *s = ud.get<std::string>("key");
  2902. ASSERT_NE(nullptr, s);
  2903. EXPECT_EQ("hello", *s);
  2904. // erase
  2905. ud.erase("key");
  2906. EXPECT_FALSE(ud.has("key"));
  2907. // clear
  2908. ud.set("a", 1);
  2909. ud.set("b", 2);
  2910. ud.clear();
  2911. EXPECT_FALSE(ud.has("a"));
  2912. EXPECT_FALSE(ud.has("b"));
  2913. }
  2914. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2915. struct AuthCtx {
  2916. std::string user_id;
  2917. };
  2918. Server svr;
  2919. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2920. res.user_data.set("auth", AuthCtx{"alice"});
  2921. return Server::HandlerResponse::Unhandled;
  2922. });
  2923. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2924. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2925. ASSERT_NE(nullptr, ctx);
  2926. res.set_content("Hello " + ctx->user_id, "text/plain");
  2927. });
  2928. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2929. auto se = detail::scope_exit([&] {
  2930. svr.stop();
  2931. thread.join();
  2932. ASSERT_FALSE(svr.is_running());
  2933. });
  2934. svr.wait_until_ready();
  2935. Client cli(HOST, PORT);
  2936. auto res = cli.Get("/me");
  2937. ASSERT_TRUE(res);
  2938. EXPECT_EQ(StatusCode::OK_200, res->status);
  2939. EXPECT_EQ("Hello alice", res->body);
  2940. }
  2941. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2942. struct RoleCtx {
  2943. std::string role;
  2944. };
  2945. Server svr;
  2946. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2947. res.user_data.set("role", RoleCtx{"admin"});
  2948. return Server::HandlerResponse::Unhandled;
  2949. });
  2950. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2951. auto *ctx = res.user_data.get<RoleCtx>("role");
  2952. ASSERT_NE(nullptr, ctx);
  2953. res.set_content(ctx->role, "text/plain");
  2954. });
  2955. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2956. auto se = detail::scope_exit([&] {
  2957. svr.stop();
  2958. thread.join();
  2959. ASSERT_FALSE(svr.is_running());
  2960. });
  2961. svr.wait_until_ready();
  2962. Client cli(HOST, PORT);
  2963. auto res = cli.Get("/role");
  2964. ASSERT_TRUE(res);
  2965. EXPECT_EQ(StatusCode::OK_200, res->status);
  2966. EXPECT_EQ("admin", res->body);
  2967. }
  2968. TEST(InvalidFormatTest, StatusCode) {
  2969. Server svr;
  2970. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2971. res.set_content("Hello World!\n", "text/plain");
  2972. res.status = 9999; // Status should be a three-digit code...
  2973. });
  2974. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2975. auto se = detail::scope_exit([&] {
  2976. svr.stop();
  2977. thread.join();
  2978. ASSERT_FALSE(svr.is_running());
  2979. });
  2980. svr.wait_until_ready();
  2981. {
  2982. Client cli(HOST, PORT);
  2983. auto res = cli.Get("/hi");
  2984. ASSERT_FALSE(res);
  2985. }
  2986. }
  2987. TEST(URLFragmentTest, WithFragment) {
  2988. Server svr;
  2989. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2990. EXPECT_TRUE(req.target == "/hi");
  2991. });
  2992. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2993. auto se = detail::scope_exit([&] {
  2994. svr.stop();
  2995. thread.join();
  2996. ASSERT_FALSE(svr.is_running());
  2997. });
  2998. svr.wait_until_ready();
  2999. {
  3000. Client cli(HOST, PORT);
  3001. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3002. EXPECT_TRUE(res);
  3003. EXPECT_EQ(StatusCode::OK_200, res->status);
  3004. res = cli.Get("/hi%23key1=val1=key2=val2");
  3005. EXPECT_TRUE(res);
  3006. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3007. }
  3008. }
  3009. TEST(HeaderWriter, SetHeaderWriter) {
  3010. Server svr;
  3011. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3012. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3013. return detail::write_headers(strm, hdrs);
  3014. });
  3015. svr.Get("/hi", [](const Request &req, Response &res) {
  3016. auto it = req.headers.find("CustomClientHeader");
  3017. EXPECT_TRUE(it != req.headers.end());
  3018. EXPECT_EQ(it->second, "CustomClientValue");
  3019. res.set_content("Hello World!\n", "text/plain");
  3020. });
  3021. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3022. auto se = detail::scope_exit([&] {
  3023. svr.stop();
  3024. thread.join();
  3025. ASSERT_FALSE(svr.is_running());
  3026. });
  3027. svr.wait_until_ready();
  3028. {
  3029. Client cli(HOST, PORT);
  3030. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3031. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3032. return detail::write_headers(strm, hdrs);
  3033. });
  3034. auto res = cli.Get("/hi");
  3035. EXPECT_TRUE(res);
  3036. EXPECT_EQ(StatusCode::OK_200, res->status);
  3037. auto it = res->headers.find("CustomServerHeader");
  3038. EXPECT_TRUE(it != res->headers.end());
  3039. EXPECT_EQ(it->second, "CustomServerValue");
  3040. }
  3041. }
  3042. class ServerTest : public ::testing::Test {
  3043. protected:
  3044. ServerTest()
  3045. : cli_(HOST, PORT)
  3046. #ifdef CPPHTTPLIB_SSL_ENABLED
  3047. ,
  3048. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3049. #endif
  3050. {
  3051. #ifdef CPPHTTPLIB_SSL_ENABLED
  3052. cli_.enable_server_certificate_verification(false);
  3053. #endif
  3054. // Allow LARGE_DATA (100MB) responses
  3055. cli_.set_payload_max_length(200 * 1024 * 1024);
  3056. }
  3057. virtual void SetUp() {
  3058. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3059. svr_.set_payload_max_length(200 * 1024 * 1024);
  3060. svr_.set_mount_point("/", "./www");
  3061. svr_.set_mount_point("/mount", "./www2");
  3062. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3063. svr_.Get("/hi",
  3064. [&](const Request & /*req*/, Response &res) {
  3065. res.set_content("Hello World!", "text/plain");
  3066. })
  3067. .Get("/file_content",
  3068. [&](const Request & /*req*/, Response &res) {
  3069. res.set_file_content("./www/dir/test.html");
  3070. })
  3071. .Get("/file_content_with_content_type",
  3072. [&](const Request & /*req*/, Response &res) {
  3073. res.set_file_content("./www/file", "text/plain");
  3074. })
  3075. .Get("/invalid_file_content",
  3076. [&](const Request & /*req*/, Response &res) {
  3077. res.set_file_content("./www/dir/invalid_file_path");
  3078. })
  3079. .Get("/http_response_splitting",
  3080. [&](const Request & /*req*/, Response &res) {
  3081. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3082. EXPECT_EQ(0U, res.headers.size());
  3083. EXPECT_FALSE(res.has_header("a"));
  3084. res.set_header("a", "1\nSet-Cookie: a=1");
  3085. EXPECT_EQ(0U, res.headers.size());
  3086. EXPECT_FALSE(res.has_header("a"));
  3087. res.set_header("a", "1\rSet-Cookie: a=1");
  3088. EXPECT_EQ(0U, res.headers.size());
  3089. EXPECT_FALSE(res.has_header("a"));
  3090. res.set_header("a\r\nb", "0");
  3091. EXPECT_EQ(0U, res.headers.size());
  3092. EXPECT_FALSE(res.has_header("a"));
  3093. res.set_header("a\rb", "0");
  3094. EXPECT_EQ(0U, res.headers.size());
  3095. EXPECT_FALSE(res.has_header("a"));
  3096. res.set_header("a\nb", "0");
  3097. EXPECT_EQ(0U, res.headers.size());
  3098. EXPECT_FALSE(res.has_header("a"));
  3099. res.set_redirect("1\r\nSet-Cookie: a=1");
  3100. EXPECT_EQ(0U, res.headers.size());
  3101. EXPECT_FALSE(res.has_header("Location"));
  3102. })
  3103. .Get("/slow",
  3104. [&](const Request & /*req*/, Response &res) {
  3105. std::this_thread::sleep_for(std::chrono::seconds(4));
  3106. res.set_content("slow", "text/plain");
  3107. })
  3108. #if 0
  3109. .Post("/slowpost",
  3110. [&](const Request & /*req*/, Response &res) {
  3111. std::this_thread::sleep_for(std::chrono::seconds(2));
  3112. res.set_content("slow", "text/plain");
  3113. })
  3114. #endif
  3115. .Get("/remote_addr",
  3116. [&](const Request &req, Response &res) {
  3117. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3118. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3119. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3120. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3121. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3122. #endif
  3123. res.set_content(req.remote_addr, "text/plain");
  3124. })
  3125. .Get("/local_addr",
  3126. [&](const Request &req, Response &res) {
  3127. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3128. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3129. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3130. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3131. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3132. #endif
  3133. auto local_addr = req.local_addr;
  3134. auto local_port = std::to_string(req.local_port);
  3135. res.set_content(local_addr.append(":").append(local_port),
  3136. "text/plain");
  3137. })
  3138. .Get("/endwith%",
  3139. [&](const Request & /*req*/, Response &res) {
  3140. res.set_content("Hello World!", "text/plain");
  3141. })
  3142. .Get("/a\\+\\+b",
  3143. [&](const Request &req, Response &res) {
  3144. ASSERT_TRUE(req.has_param("a +b"));
  3145. auto val = req.get_param_value("a +b");
  3146. res.set_content(val, "text/plain");
  3147. })
  3148. .Get("/", [&](const Request & /*req*/,
  3149. Response &res) { res.set_redirect("/hi"); })
  3150. .Post("/1",
  3151. [](const Request & /*req*/, Response &res) {
  3152. res.set_redirect("/2", StatusCode::SeeOther_303);
  3153. })
  3154. .Get("/2",
  3155. [](const Request & /*req*/, Response &res) {
  3156. res.set_content("redirected.", "text/plain");
  3157. res.status = StatusCode::OK_200;
  3158. })
  3159. .Post("/person",
  3160. [&](const Request &req, Response &res) {
  3161. if (req.has_param("name") && req.has_param("note")) {
  3162. persons_[req.get_param_value("name")] =
  3163. req.get_param_value("note");
  3164. } else {
  3165. res.status = StatusCode::BadRequest_400;
  3166. }
  3167. })
  3168. .Put("/person",
  3169. [&](const Request &req, Response &res) {
  3170. if (req.has_param("name") && req.has_param("note")) {
  3171. persons_[req.get_param_value("name")] =
  3172. req.get_param_value("note");
  3173. } else {
  3174. res.status = StatusCode::BadRequest_400;
  3175. }
  3176. })
  3177. .Get("/person/(.*)",
  3178. [&](const Request &req, Response &res) {
  3179. string name = req.matches[1];
  3180. if (persons_.find(name) != persons_.end()) {
  3181. auto note = persons_[name];
  3182. res.set_content(note, "text/plain");
  3183. } else {
  3184. res.status = StatusCode::NotFound_404;
  3185. }
  3186. })
  3187. .Delete("/person",
  3188. [&](const Request &req, Response &res) {
  3189. if (req.has_param("name")) {
  3190. string name = req.get_param_value("name");
  3191. if (persons_.find(name) != persons_.end()) {
  3192. persons_.erase(name);
  3193. res.set_content("DELETED", "text/plain");
  3194. } else {
  3195. res.status = StatusCode::NotFound_404;
  3196. }
  3197. } else {
  3198. res.status = StatusCode::BadRequest_400;
  3199. }
  3200. })
  3201. .Post("/x-www-form-urlencoded-json",
  3202. [&](const Request &req, Response &res) {
  3203. auto json = req.get_param_value("json");
  3204. ASSERT_EQ(JSON_DATA, json);
  3205. res.set_content(json, "appliation/json");
  3206. res.status = StatusCode::OK_200;
  3207. })
  3208. .Get("/streamed-chunked",
  3209. [&](const Request & /*req*/, Response &res) {
  3210. res.set_chunked_content_provider(
  3211. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3212. sink.os << "123";
  3213. sink.os << "456";
  3214. sink.os << "789";
  3215. sink.done();
  3216. return true;
  3217. });
  3218. })
  3219. .Get("/streamed-chunked-with-prohibited-trailer",
  3220. [&](const Request & /*req*/, Response &res) {
  3221. auto i = new int(0);
  3222. // Declare both a prohibited trailer (Content-Length) and an
  3223. // allowed one
  3224. res.set_header("Trailer", "Content-Length, X-Allowed");
  3225. res.set_chunked_content_provider(
  3226. "text/plain",
  3227. [i](size_t /*offset*/, DataSink &sink) {
  3228. switch (*i) {
  3229. case 0: sink.os << "123"; break;
  3230. case 1: sink.os << "456"; break;
  3231. case 2: sink.os << "789"; break;
  3232. case 3: {
  3233. sink.done_with_trailer(
  3234. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3235. } break;
  3236. }
  3237. (*i)++;
  3238. return true;
  3239. },
  3240. [i](bool success) {
  3241. EXPECT_TRUE(success);
  3242. delete i;
  3243. });
  3244. })
  3245. .Get("/streamed-chunked2",
  3246. [&](const Request & /*req*/, Response &res) {
  3247. auto i = new int(0);
  3248. res.set_chunked_content_provider(
  3249. "text/plain",
  3250. [i](size_t /*offset*/, DataSink &sink) {
  3251. switch (*i) {
  3252. case 0: sink.os << "123"; break;
  3253. case 1: sink.os << "456"; break;
  3254. case 2: sink.os << "789"; break;
  3255. case 3: sink.done(); break;
  3256. }
  3257. (*i)++;
  3258. return true;
  3259. },
  3260. [i](bool success) {
  3261. EXPECT_TRUE(success);
  3262. delete i;
  3263. });
  3264. })
  3265. .Get("/streamed-chunked-with-trailer",
  3266. [&](const Request & /*req*/, Response &res) {
  3267. auto i = new int(0);
  3268. res.set_header("Trailer", "Dummy1, Dummy2");
  3269. res.set_chunked_content_provider(
  3270. "text/plain",
  3271. [i](size_t /*offset*/, DataSink &sink) {
  3272. switch (*i) {
  3273. case 0: sink.os << "123"; break;
  3274. case 1: sink.os << "456"; break;
  3275. case 2: sink.os << "789"; break;
  3276. case 3: {
  3277. sink.done_with_trailer(
  3278. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3279. } break;
  3280. }
  3281. (*i)++;
  3282. return true;
  3283. },
  3284. [i](bool success) {
  3285. EXPECT_TRUE(success);
  3286. delete i;
  3287. });
  3288. })
  3289. .Get("/streamed",
  3290. [&](const Request & /*req*/, Response &res) {
  3291. res.set_content_provider(
  3292. 6, "text/plain",
  3293. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3294. sink.os << (offset < 3 ? "a" : "b");
  3295. return true;
  3296. });
  3297. })
  3298. .Get("/streamed-without-length",
  3299. [&](const Request & /*req*/, Response &res) {
  3300. auto data = new std::string("abcdefg");
  3301. res.set_content_provider(
  3302. "text/plain",
  3303. [data](size_t offset, DataSink &sink) {
  3304. if (offset < data->size()) {
  3305. sink.os << data->substr(offset);
  3306. }
  3307. sink.done();
  3308. return true;
  3309. },
  3310. [data](bool success) {
  3311. EXPECT_TRUE(success);
  3312. delete data;
  3313. });
  3314. })
  3315. .Get("/streamed-with-range",
  3316. [&](const Request &req, Response &res) {
  3317. auto data = new std::string("abcdefg");
  3318. res.set_content_provider(
  3319. data->size(), "text/plain",
  3320. [data](size_t offset, size_t length, DataSink &sink) {
  3321. size_t DATA_CHUNK_SIZE = 4;
  3322. const auto &d = *data;
  3323. auto out_len =
  3324. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3325. auto ret =
  3326. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3327. EXPECT_TRUE(ret);
  3328. return true;
  3329. },
  3330. [data, &req](bool success) {
  3331. EXPECT_EQ(success, !req.has_param("error"));
  3332. delete data;
  3333. });
  3334. })
  3335. .Get("/streamed-cancel",
  3336. [&](const Request & /*req*/, Response &res) {
  3337. res.set_content_provider(
  3338. size_t(-1), "text/plain",
  3339. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3340. sink.os << "data_chunk";
  3341. return true;
  3342. });
  3343. })
  3344. .Get("/regex-with-delimiter",
  3345. [&](const Request &req, Response & /*res*/) {
  3346. ASSERT_TRUE(req.has_param("key"));
  3347. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3348. })
  3349. .Get("/with-range",
  3350. [&](const Request & /*req*/, Response &res) {
  3351. res.set_content("abcdefg", "text/plain");
  3352. })
  3353. .Get("/test-start-time",
  3354. [&](const Request &req, Response & /*res*/) {
  3355. EXPECT_NE(req.start_time_,
  3356. std::chrono::steady_clock::time_point::min());
  3357. })
  3358. .Get("/with-range-customized-response",
  3359. [&](const Request & /*req*/, Response &res) {
  3360. res.status = StatusCode::BadRequest_400;
  3361. res.set_content(JSON_DATA, "application/json");
  3362. })
  3363. .Post("/chunked",
  3364. [&](const Request &req, Response & /*res*/) {
  3365. EXPECT_EQ(req.body, "dechunked post body");
  3366. })
  3367. .Post("/large-chunked",
  3368. [&](const Request &req, Response & /*res*/) {
  3369. std::string expected(6 * 30 * 1024u, 'a');
  3370. EXPECT_EQ(req.body, expected);
  3371. })
  3372. .Post("/multipart",
  3373. [&](const Request &req, Response & /*res*/) {
  3374. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3375. req.form.get_field_count("text2") +
  3376. req.form.get_field_count("file3") +
  3377. req.form.get_field_count("file4"));
  3378. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3379. req.form.get_file_count("file2"));
  3380. ASSERT_TRUE(!req.form.has_file("???"));
  3381. ASSERT_TRUE(!req.form.has_field("???"));
  3382. ASSERT_TRUE(req.body.empty());
  3383. {
  3384. const auto &text = req.form.get_field("text1");
  3385. EXPECT_EQ("text default", text);
  3386. }
  3387. {
  3388. const auto &text = req.form.get_field("text2");
  3389. EXPECT_EQ("aωb", text);
  3390. }
  3391. {
  3392. const auto &file = req.form.get_file("file1");
  3393. EXPECT_EQ("hello.txt", file.filename);
  3394. EXPECT_EQ("text/plain", file.content_type);
  3395. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3396. }
  3397. {
  3398. const auto &file = req.form.get_file("file2");
  3399. EXPECT_EQ("world.json", file.filename);
  3400. EXPECT_EQ("application/json", file.content_type);
  3401. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3402. }
  3403. {
  3404. const auto &text = req.form.get_field("file3");
  3405. EXPECT_EQ(0u, text.size());
  3406. }
  3407. {
  3408. const auto &text = req.form.get_field("file4");
  3409. EXPECT_EQ(0u, text.size());
  3410. }
  3411. })
  3412. .Post("/multipart/multi_file_values",
  3413. [&](const Request &req, Response & /*res*/) {
  3414. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3415. req.form.get_field_count("multi_text1"));
  3416. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3417. ASSERT_TRUE(!req.form.has_file("???"));
  3418. ASSERT_TRUE(!req.form.has_field("???"));
  3419. ASSERT_TRUE(req.body.empty());
  3420. {
  3421. const auto &text = req.form.get_field("text");
  3422. EXPECT_EQ("default text", text);
  3423. }
  3424. {
  3425. const auto &text1_values = req.form.get_fields("multi_text1");
  3426. EXPECT_EQ(2u, text1_values.size());
  3427. EXPECT_EQ("aaaaa", text1_values[0]);
  3428. EXPECT_EQ("bbbbb", text1_values[1]);
  3429. }
  3430. {
  3431. const auto &file1_values = req.form.get_files("multi_file1");
  3432. EXPECT_EQ(2u, file1_values.size());
  3433. auto file1 = file1_values[0];
  3434. EXPECT_EQ(file1.filename, "hello.txt");
  3435. EXPECT_EQ(file1.content_type, "text/plain");
  3436. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3437. auto file2 = file1_values[1];
  3438. EXPECT_EQ(file2.filename, "world.json");
  3439. EXPECT_EQ(file2.content_type, "application/json");
  3440. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3441. }
  3442. })
  3443. .Post("/empty",
  3444. [&](const Request &req, Response &res) {
  3445. EXPECT_EQ(req.body, "");
  3446. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3447. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3448. res.set_content("empty", "text/plain");
  3449. })
  3450. .Post("/empty-no-content-type",
  3451. [&](const Request &req, Response &res) {
  3452. EXPECT_EQ(req.body, "");
  3453. EXPECT_FALSE(req.has_header("Content-Type"));
  3454. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3455. res.set_content("empty-no-content-type", "text/plain");
  3456. })
  3457. .Post("/path-only",
  3458. [&](const Request &req, Response &res) {
  3459. EXPECT_EQ(req.body, "");
  3460. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3461. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3462. res.set_content("path-only", "text/plain");
  3463. })
  3464. .Post("/path-headers-only",
  3465. [&](const Request &req, Response &res) {
  3466. EXPECT_EQ(req.body, "");
  3467. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3468. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3469. EXPECT_EQ("world", req.get_header_value("hello"));
  3470. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3471. res.set_content("path-headers-only", "text/plain");
  3472. })
  3473. .Post("/post-large",
  3474. [&](const Request &req, Response &res) {
  3475. EXPECT_EQ(req.body, LARGE_DATA);
  3476. res.set_content(req.body, "text/plain");
  3477. })
  3478. .Post("/post-loopback",
  3479. [&](const Request &, Response &res,
  3480. ContentReader const &content_reader) {
  3481. std::string body;
  3482. content_reader([&](const char *data, size_t data_length) {
  3483. body.append(data, data_length);
  3484. return true;
  3485. });
  3486. res.set_content(body, "text/plain");
  3487. })
  3488. .Put("/put-loopback",
  3489. [&](const Request &, Response &res,
  3490. ContentReader const &content_reader) {
  3491. std::string body;
  3492. content_reader([&](const char *data, size_t data_length) {
  3493. body.append(data, data_length);
  3494. return true;
  3495. });
  3496. res.set_content(body, "text/plain");
  3497. })
  3498. .Patch("/patch-loopback",
  3499. [&](const Request &, Response &res,
  3500. ContentReader const &content_reader) {
  3501. std::string body;
  3502. content_reader([&](const char *data, size_t data_length) {
  3503. body.append(data, data_length);
  3504. return true;
  3505. });
  3506. res.set_content(body, "text/plain");
  3507. })
  3508. .Put("/empty-no-content-type",
  3509. [&](const Request &req, Response &res) {
  3510. EXPECT_EQ(req.body, "");
  3511. EXPECT_FALSE(req.has_header("Content-Type"));
  3512. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3513. res.set_content("empty-no-content-type", "text/plain");
  3514. })
  3515. .Put("/put",
  3516. [&](const Request &req, Response &res) {
  3517. EXPECT_EQ(req.body, "PUT");
  3518. res.set_content(req.body, "text/plain");
  3519. })
  3520. .Put("/put-large",
  3521. [&](const Request &req, Response &res) {
  3522. EXPECT_EQ(req.body, LARGE_DATA);
  3523. res.set_content(req.body, "text/plain");
  3524. })
  3525. .Patch("/patch",
  3526. [&](const Request &req, Response &res) {
  3527. EXPECT_EQ(req.body, "PATCH");
  3528. res.set_content(req.body, "text/plain");
  3529. })
  3530. .Delete("/delete",
  3531. [&](const Request & /*req*/, Response &res) {
  3532. res.set_content("DELETE", "text/plain");
  3533. })
  3534. .Delete("/delete-body",
  3535. [&](const Request &req, Response &res) {
  3536. EXPECT_EQ(req.body, "content");
  3537. res.set_content(req.body, "text/plain");
  3538. })
  3539. .Options(R"(\*)",
  3540. [&](const Request & /*req*/, Response &res) {
  3541. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3542. })
  3543. .Get("/request-target",
  3544. [&](const Request &req, Response & /*res*/) {
  3545. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3546. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3547. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3548. })
  3549. .Get("/long-query-value",
  3550. [&](const Request &req, Response & /*res*/) {
  3551. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3552. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3553. })
  3554. .Get("/too-long-query-value",
  3555. [&](const Request &req, Response & /*res*/) {
  3556. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3557. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3558. })
  3559. .Get("/array-param",
  3560. [&](const Request &req, Response & /*res*/) {
  3561. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3562. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3563. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3564. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3565. })
  3566. .Get("/array-param-values",
  3567. [&](const Request &req, Response & /*res*/) {
  3568. auto values = req.get_param_values("array");
  3569. EXPECT_EQ(3u, values.size());
  3570. EXPECT_EQ("value1", values[0]);
  3571. EXPECT_EQ("value2", values[1]);
  3572. EXPECT_EQ("value3", values[2]);
  3573. auto empty = req.get_param_values("nonexistent");
  3574. EXPECT_TRUE(empty.empty());
  3575. })
  3576. .Post("/validate-no-multiple-headers",
  3577. [&](const Request &req, Response & /*res*/) {
  3578. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3579. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3580. })
  3581. .Post("/content_receiver",
  3582. [&](const Request &req, Response &res,
  3583. const ContentReader &content_reader) {
  3584. if (req.is_multipart_form_data()) {
  3585. std::vector<FormData> items;
  3586. content_reader(
  3587. [&](const FormData &file) {
  3588. items.push_back(file);
  3589. return true;
  3590. },
  3591. [&](const char *data, size_t data_length) {
  3592. items.back().content.append(data, data_length);
  3593. return true;
  3594. });
  3595. EXPECT_EQ(5u, items.size());
  3596. {
  3597. const auto &file = get_file_value(items, "text1");
  3598. EXPECT_TRUE(file.filename.empty());
  3599. EXPECT_EQ("text default", file.content);
  3600. }
  3601. {
  3602. const auto &file = get_file_value(items, "text2");
  3603. EXPECT_TRUE(file.filename.empty());
  3604. EXPECT_EQ("aωb", file.content);
  3605. }
  3606. {
  3607. const auto &file = get_file_value(items, "file1");
  3608. EXPECT_EQ("hello.txt", file.filename);
  3609. EXPECT_EQ("text/plain", file.content_type);
  3610. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3611. }
  3612. {
  3613. const auto &file = get_file_value(items, "file2");
  3614. EXPECT_EQ("world.json", file.filename);
  3615. EXPECT_EQ("application/json", file.content_type);
  3616. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3617. }
  3618. {
  3619. const auto &file = get_file_value(items, "file3");
  3620. EXPECT_TRUE(file.filename.empty());
  3621. EXPECT_EQ("application/octet-stream", file.content_type);
  3622. EXPECT_EQ(0u, file.content.size());
  3623. }
  3624. } else {
  3625. std::string body;
  3626. content_reader([&](const char *data, size_t data_length) {
  3627. EXPECT_EQ(7U, data_length);
  3628. body.append(data, data_length);
  3629. return true;
  3630. });
  3631. EXPECT_EQ(body, "content");
  3632. res.set_content(body, "text/plain");
  3633. }
  3634. })
  3635. .Put("/content_receiver",
  3636. [&](const Request & /*req*/, Response &res,
  3637. const ContentReader &content_reader) {
  3638. std::string body;
  3639. content_reader([&](const char *data, size_t data_length) {
  3640. body.append(data, data_length);
  3641. return true;
  3642. });
  3643. EXPECT_EQ(body, "content");
  3644. res.set_content(body, "text/plain");
  3645. })
  3646. .Patch("/content_receiver",
  3647. [&](const Request & /*req*/, Response &res,
  3648. const ContentReader &content_reader) {
  3649. std::string body;
  3650. content_reader([&](const char *data, size_t data_length) {
  3651. body.append(data, data_length);
  3652. return true;
  3653. });
  3654. EXPECT_EQ(body, "content");
  3655. res.set_content(body, "text/plain");
  3656. })
  3657. .Post("/query-string-and-body",
  3658. [&](const Request &req, Response & /*res*/) {
  3659. ASSERT_TRUE(req.has_param("key"));
  3660. EXPECT_EQ(req.get_param_value("key"), "value");
  3661. EXPECT_EQ(req.body, "content");
  3662. })
  3663. .Get("/last-request",
  3664. [&](const Request &req, Response & /*res*/) {
  3665. EXPECT_EQ("close", req.get_header_value("Connection"));
  3666. })
  3667. .Get(R"(/redirect/(\d+))",
  3668. [&](const Request &req, Response &res) {
  3669. auto num = std::stoi(req.matches[1]) + 1;
  3670. std::string url = "/redirect/" + std::to_string(num);
  3671. res.set_redirect(url);
  3672. })
  3673. .Post("/binary",
  3674. [&](const Request &req, Response &res) {
  3675. EXPECT_EQ(4U, req.body.size());
  3676. EXPECT_EQ("application/octet-stream",
  3677. req.get_header_value("Content-Type"));
  3678. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3679. res.set_content(req.body, "application/octet-stream");
  3680. })
  3681. .Put("/binary",
  3682. [&](const Request &req, Response &res) {
  3683. EXPECT_EQ(4U, req.body.size());
  3684. EXPECT_EQ("application/octet-stream",
  3685. req.get_header_value("Content-Type"));
  3686. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3687. res.set_content(req.body, "application/octet-stream");
  3688. })
  3689. .Patch("/binary",
  3690. [&](const Request &req, Response &res) {
  3691. EXPECT_EQ(4U, req.body.size());
  3692. EXPECT_EQ("application/octet-stream",
  3693. req.get_header_value("Content-Type"));
  3694. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3695. res.set_content(req.body, "application/octet-stream");
  3696. })
  3697. .Delete("/binary",
  3698. [&](const Request &req, Response &res) {
  3699. EXPECT_EQ(4U, req.body.size());
  3700. EXPECT_EQ("application/octet-stream",
  3701. req.get_header_value("Content-Type"));
  3702. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3703. res.set_content(req.body, "application/octet-stream");
  3704. })
  3705. .Get("/issue1772",
  3706. [&](const Request & /*req*/, Response &res) {
  3707. res.status = 401;
  3708. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3709. })
  3710. .Delete("/issue609",
  3711. [](const httplib::Request &, httplib::Response &res,
  3712. const httplib::ContentReader &) {
  3713. res.set_content("ok", "text/plain");
  3714. })
  3715. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3716. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3717. .Get("/compress",
  3718. [&](const Request & /*req*/, Response &res) {
  3719. res.set_content(
  3720. "12345678901234567890123456789012345678901234567890123456789"
  3721. "01234567890123456789012345678901234567890",
  3722. "text/plain");
  3723. })
  3724. .Get("/compress-with-charset",
  3725. [&](const Request & /*req*/, Response &res) {
  3726. res.set_content(
  3727. "12345678901234567890123456789012345678901234567890123456789"
  3728. "01234567890123456789012345678901234567890",
  3729. "application/json; charset=utf-8");
  3730. })
  3731. .Get("/nocompress",
  3732. [&](const Request & /*req*/, Response &res) {
  3733. res.set_content(
  3734. "12345678901234567890123456789012345678901234567890123456789"
  3735. "01234567890123456789012345678901234567890",
  3736. "application/octet-stream");
  3737. })
  3738. .Post("/compress-multipart",
  3739. [&](const Request &req, Response & /*res*/) {
  3740. EXPECT_EQ(2u, req.form.fields.size());
  3741. ASSERT_TRUE(!req.form.has_field("???"));
  3742. {
  3743. const auto &text = req.form.get_field("key1");
  3744. EXPECT_EQ("test", text);
  3745. }
  3746. {
  3747. const auto &text = req.form.get_field("key2");
  3748. EXPECT_EQ("--abcdefg123", text);
  3749. }
  3750. })
  3751. #endif
  3752. ;
  3753. persons_["john"] = "programmer";
  3754. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3755. svr_.wait_until_ready();
  3756. }
  3757. virtual void TearDown() {
  3758. svr_.stop();
  3759. if (!request_threads_.empty()) {
  3760. std::this_thread::sleep_for(std::chrono::seconds(1));
  3761. for (auto &t : request_threads_) {
  3762. t.join();
  3763. }
  3764. }
  3765. t_.join();
  3766. }
  3767. map<string, string> persons_;
  3768. #ifdef CPPHTTPLIB_SSL_ENABLED
  3769. SSLClient cli_;
  3770. SSLServer svr_;
  3771. #else
  3772. Client cli_;
  3773. Server svr_;
  3774. #endif
  3775. thread t_;
  3776. std::vector<thread> request_threads_;
  3777. };
  3778. TEST_F(ServerTest, GetMethod200) {
  3779. auto res = cli_.Get("/hi");
  3780. ASSERT_TRUE(res);
  3781. EXPECT_EQ("HTTP/1.1", res->version);
  3782. EXPECT_EQ(StatusCode::OK_200, res->status);
  3783. EXPECT_EQ("OK", res->reason);
  3784. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3785. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3786. EXPECT_EQ("Hello World!", res->body);
  3787. }
  3788. TEST_F(ServerTest, GetEmptyFile) {
  3789. auto res = cli_.Get("/empty_file");
  3790. ASSERT_TRUE(res);
  3791. EXPECT_EQ(StatusCode::OK_200, res->status);
  3792. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3793. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3794. EXPECT_EQ("", res->body);
  3795. }
  3796. TEST_F(ServerTest, GetFileContent) {
  3797. auto res = cli_.Get("/file_content");
  3798. ASSERT_TRUE(res);
  3799. EXPECT_EQ(StatusCode::OK_200, res->status);
  3800. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3801. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3802. EXPECT_EQ("test.html", res->body);
  3803. }
  3804. TEST_F(ServerTest, GetFileContentWithRange) {
  3805. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3806. ASSERT_TRUE(res);
  3807. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3808. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3809. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3810. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3811. EXPECT_EQ("est", res->body);
  3812. }
  3813. TEST_F(ServerTest, GetFileContentWithContentType) {
  3814. auto res = cli_.Get("/file_content_with_content_type");
  3815. ASSERT_TRUE(res);
  3816. EXPECT_EQ(StatusCode::OK_200, res->status);
  3817. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3818. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3819. EXPECT_EQ("file\n", res->body);
  3820. }
  3821. TEST_F(ServerTest, GetInvalidFileContent) {
  3822. auto res = cli_.Get("/invalid_file_content");
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3825. }
  3826. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3827. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3828. ASSERT_TRUE(res);
  3829. EXPECT_EQ("HTTP/1.1", res->version);
  3830. EXPECT_EQ(StatusCode::OK_200, res->status);
  3831. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3832. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3833. EXPECT_EQ("Hello World!", res->body);
  3834. }
  3835. TEST_F(ServerTest, GetMethod302) {
  3836. auto res = cli_.Get("/");
  3837. ASSERT_TRUE(res);
  3838. EXPECT_EQ(StatusCode::Found_302, res->status);
  3839. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3840. }
  3841. TEST_F(ServerTest, GetMethod302Redirect) {
  3842. cli_.set_follow_location(true);
  3843. auto res = cli_.Get("/");
  3844. ASSERT_TRUE(res);
  3845. EXPECT_EQ(StatusCode::OK_200, res->status);
  3846. EXPECT_EQ("Hello World!", res->body);
  3847. EXPECT_EQ("/hi", res->location);
  3848. }
  3849. TEST_F(ServerTest, GetMethod404) {
  3850. auto res = cli_.Get("/invalid");
  3851. ASSERT_TRUE(res);
  3852. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3853. }
  3854. TEST_F(ServerTest, HeadMethod200) {
  3855. auto res = cli_.Head("/hi");
  3856. ASSERT_TRUE(res);
  3857. EXPECT_EQ(StatusCode::OK_200, res->status);
  3858. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3859. EXPECT_TRUE(res->body.empty());
  3860. }
  3861. TEST_F(ServerTest, HeadMethod200Static) {
  3862. auto res = cli_.Head("/mount/dir/index.html");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3866. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3867. EXPECT_TRUE(res->body.empty());
  3868. }
  3869. TEST_F(ServerTest, HeadMethod404) {
  3870. auto res = cli_.Head("/invalid");
  3871. ASSERT_TRUE(res);
  3872. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3873. EXPECT_TRUE(res->body.empty());
  3874. }
  3875. TEST_F(ServerTest, GetMethodPersonJohn) {
  3876. auto res = cli_.Get("/person/john");
  3877. ASSERT_TRUE(res);
  3878. EXPECT_EQ(StatusCode::OK_200, res->status);
  3879. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3880. EXPECT_EQ("programmer", res->body);
  3881. }
  3882. TEST_F(ServerTest, PostMethod1) {
  3883. auto res = cli_.Get("/person/john1");
  3884. ASSERT_TRUE(res);
  3885. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3886. res = cli_.Post("/person", "name=john1&note=coder",
  3887. "application/x-www-form-urlencoded");
  3888. ASSERT_TRUE(res);
  3889. ASSERT_EQ(StatusCode::OK_200, res->status);
  3890. res = cli_.Get("/person/john1");
  3891. ASSERT_TRUE(res);
  3892. ASSERT_EQ(StatusCode::OK_200, res->status);
  3893. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3894. ASSERT_EQ("coder", res->body);
  3895. }
  3896. TEST_F(ServerTest, PostMethod2) {
  3897. auto res = cli_.Get("/person/john2");
  3898. ASSERT_TRUE(res);
  3899. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3900. Params params;
  3901. params.emplace("name", "john2");
  3902. params.emplace("note", "coder");
  3903. res = cli_.Post("/person", params);
  3904. ASSERT_TRUE(res);
  3905. ASSERT_EQ(StatusCode::OK_200, res->status);
  3906. res = cli_.Get("/person/john2");
  3907. ASSERT_TRUE(res);
  3908. ASSERT_EQ(StatusCode::OK_200, res->status);
  3909. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3910. ASSERT_EQ("coder", res->body);
  3911. }
  3912. TEST_F(ServerTest, PutMethod3) {
  3913. auto res = cli_.Get("/person/john3");
  3914. ASSERT_TRUE(res);
  3915. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3916. Params params;
  3917. params.emplace("name", "john3");
  3918. params.emplace("note", "coder");
  3919. res = cli_.Put("/person", params);
  3920. ASSERT_TRUE(res);
  3921. ASSERT_EQ(StatusCode::OK_200, res->status);
  3922. res = cli_.Get("/person/john3");
  3923. ASSERT_TRUE(res);
  3924. ASSERT_EQ(StatusCode::OK_200, res->status);
  3925. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3926. ASSERT_EQ("coder", res->body);
  3927. }
  3928. TEST_F(ServerTest, DeleteMethod1) {
  3929. auto res = cli_.Get("/person/john4");
  3930. ASSERT_TRUE(res);
  3931. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3932. Params params;
  3933. params.emplace("name", "john4");
  3934. params.emplace("note", "coder");
  3935. res = cli_.Post("/person", params);
  3936. ASSERT_TRUE(res);
  3937. ASSERT_EQ(StatusCode::OK_200, res->status);
  3938. res = cli_.Get("/person/john4");
  3939. ASSERT_TRUE(res);
  3940. ASSERT_EQ(StatusCode::OK_200, res->status);
  3941. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3942. ASSERT_EQ("coder", res->body);
  3943. Params delete_params;
  3944. delete_params.emplace("name", "john4");
  3945. res = cli_.Delete("/person", delete_params);
  3946. ASSERT_TRUE(res);
  3947. ASSERT_EQ(StatusCode::OK_200, res->status);
  3948. ASSERT_EQ("DELETED", res->body);
  3949. res = cli_.Get("/person/john4");
  3950. ASSERT_TRUE(res);
  3951. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3952. }
  3953. TEST_F(ServerTest, DeleteMethod2) {
  3954. auto res = cli_.Get("/person/john5");
  3955. ASSERT_TRUE(res);
  3956. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3957. Params params;
  3958. params.emplace("name", "john5");
  3959. params.emplace("note", "developer");
  3960. res = cli_.Post("/person", params);
  3961. ASSERT_TRUE(res);
  3962. ASSERT_EQ(StatusCode::OK_200, res->status);
  3963. res = cli_.Get("/person/john5");
  3964. ASSERT_TRUE(res);
  3965. ASSERT_EQ(StatusCode::OK_200, res->status);
  3966. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3967. ASSERT_EQ("developer", res->body);
  3968. Params delete_params;
  3969. delete_params.emplace("name", "john5");
  3970. Headers headers;
  3971. headers.emplace("Custom-Header", "test-value");
  3972. res = cli_.Delete("/person", headers, delete_params);
  3973. ASSERT_TRUE(res);
  3974. ASSERT_EQ(StatusCode::OK_200, res->status);
  3975. ASSERT_EQ("DELETED", res->body);
  3976. res = cli_.Get("/person/john5");
  3977. ASSERT_TRUE(res);
  3978. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3979. }
  3980. TEST_F(ServerTest, DeleteMethod3) {
  3981. auto res = cli_.Get("/person/john6");
  3982. ASSERT_TRUE(res);
  3983. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3984. Params params;
  3985. params.emplace("name", "john6");
  3986. params.emplace("note", "tester");
  3987. res = cli_.Post("/person", params);
  3988. ASSERT_TRUE(res);
  3989. ASSERT_EQ(StatusCode::OK_200, res->status);
  3990. res = cli_.Get("/person/john6");
  3991. ASSERT_TRUE(res);
  3992. ASSERT_EQ(StatusCode::OK_200, res->status);
  3993. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3994. ASSERT_EQ("tester", res->body);
  3995. Params delete_params;
  3996. delete_params.emplace("name", "john6");
  3997. Headers headers;
  3998. headers.emplace("Custom-Header", "test-value");
  3999. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4000. ASSERT_TRUE(res);
  4001. ASSERT_EQ(StatusCode::OK_200, res->status);
  4002. ASSERT_EQ("DELETED", res->body);
  4003. res = cli_.Get("/person/john6");
  4004. ASSERT_TRUE(res);
  4005. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4006. }
  4007. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4008. Params params;
  4009. params.emplace("json", JSON_DATA);
  4010. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4011. ASSERT_TRUE(res);
  4012. ASSERT_EQ(StatusCode::OK_200, res->status);
  4013. ASSERT_EQ(JSON_DATA, res->body);
  4014. }
  4015. TEST_F(ServerTest, PostEmptyContent) {
  4016. auto res = cli_.Post("/empty", "", "text/plain");
  4017. ASSERT_TRUE(res);
  4018. ASSERT_EQ(StatusCode::OK_200, res->status);
  4019. ASSERT_EQ("empty", res->body);
  4020. }
  4021. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4022. auto res = cli_.Post("/empty-no-content-type");
  4023. ASSERT_TRUE(res);
  4024. ASSERT_EQ(StatusCode::OK_200, res->status);
  4025. ASSERT_EQ("empty-no-content-type", res->body);
  4026. }
  4027. TEST_F(ServerTest, PostPathOnly) {
  4028. auto res = cli_.Post("/path-only");
  4029. ASSERT_TRUE(res);
  4030. ASSERT_EQ(StatusCode::OK_200, res->status);
  4031. ASSERT_EQ("path-only", res->body);
  4032. }
  4033. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4034. auto res = cli_.Post("/path-headers-only",
  4035. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4036. ASSERT_TRUE(res);
  4037. ASSERT_EQ(StatusCode::OK_200, res->status);
  4038. ASSERT_EQ("path-headers-only", res->body);
  4039. }
  4040. TEST_F(ServerTest, PostLarge) {
  4041. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4042. ASSERT_TRUE(res);
  4043. ASSERT_EQ(StatusCode::OK_200, res->status);
  4044. EXPECT_EQ(LARGE_DATA, res->body);
  4045. }
  4046. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4047. auto res = cli_.Put("/empty-no-content-type");
  4048. ASSERT_TRUE(res);
  4049. ASSERT_EQ(StatusCode::OK_200, res->status);
  4050. ASSERT_EQ("empty-no-content-type", res->body);
  4051. }
  4052. TEST_F(ServerTest, GetMethodDir) {
  4053. auto res = cli_.Get("/dir/");
  4054. ASSERT_TRUE(res);
  4055. EXPECT_EQ(StatusCode::OK_200, res->status);
  4056. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4057. auto body = R"(<html>
  4058. <head>
  4059. </head>
  4060. <body>
  4061. <a href="/dir/test.html">Test</a>
  4062. <a href="/hi">hi</a>
  4063. </body>
  4064. </html>
  4065. )";
  4066. EXPECT_EQ(body, res->body);
  4067. }
  4068. TEST_F(ServerTest, GetMethodDirTest) {
  4069. auto res = cli_.Get("/dir/test.html");
  4070. ASSERT_TRUE(res);
  4071. EXPECT_EQ(StatusCode::OK_200, res->status);
  4072. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4073. EXPECT_EQ("test.html", res->body);
  4074. }
  4075. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4076. auto res = cli_.Get("/dir/../dir/test.html");
  4077. ASSERT_TRUE(res);
  4078. EXPECT_EQ(StatusCode::OK_200, res->status);
  4079. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4080. EXPECT_EQ("test.html", res->body);
  4081. }
  4082. TEST_F(ServerTest, GetMethodInvalidPath) {
  4083. auto res = cli_.Get("/dir/../test.html");
  4084. ASSERT_TRUE(res);
  4085. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4086. }
  4087. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4088. auto res = cli_.Get("/../www/dir/test.html");
  4089. ASSERT_TRUE(res);
  4090. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4091. }
  4092. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4093. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4094. ASSERT_TRUE(res);
  4095. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4096. }
  4097. TEST_F(ServerTest, GetMethodDirMountTest) {
  4098. auto res = cli_.Get("/mount/dir/test.html");
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::OK_200, res->status);
  4101. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4102. EXPECT_EQ("test.html", res->body);
  4103. }
  4104. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4105. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4106. ASSERT_TRUE(res);
  4107. EXPECT_EQ(StatusCode::OK_200, res->status);
  4108. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4109. EXPECT_EQ("test.html", res->body);
  4110. }
  4111. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4112. auto res = cli_.Get("/mount/dir/../test.html");
  4113. ASSERT_TRUE(res);
  4114. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4115. }
  4116. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4117. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4118. ASSERT_TRUE(res);
  4119. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4120. }
  4121. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4122. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4123. ASSERT_TRUE(res);
  4124. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4125. }
  4126. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4127. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4128. ASSERT_TRUE(res);
  4129. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4130. }
  4131. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4132. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4133. ASSERT_TRUE(res);
  4134. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4135. }
  4136. TEST_F(ServerTest, PostMethod303) {
  4137. auto res = cli_.Post("/1", "body", "text/plain");
  4138. ASSERT_TRUE(res);
  4139. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4140. EXPECT_EQ("/2", res->get_header_value("Location"));
  4141. }
  4142. TEST_F(ServerTest, PostMethod303Redirect) {
  4143. cli_.set_follow_location(true);
  4144. auto res = cli_.Post("/1", "body", "text/plain");
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::OK_200, res->status);
  4147. EXPECT_EQ("redirected.", res->body);
  4148. EXPECT_EQ("/2", res->location);
  4149. }
  4150. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4151. auto res = cli_.Get("/dir/test.abcde");
  4152. ASSERT_TRUE(res);
  4153. EXPECT_EQ(StatusCode::OK_200, res->status);
  4154. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4155. EXPECT_EQ("abcde", res->body);
  4156. }
  4157. TEST_F(ServerTest, StaticFileRange) {
  4158. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4159. ASSERT_TRUE(res);
  4160. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4161. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4162. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4163. EXPECT_EQ(true, res->has_header("Content-Range"));
  4164. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4165. EXPECT_EQ(std::string("cd"), res->body);
  4166. }
  4167. TEST_F(ServerTest, StaticFileRanges) {
  4168. auto res =
  4169. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  4170. ASSERT_TRUE(res);
  4171. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4172. EXPECT_TRUE(
  4173. res->get_header_value("Content-Type")
  4174. .find(
  4175. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4176. 0);
  4177. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4178. }
  4179. TEST_F(ServerTest, StaticFileRangeHead) {
  4180. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4181. ASSERT_TRUE(res);
  4182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4183. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4184. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4185. EXPECT_EQ(true, res->has_header("Content-Range"));
  4186. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4187. }
  4188. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4189. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  4190. ASSERT_TRUE(res);
  4191. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4193. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(true, res->has_header("Content-Range"));
  4195. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4196. res->get_header_value("Content-Range"));
  4197. EXPECT_EQ("LAST\n", res->body);
  4198. }
  4199. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4200. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  4201. ASSERT_TRUE(res);
  4202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4203. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4204. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4205. EXPECT_EQ(true, res->has_header("Content-Range"));
  4206. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4207. }
  4208. TEST_F(ServerTest, StaticFileBigFile) {
  4209. auto res = cli_.Get("/dir/1MB.txt");
  4210. ASSERT_TRUE(res);
  4211. EXPECT_EQ(StatusCode::OK_200, res->status);
  4212. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4213. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4214. }
  4215. TEST_F(ServerTest, InvalidBaseDirMount) {
  4216. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4217. }
  4218. TEST_F(ServerTest, Binary) {
  4219. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4220. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4221. "application/octet-stream");
  4222. ASSERT_TRUE(res);
  4223. ASSERT_EQ(StatusCode::OK_200, res->status);
  4224. ASSERT_EQ(4U, res->body.size());
  4225. res = cli_.Put("/binary", binary.data(), binary.size(),
  4226. "application/octet-stream");
  4227. ASSERT_TRUE(res);
  4228. ASSERT_EQ(StatusCode::OK_200, res->status);
  4229. ASSERT_EQ(4U, res->body.size());
  4230. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4231. "application/octet-stream");
  4232. ASSERT_TRUE(res);
  4233. ASSERT_EQ(StatusCode::OK_200, res->status);
  4234. ASSERT_EQ(4U, res->body.size());
  4235. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4236. "application/octet-stream");
  4237. ASSERT_TRUE(res);
  4238. ASSERT_EQ(StatusCode::OK_200, res->status);
  4239. ASSERT_EQ(4U, res->body.size());
  4240. }
  4241. TEST_F(ServerTest, BinaryString) {
  4242. auto binary = std::string("\x00\x01\x02\x03", 4);
  4243. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4244. ASSERT_TRUE(res);
  4245. ASSERT_EQ(StatusCode::OK_200, res->status);
  4246. ASSERT_EQ(4U, res->body.size());
  4247. res = cli_.Put("/binary", binary, "application/octet-stream");
  4248. ASSERT_TRUE(res);
  4249. ASSERT_EQ(StatusCode::OK_200, res->status);
  4250. ASSERT_EQ(4U, res->body.size());
  4251. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4252. ASSERT_TRUE(res);
  4253. ASSERT_EQ(StatusCode::OK_200, res->status);
  4254. ASSERT_EQ(4U, res->body.size());
  4255. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4256. ASSERT_TRUE(res);
  4257. ASSERT_EQ(StatusCode::OK_200, res->status);
  4258. ASSERT_EQ(4U, res->body.size());
  4259. }
  4260. TEST_F(ServerTest, EmptyRequest) {
  4261. auto res = cli_.Get("");
  4262. ASSERT_TRUE(!res);
  4263. EXPECT_EQ(Error::Connection, res.error());
  4264. }
  4265. TEST_F(ServerTest, LongRequest) {
  4266. std::string request;
  4267. for (size_t i = 0; i < 545; i++) {
  4268. request += "/TooLongRequest";
  4269. }
  4270. request += "OK";
  4271. auto res = cli_.Get(request.c_str());
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4274. }
  4275. TEST_F(ServerTest, TooLongRequest) {
  4276. std::string request;
  4277. for (size_t i = 0; i < 546; i++) {
  4278. request += "/TooLongRequest";
  4279. }
  4280. request += "_NG";
  4281. auto start = std::chrono::high_resolution_clock::now();
  4282. cli_.set_keep_alive(true);
  4283. auto res = cli_.Get(request.c_str());
  4284. auto end = std::chrono::high_resolution_clock::now();
  4285. auto elapsed =
  4286. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4287. .count();
  4288. ASSERT_TRUE(res);
  4289. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4290. EXPECT_LE(elapsed, 1000);
  4291. EXPECT_EQ("close", res->get_header_value("Connection"));
  4292. EXPECT_FALSE(cli_.is_socket_open());
  4293. }
  4294. TEST_F(ServerTest, AlmostTooLongRequest) {
  4295. // test for #2046 - URI length check shouldn't include other content on req
  4296. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4297. // leading /, space, HTTP/1.1)
  4298. std::string request =
  4299. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4300. auto res = cli_.Get(request.c_str());
  4301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4302. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4303. }
  4304. TEST_F(ServerTest, LongHeader) {
  4305. Request req;
  4306. req.method = "GET";
  4307. req.path = "/hi";
  4308. std::string host_and_port;
  4309. host_and_port += HOST;
  4310. host_and_port += ":";
  4311. host_and_port += std::to_string(PORT);
  4312. req.headers.emplace("Host", host_and_port.c_str());
  4313. req.headers.emplace("Accept", "*/*");
  4314. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4315. req.headers.emplace(
  4316. "Header-Name",
  4317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4320. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4321. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4322. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4323. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4324. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4325. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4326. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4327. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4328. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4329. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4330. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4331. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4332. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4333. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4334. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4335. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4336. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4338. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4339. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4340. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4341. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4342. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4343. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4344. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4345. "@@@@@@@@@@@@@@@@");
  4346. auto res = std::make_shared<Response>();
  4347. auto error = Error::Success;
  4348. auto ret = cli_.send(req, *res, error);
  4349. ASSERT_TRUE(ret);
  4350. EXPECT_EQ(StatusCode::OK_200, res->status);
  4351. }
  4352. TEST_F(ServerTest, LongQueryValue) {
  4353. auto start = std::chrono::high_resolution_clock::now();
  4354. cli_.set_keep_alive(true);
  4355. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4356. auto end = std::chrono::high_resolution_clock::now();
  4357. auto elapsed =
  4358. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4359. .count();
  4360. ASSERT_TRUE(res);
  4361. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4362. EXPECT_LE(elapsed, 1000);
  4363. EXPECT_EQ("close", res->get_header_value("Connection"));
  4364. EXPECT_FALSE(cli_.is_socket_open());
  4365. }
  4366. TEST_F(ServerTest, TooLongQueryValue) {
  4367. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4368. ASSERT_FALSE(res);
  4369. EXPECT_EQ(Error::Read, res.error());
  4370. }
  4371. TEST_F(ServerTest, TooLongHeader) {
  4372. Request req;
  4373. req.method = "GET";
  4374. req.path = "/hi";
  4375. std::string host_and_port;
  4376. host_and_port += HOST;
  4377. host_and_port += ":";
  4378. host_and_port += std::to_string(PORT);
  4379. req.headers.emplace("Host", host_and_port.c_str());
  4380. req.headers.emplace("Accept", "*/*");
  4381. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4382. req.headers.emplace(
  4383. "Header-Name",
  4384. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4385. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4386. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4387. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4388. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4389. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4390. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4391. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4392. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4393. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4394. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4395. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4396. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4397. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4398. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4399. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4400. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4401. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4402. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4403. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4404. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4405. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4406. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4407. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4408. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4409. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4410. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4411. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4412. "@@@@@@@@@@@@@@@@@");
  4413. auto res = std::make_shared<Response>();
  4414. auto error = Error::Success;
  4415. auto ret = cli_.send(req, *res, error);
  4416. ASSERT_TRUE(ret);
  4417. EXPECT_EQ(StatusCode::OK_200, res->status);
  4418. }
  4419. TEST_F(ServerTest, HeaderCountAtLimit) {
  4420. // Test with headers just under the 100 limit
  4421. httplib::Headers headers;
  4422. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4423. // This should keep us just under the 100 header limit
  4424. for (int i = 0; i < 95; i++) {
  4425. std::string name = "X-Test-Header-" + std::to_string(i);
  4426. std::string value = "value" + std::to_string(i);
  4427. headers.emplace(name, value);
  4428. }
  4429. // This should work fine as we're under the limit
  4430. auto res = cli_.Get("/hi", headers);
  4431. EXPECT_TRUE(res);
  4432. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4433. }
  4434. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4435. // Test with many headers to exceed the 100 limit
  4436. httplib::Headers headers;
  4437. // Add 150 headers to definitely exceed the 100 limit
  4438. for (int i = 0; i < 150; i++) {
  4439. std::string name = "X-Test-Header-" + std::to_string(i);
  4440. std::string value = "value" + std::to_string(i);
  4441. headers.emplace(name, value);
  4442. }
  4443. // This should fail due to exceeding header count limit
  4444. cli_.set_keep_alive(true);
  4445. auto res = cli_.Get("/hi", headers);
  4446. // The server should respond with 400 Bad Request
  4447. ASSERT_TRUE(res);
  4448. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4449. EXPECT_EQ("close", res->get_header_value("Connection"));
  4450. EXPECT_FALSE(cli_.is_socket_open());
  4451. }
  4452. TEST_F(ServerTest, PercentEncoding) {
  4453. auto res = cli_.Get("/e%6edwith%");
  4454. ASSERT_TRUE(res);
  4455. EXPECT_EQ(StatusCode::OK_200, res->status);
  4456. }
  4457. TEST_F(ServerTest, PercentEncodingUnicode) {
  4458. auto res = cli_.Get("/e%u006edwith%");
  4459. ASSERT_TRUE(res);
  4460. EXPECT_EQ(StatusCode::OK_200, res->status);
  4461. }
  4462. TEST_F(ServerTest, InvalidPercentEncoding) {
  4463. auto res = cli_.Get("/%endwith%");
  4464. ASSERT_TRUE(res);
  4465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4466. }
  4467. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4468. auto res = cli_.Get("/%uendwith%");
  4469. ASSERT_TRUE(res);
  4470. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4471. }
  4472. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4473. auto res = cli_.Get("/hello?aaa=bbb%");
  4474. ASSERT_TRUE(res);
  4475. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4476. }
  4477. TEST_F(ServerTest, PlusSignEncoding) {
  4478. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::OK_200, res->status);
  4481. EXPECT_EQ("a +b", res->body);
  4482. }
  4483. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4484. // This test simulates a potential DoS attack using many headers
  4485. // to verify our security fix prevents memory exhaustion
  4486. httplib::Headers attack_headers;
  4487. // Attempt to add many headers like an attacker would (200 headers to far
  4488. // exceed limit)
  4489. for (int i = 0; i < 200; i++) {
  4490. std::string name = "X-Attack-Header-" + std::to_string(i);
  4491. std::string value = "attack_payload_" + std::to_string(i);
  4492. attack_headers.emplace(name, value);
  4493. }
  4494. // Try to POST with excessive headers
  4495. cli_.set_keep_alive(true);
  4496. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4497. // Should either fail or return 400 Bad Request due to security limit
  4498. if (res) {
  4499. // If we get a response, it should be 400 Bad Request
  4500. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4501. EXPECT_EQ("close", res->get_header_value("Connection"));
  4502. }
  4503. EXPECT_FALSE(cli_.is_socket_open());
  4504. }
  4505. TEST_F(ServerTest, MultipartFormData) {
  4506. UploadFormDataItems items = {
  4507. {"text1", "text default", "", ""},
  4508. {"text2", "aωb", "", ""},
  4509. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4510. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4511. {"file3", "", "", "application/octet-stream"},
  4512. {"file4", "", "", " application/json tmp-string "}};
  4513. auto res = cli_.Post("/multipart", items);
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. }
  4517. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4518. UploadFormDataItems items = {
  4519. {"text", "default text", "", ""},
  4520. {"multi_text1", "aaaaa", "", ""},
  4521. {"multi_text1", "bbbbb", "", ""},
  4522. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4523. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4524. "application/json"},
  4525. };
  4526. auto res = cli_.Post("/multipart/multi_file_values", items);
  4527. ASSERT_TRUE(res);
  4528. EXPECT_EQ(StatusCode::OK_200, res->status);
  4529. }
  4530. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4531. auto res = cli_.Get("/hi");
  4532. ASSERT_TRUE(res);
  4533. EXPECT_EQ(StatusCode::OK_200, res->status);
  4534. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4535. EXPECT_EQ("Hello World!", res->body);
  4536. }
  4537. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4538. Request req;
  4539. req.method = "POST";
  4540. req.path = "/chunked";
  4541. std::string host_and_port;
  4542. host_and_port += HOST;
  4543. host_and_port += ":";
  4544. host_and_port += std::to_string(PORT);
  4545. req.headers.emplace("Host", host_and_port.c_str());
  4546. req.headers.emplace("Accept", "*/*");
  4547. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4548. req.headers.emplace("Content-Type", "text/plain");
  4549. req.headers.emplace("Content-Length", "0");
  4550. req.headers.emplace(
  4551. "Transfer-Encoding",
  4552. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4553. // Client does not chunk, so make a chunked body manually.
  4554. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4555. auto res = std::make_shared<Response>();
  4556. auto error = Error::Success;
  4557. auto ret = cli_.send(req, *res, error);
  4558. ASSERT_TRUE(ret);
  4559. EXPECT_EQ(StatusCode::OK_200, res->status);
  4560. }
  4561. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4562. // rather than treat them as valid lengths.
  4563. template <typename ClientT>
  4564. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4565. Request req;
  4566. req.method = "POST";
  4567. req.path = "/chunked";
  4568. std::string host_and_port;
  4569. host_and_port += HOST;
  4570. host_and_port += ":";
  4571. host_and_port += std::to_string(PORT);
  4572. req.headers.emplace("Host", host_and_port.c_str());
  4573. req.headers.emplace("Content-Length", "0");
  4574. req.headers.emplace("Transfer-Encoding", "chunked");
  4575. req.body = body;
  4576. auto res = std::make_shared<Response>();
  4577. auto error = Error::Success;
  4578. ASSERT_TRUE(cli.send(req, *res, error));
  4579. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4580. }
  4581. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4582. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4583. }
  4584. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4585. expect_chunked_body_rejected(
  4586. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4587. }
  4588. TEST_F(ServerTest, GetStreamed2) {
  4589. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4590. ASSERT_TRUE(res);
  4591. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4592. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4593. EXPECT_EQ(true, res->has_header("Content-Range"));
  4594. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4595. EXPECT_EQ(std::string("ab"), res->body);
  4596. }
  4597. TEST_F(ServerTest, GetStreamed) {
  4598. auto res = cli_.Get("/streamed");
  4599. ASSERT_TRUE(res);
  4600. EXPECT_EQ(StatusCode::OK_200, res->status);
  4601. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4602. EXPECT_EQ(std::string("aaabbb"), res->body);
  4603. }
  4604. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4605. auto res =
  4606. cli_.Get("/streamed-without-length", {make_range_header({{0, -1}})});
  4607. ASSERT_TRUE(res);
  4608. EXPECT_EQ(StatusCode::OK_200, res->status);
  4609. EXPECT_EQ(false, res->has_header("Content-Length"));
  4610. EXPECT_EQ(false, res->has_header("Content-Range"));
  4611. EXPECT_EQ(std::string("abcdefg"), res->body);
  4612. }
  4613. TEST_F(ServerTest, GetStreamedWithRange1) {
  4614. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4615. ASSERT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4617. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4618. EXPECT_EQ(true, res->has_header("Content-Range"));
  4619. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4620. EXPECT_EQ(std::string("def"), res->body);
  4621. }
  4622. TEST_F(ServerTest, GetStreamedWithRange2) {
  4623. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4624. ASSERT_TRUE(res);
  4625. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4626. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4627. EXPECT_EQ(true, res->has_header("Content-Range"));
  4628. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4629. EXPECT_EQ(std::string("bcdefg"), res->body);
  4630. }
  4631. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4632. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4633. ASSERT_TRUE(res);
  4634. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4635. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4636. EXPECT_EQ(true, res->has_header("Content-Range"));
  4637. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4638. EXPECT_EQ(std::string("efg"), res->body);
  4639. }
  4640. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4641. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4642. ASSERT_TRUE(res);
  4643. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4644. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4645. EXPECT_EQ(false, res->has_header("Content-Range"));
  4646. EXPECT_EQ(0U, res->body.size());
  4647. }
  4648. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4649. auto res = cli_.Get("/streamed-with-range",
  4650. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4651. "92233720368547758079223372036854775807"}});
  4652. ASSERT_TRUE(res);
  4653. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4654. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4655. EXPECT_EQ(false, res->has_header("Content-Range"));
  4656. EXPECT_EQ(0U, res->body.size());
  4657. }
  4658. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4659. auto res = cli_.Get(
  4660. "/with-range",
  4661. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4662. {"Accept-Encoding", ""}});
  4663. ASSERT_TRUE(res);
  4664. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4665. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4666. EXPECT_EQ(true, res->has_header("Content-Range"));
  4667. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4668. EXPECT_EQ(std::string("abcdefg"), res->body);
  4669. }
  4670. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4671. auto res = cli_.Get("/with-range", {
  4672. {"Range", "bytes=0-"},
  4673. {"Accept-Encoding", ""},
  4674. });
  4675. ASSERT_TRUE(res);
  4676. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4677. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4678. EXPECT_EQ(true, res->has_header("Content-Range"));
  4679. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4680. EXPECT_EQ(std::string("abcdefg"), res->body);
  4681. }
  4682. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4683. auto res =
  4684. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4685. ASSERT_TRUE(res);
  4686. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4687. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4688. EXPECT_EQ(false, res->has_header("Content-Range"));
  4689. EXPECT_EQ(267U, res->body.size());
  4690. // Check that both range contents are present
  4691. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4692. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4693. // Check that Content-Range headers are present for both ranges
  4694. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4695. std::string::npos);
  4696. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4697. std::string::npos);
  4698. }
  4699. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4700. Ranges ranges;
  4701. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4702. ranges.emplace_back(0, -1);
  4703. }
  4704. auto res =
  4705. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4706. ASSERT_TRUE(res);
  4707. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4708. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4709. EXPECT_EQ(false, res->has_header("Content-Range"));
  4710. EXPECT_EQ(0U, res->body.size());
  4711. }
  4712. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4713. auto res =
  4714. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4715. ASSERT_TRUE(res);
  4716. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4717. EXPECT_EQ(5U, res->body.size());
  4718. // Check that overlapping ranges are coalesced into a single range
  4719. EXPECT_EQ("bcdef", res->body);
  4720. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4721. // Should be single range, not multipart
  4722. EXPECT_TRUE(res->has_header("Content-Range"));
  4723. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4724. }
  4725. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4726. auto res =
  4727. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4728. ASSERT_TRUE(res);
  4729. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4730. EXPECT_EQ(268U, res->body.size());
  4731. // Check that both range contents are present
  4732. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4733. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4734. // Check that Content-Range headers are present for both ranges
  4735. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4736. std::string::npos);
  4737. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4738. std::string::npos);
  4739. }
  4740. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4741. auto res =
  4742. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4743. ASSERT_TRUE(res);
  4744. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4745. EXPECT_EQ(269U, res->body.size());
  4746. // Check that both duplicate range contents are present
  4747. size_t first_abc = res->body.find("abc\r\n");
  4748. EXPECT_TRUE(first_abc != std::string::npos);
  4749. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4750. EXPECT_TRUE(second_abc != std::string::npos);
  4751. // Check that Content-Range headers are present for both ranges
  4752. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4753. EXPECT_TRUE(first_range != std::string::npos);
  4754. size_t second_range =
  4755. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4756. EXPECT_TRUE(second_range != std::string::npos);
  4757. }
  4758. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4759. auto res = cli_.Get("/streamed-with-range?error",
  4760. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4763. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4764. EXPECT_EQ(false, res->has_header("Content-Range"));
  4765. EXPECT_EQ(0U, res->body.size());
  4766. }
  4767. TEST_F(ServerTest, GetStreamedEndless) {
  4768. uint64_t offset = 0;
  4769. auto res = cli_.Get("/streamed-cancel",
  4770. [&](const char * /*data*/, uint64_t data_length) {
  4771. if (offset < 100) {
  4772. offset += data_length;
  4773. return true;
  4774. }
  4775. return false;
  4776. });
  4777. ASSERT_TRUE(!res);
  4778. EXPECT_EQ(Error::Canceled, res.error());
  4779. }
  4780. TEST_F(ServerTest, ClientStop) {
  4781. std::atomic_size_t count{4};
  4782. std::vector<std::thread> threads;
  4783. for (auto i = count.load(); i != 0; --i) {
  4784. threads.emplace_back([&]() {
  4785. auto res = cli_.Get("/streamed-cancel",
  4786. [&](const char *, uint64_t) { return true; });
  4787. --count;
  4788. ASSERT_TRUE(!res);
  4789. EXPECT_TRUE(res.error() == Error::Canceled ||
  4790. res.error() == Error::Read || res.error() == Error::Write);
  4791. });
  4792. }
  4793. std::this_thread::sleep_for(std::chrono::seconds(2));
  4794. while (count != 0) {
  4795. cli_.stop();
  4796. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4797. }
  4798. for (auto &t : threads) {
  4799. t.join();
  4800. }
  4801. }
  4802. TEST_F(ServerTest, GetWithRange1) {
  4803. auto res = cli_.Get("/with-range", {
  4804. make_range_header({{3, 5}}),
  4805. {"Accept-Encoding", ""},
  4806. });
  4807. ASSERT_TRUE(res);
  4808. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4809. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4810. EXPECT_EQ(true, res->has_header("Content-Range"));
  4811. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4812. EXPECT_EQ(std::string("def"), res->body);
  4813. }
  4814. TEST_F(ServerTest, GetWithRange2) {
  4815. auto res = cli_.Get("/with-range", {
  4816. make_range_header({{1, -1}}),
  4817. {"Accept-Encoding", ""},
  4818. });
  4819. ASSERT_TRUE(res);
  4820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4821. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4822. EXPECT_EQ(true, res->has_header("Content-Range"));
  4823. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4824. EXPECT_EQ(std::string("bcdefg"), res->body);
  4825. }
  4826. TEST_F(ServerTest, GetWithRange3) {
  4827. auto res = cli_.Get("/with-range", {
  4828. make_range_header({{0, 0}}),
  4829. {"Accept-Encoding", ""},
  4830. });
  4831. ASSERT_TRUE(res);
  4832. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4833. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4834. EXPECT_EQ(true, res->has_header("Content-Range"));
  4835. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4836. EXPECT_EQ(std::string("a"), res->body);
  4837. }
  4838. TEST_F(ServerTest, GetWithRange4) {
  4839. auto res = cli_.Get("/with-range", {
  4840. make_range_header({{-1, 2}}),
  4841. {"Accept-Encoding", ""},
  4842. });
  4843. ASSERT_TRUE(res);
  4844. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4845. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4846. EXPECT_EQ(true, res->has_header("Content-Range"));
  4847. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4848. EXPECT_EQ(std::string("fg"), res->body);
  4849. }
  4850. TEST_F(ServerTest, GetWithRange5) {
  4851. auto res = cli_.Get("/with-range", {
  4852. make_range_header({{0, 5}}),
  4853. {"Accept-Encoding", ""},
  4854. });
  4855. ASSERT_TRUE(res);
  4856. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4857. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4858. EXPECT_EQ(true, res->has_header("Content-Range"));
  4859. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4860. EXPECT_EQ(std::string("abcdef"), res->body);
  4861. }
  4862. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4863. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4864. ASSERT_TRUE(res);
  4865. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4866. }
  4867. TEST_F(ServerTest, GetWithRangeMultipart) {
  4868. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4869. ASSERT_TRUE(res);
  4870. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4871. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4872. EXPECT_EQ(false, res->has_header("Content-Range"));
  4873. EXPECT_EQ(267U, res->body.size());
  4874. }
  4875. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4876. auto res =
  4877. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4878. ASSERT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4880. }
  4881. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4882. auto res = cli_.Get("/with-range-customized-response",
  4883. {{make_range_header({{1, 2}})}});
  4884. ASSERT_TRUE(res);
  4885. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4886. EXPECT_EQ(true, res->has_header("Content-Length"));
  4887. EXPECT_EQ(false, res->has_header("Content-Range"));
  4888. EXPECT_EQ(JSON_DATA, res->body);
  4889. }
  4890. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4891. auto res = cli_.Get("/with-range-customized-response",
  4892. {{make_range_header({{1, 2}, {4, 5}})}});
  4893. ASSERT_TRUE(res);
  4894. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4895. EXPECT_EQ(true, res->has_header("Content-Length"));
  4896. EXPECT_EQ(false, res->has_header("Content-Range"));
  4897. EXPECT_EQ(JSON_DATA, res->body);
  4898. }
  4899. TEST_F(ServerTest, Issue1772) {
  4900. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4901. ASSERT_TRUE(res);
  4902. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4903. }
  4904. TEST_F(ServerTest, Issue609) {
  4905. auto res = cli_.Delete("/issue609");
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. EXPECT_EQ(std::string("ok"), res->body);
  4909. }
  4910. TEST_F(ServerTest, GetStreamedChunked) {
  4911. auto res = cli_.Get("/streamed-chunked");
  4912. ASSERT_TRUE(res);
  4913. EXPECT_EQ(StatusCode::OK_200, res->status);
  4914. EXPECT_EQ(std::string("123456789"), res->body);
  4915. }
  4916. TEST_F(ServerTest, GetStreamedChunked2) {
  4917. auto res = cli_.Get("/streamed-chunked2");
  4918. ASSERT_TRUE(res);
  4919. EXPECT_EQ(StatusCode::OK_200, res->status);
  4920. EXPECT_EQ(std::string("123456789"), res->body);
  4921. }
  4922. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4923. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4924. ASSERT_TRUE(res);
  4925. EXPECT_EQ(StatusCode::OK_200, res->status);
  4926. EXPECT_EQ(std::string("123456789"), res->body);
  4927. EXPECT_TRUE(res->has_header("Trailer"));
  4928. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4929. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4930. // Trailers are now stored separately from headers (security fix)
  4931. EXPECT_EQ(2U, res->trailers.size());
  4932. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4933. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4934. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4935. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4936. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4937. // Verify trailers are NOT in headers (security verification)
  4938. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4939. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4940. }
  4941. TEST_F(ServerTest, LargeChunkedPost) {
  4942. Request req;
  4943. req.method = "POST";
  4944. req.path = "/large-chunked";
  4945. std::string host_and_port;
  4946. host_and_port += HOST;
  4947. host_and_port += ":";
  4948. host_and_port += std::to_string(PORT);
  4949. req.headers.emplace("Host", host_and_port.c_str());
  4950. req.headers.emplace("Accept", "*/*");
  4951. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4952. req.headers.emplace("Content-Type", "text/plain");
  4953. req.headers.emplace("Content-Length", "0");
  4954. req.headers.emplace("Transfer-Encoding", "chunked");
  4955. std::string long_string(30 * 1024u, 'a');
  4956. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4957. // Attempt to make a large enough post to exceed OS buffers, to test that
  4958. // the server handles short reads if the full chunk data isn't available.
  4959. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4960. auto res = std::make_shared<Response>();
  4961. auto error = Error::Success;
  4962. auto ret = cli_.send(req, *res, error);
  4963. ASSERT_TRUE(ret);
  4964. EXPECT_EQ(StatusCode::OK_200, res->status);
  4965. }
  4966. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4967. auto res = cli_.Get("/remote_addr");
  4968. ASSERT_TRUE(res);
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4971. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4972. }
  4973. TEST_F(ServerTest, GetMethodLocalAddr) {
  4974. auto res = cli_.Get("/local_addr");
  4975. ASSERT_TRUE(res);
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4978. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4979. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4980. }
  4981. TEST_F(ServerTest, HTTPResponseSplitting) {
  4982. auto res = cli_.Get("/http_response_splitting");
  4983. ASSERT_TRUE(res);
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. }
  4986. TEST_F(ServerTest, SlowRequest) {
  4987. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4988. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4989. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4990. }
  4991. #if 0
  4992. TEST_F(ServerTest, SlowPost) {
  4993. char buffer[64 * 1024];
  4994. memset(buffer, 0x42, sizeof(buffer));
  4995. auto res = cli_.Post(
  4996. "/slowpost", 64 * 1024 * 1024,
  4997. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4998. auto ret = sink.write(buffer, sizeof(buffer));
  4999. EXPECT_TRUE(ret);
  5000. return true;
  5001. },
  5002. "text/plain");
  5003. ASSERT_TRUE(res);
  5004. EXPECT_EQ(StatusCode::OK_200, res->status);
  5005. }
  5006. TEST_F(ServerTest, SlowPostFail) {
  5007. char buffer[64 * 1024];
  5008. memset(buffer, 0x42, sizeof(buffer));
  5009. cli_.set_write_timeout(std::chrono::seconds(0));
  5010. auto res = cli_.Post(
  5011. "/slowpost", 64 * 1024 * 1024,
  5012. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5013. sink.write(buffer, sizeof(buffer));
  5014. return true;
  5015. },
  5016. "text/plain");
  5017. ASSERT_TRUE(!res);
  5018. EXPECT_EQ(Error::Write, res.error());
  5019. }
  5020. #endif
  5021. TEST_F(ServerTest, Put) {
  5022. auto res = cli_.Put("/put", "PUT", "text/plain");
  5023. ASSERT_TRUE(res);
  5024. EXPECT_EQ(StatusCode::OK_200, res->status);
  5025. EXPECT_EQ("PUT", res->body);
  5026. }
  5027. TEST_F(ServerTest, PutWithContentProvider) {
  5028. auto res = cli_.Put(
  5029. "/put", 3,
  5030. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5031. sink.os << "PUT";
  5032. return true;
  5033. },
  5034. "text/plain");
  5035. ASSERT_TRUE(res);
  5036. EXPECT_EQ(StatusCode::OK_200, res->status);
  5037. EXPECT_EQ("PUT", res->body);
  5038. }
  5039. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5040. auto res = cli_.Post(
  5041. "/post", 42,
  5042. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5043. return false;
  5044. },
  5045. "text/plain");
  5046. ASSERT_TRUE(!res);
  5047. EXPECT_EQ(Error::Canceled, res.error());
  5048. }
  5049. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5050. auto res = cli_.Put(
  5051. "/put",
  5052. [](size_t /*offset*/, DataSink &sink) {
  5053. sink.os << "PUT";
  5054. sink.done();
  5055. return true;
  5056. },
  5057. "text/plain");
  5058. ASSERT_TRUE(res);
  5059. EXPECT_EQ(StatusCode::OK_200, res->status);
  5060. EXPECT_EQ("PUT", res->body);
  5061. }
  5062. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5063. auto res = cli_.Post(
  5064. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5065. "text/plain");
  5066. ASSERT_TRUE(!res);
  5067. EXPECT_EQ(Error::Canceled, res.error());
  5068. }
  5069. TEST_F(ServerTest, PostLoopBack) {
  5070. std::string body;
  5071. auto res = cli_.Post(
  5072. "/post-loopback", 9,
  5073. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5074. EXPECT_EQ(9u, length);
  5075. sink.write("123", 3);
  5076. sink.write("456", 3);
  5077. sink.write("789", 3);
  5078. return true;
  5079. },
  5080. "text/plain",
  5081. [&body](const char *data, size_t data_length) {
  5082. body.append(data, data_length);
  5083. return true;
  5084. });
  5085. ASSERT_TRUE(res);
  5086. EXPECT_EQ(StatusCode::OK_200, res->status);
  5087. EXPECT_EQ("123456789", body);
  5088. }
  5089. TEST_F(ServerTest, PutLoopBack) {
  5090. std::string body;
  5091. auto res = cli_.Put(
  5092. "/put-loopback", 9,
  5093. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5094. EXPECT_EQ(9u, length);
  5095. sink.write("123", 3);
  5096. sink.write("456", 3);
  5097. sink.write("789", 3);
  5098. return true;
  5099. },
  5100. "text/plain",
  5101. [&body](const char *data, size_t data_length) {
  5102. body.append(data, data_length);
  5103. return true;
  5104. });
  5105. ASSERT_TRUE(res);
  5106. EXPECT_EQ(StatusCode::OK_200, res->status);
  5107. EXPECT_EQ("123456789", body);
  5108. }
  5109. TEST_F(ServerTest, PatchLoopBack) {
  5110. std::string body;
  5111. auto res = cli_.Patch(
  5112. "/patch-loopback", 9,
  5113. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5114. EXPECT_EQ(9u, length);
  5115. sink.write("123", 3);
  5116. sink.write("456", 3);
  5117. sink.write("789", 3);
  5118. return true;
  5119. },
  5120. "text/plain",
  5121. [&body](const char *data, size_t data_length) {
  5122. body.append(data, data_length);
  5123. return true;
  5124. });
  5125. ASSERT_TRUE(res);
  5126. EXPECT_EQ(StatusCode::OK_200, res->status);
  5127. EXPECT_EQ("123456789", body);
  5128. }
  5129. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5130. std::string body;
  5131. auto res = cli_.Post(
  5132. "/post-loopback",
  5133. [](size_t /*offset*/, DataSink &sink) {
  5134. sink.write("123", 3);
  5135. sink.write("456", 3);
  5136. sink.write("789", 3);
  5137. sink.done();
  5138. return true;
  5139. },
  5140. "text/plain",
  5141. [&body](const char *data, size_t data_length) {
  5142. body.append(data, data_length);
  5143. return true;
  5144. });
  5145. ASSERT_TRUE(res);
  5146. EXPECT_EQ(StatusCode::OK_200, res->status);
  5147. EXPECT_EQ("123456789", body);
  5148. }
  5149. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5150. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5151. cli_.set_compress(true);
  5152. auto res = cli_.Put(
  5153. "/put", 3,
  5154. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5155. sink.os << "PUT";
  5156. return true;
  5157. },
  5158. "text/plain");
  5159. ASSERT_TRUE(res);
  5160. EXPECT_EQ(StatusCode::OK_200, res->status);
  5161. EXPECT_EQ("PUT", res->body);
  5162. }
  5163. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5164. cli_.set_compress(true);
  5165. auto res = cli_.Post(
  5166. "/post", 42,
  5167. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5168. return false;
  5169. },
  5170. "text/plain");
  5171. ASSERT_TRUE(!res);
  5172. EXPECT_EQ(Error::Canceled, res.error());
  5173. }
  5174. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5175. cli_.set_compress(true);
  5176. auto res = cli_.Put(
  5177. "/put",
  5178. [](size_t /*offset*/, DataSink &sink) {
  5179. sink.os << "PUT";
  5180. sink.done();
  5181. return true;
  5182. },
  5183. "text/plain");
  5184. ASSERT_TRUE(res);
  5185. EXPECT_EQ(StatusCode::OK_200, res->status);
  5186. EXPECT_EQ("PUT", res->body);
  5187. }
  5188. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5189. cli_.set_compress(true);
  5190. auto res = cli_.Post(
  5191. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5192. "text/plain");
  5193. ASSERT_TRUE(!res);
  5194. EXPECT_EQ(Error::Canceled, res.error());
  5195. }
  5196. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5197. cli_.set_compress(true);
  5198. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5199. ASSERT_TRUE(res);
  5200. EXPECT_EQ(StatusCode::OK_200, res->status);
  5201. EXPECT_EQ(LARGE_DATA, res->body);
  5202. }
  5203. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5204. #ifdef CPPHTTPLIB_SSL_ENABLED
  5205. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5206. Client cli(s.c_str());
  5207. cli.enable_server_certificate_verification(false);
  5208. #else
  5209. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5210. Client cli(s.c_str());
  5211. #endif
  5212. cli.set_compress(true);
  5213. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5214. ASSERT_TRUE(res);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. EXPECT_EQ(LARGE_DATA, res->body);
  5217. // The compressed size should be less than a 10th of the original. May vary
  5218. // depending on the zlib library.
  5219. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5220. static_cast<uint64_t>(10 * 1024 * 1024));
  5221. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5222. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5223. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5224. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5225. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5226. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5227. #endif
  5228. }
  5229. TEST_F(ServerTest, PutContentWithDeflate) {
  5230. cli_.set_compress(false);
  5231. Headers headers;
  5232. headers.emplace("Content-Encoding", "deflate");
  5233. // PUT in deflate format:
  5234. auto res = cli_.Put("/put", headers,
  5235. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5236. ASSERT_TRUE(res);
  5237. EXPECT_EQ(StatusCode::OK_200, res->status);
  5238. EXPECT_EQ("PUT", res->body);
  5239. }
  5240. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5241. Headers headers;
  5242. headers.emplace("Accept-Encoding", "gzip, deflate");
  5243. auto res = cli_.Get("/streamed-chunked", headers);
  5244. ASSERT_TRUE(res);
  5245. EXPECT_EQ(StatusCode::OK_200, res->status);
  5246. EXPECT_EQ(std::string("123456789"), res->body);
  5247. }
  5248. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5249. Headers headers;
  5250. headers.emplace("Accept-Encoding", "gzip, deflate");
  5251. auto res = cli_.Get("/streamed-chunked2", headers);
  5252. ASSERT_TRUE(res);
  5253. EXPECT_EQ(StatusCode::OK_200, res->status);
  5254. EXPECT_EQ(std::string("123456789"), res->body);
  5255. }
  5256. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5257. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5258. ASSERT_TRUE(res);
  5259. EXPECT_EQ(StatusCode::OK_200, res->status);
  5260. }
  5261. TEST(GzipDecompressor, ChunkedDecompression) {
  5262. std::string data;
  5263. for (size_t i = 0; i < 32 * 1024; ++i) {
  5264. data.push_back(static_cast<char>('a' + i % 26));
  5265. }
  5266. std::string compressed_data;
  5267. {
  5268. httplib::detail::gzip_compressor compressor;
  5269. bool result = compressor.compress(
  5270. data.data(), data.size(),
  5271. /*last=*/true,
  5272. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5273. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5274. compressed_data_size);
  5275. return true;
  5276. });
  5277. ASSERT_TRUE(result);
  5278. }
  5279. std::string decompressed_data;
  5280. {
  5281. httplib::detail::gzip_decompressor decompressor;
  5282. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5283. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5284. size_t chunk_size = 130;
  5285. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5286. chunk_begin += chunk_size) {
  5287. size_t current_chunk_size =
  5288. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5289. bool result = decompressor.decompress(
  5290. compressed_data.data() + chunk_begin, current_chunk_size,
  5291. [&](const char *decompressed_data_chunk,
  5292. size_t decompressed_data_chunk_size) {
  5293. decompressed_data.insert(decompressed_data.size(),
  5294. decompressed_data_chunk,
  5295. decompressed_data_chunk_size);
  5296. return true;
  5297. });
  5298. ASSERT_TRUE(result);
  5299. }
  5300. }
  5301. ASSERT_EQ(data, decompressed_data);
  5302. }
  5303. TEST(GzipDecompressor, DeflateDecompression) {
  5304. std::string original_text = "Raw deflate without gzip";
  5305. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5306. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5307. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5308. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5309. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5310. std::string decompressed_data;
  5311. {
  5312. httplib::detail::gzip_decompressor decompressor;
  5313. bool result = decompressor.decompress(
  5314. compressed_data.data(), compressed_data.size(),
  5315. [&](const char *decompressed_data_chunk,
  5316. size_t decompressed_data_chunk_size) {
  5317. decompressed_data.insert(decompressed_data.size(),
  5318. decompressed_data_chunk,
  5319. decompressed_data_chunk_size);
  5320. return true;
  5321. });
  5322. ASSERT_TRUE(result);
  5323. }
  5324. ASSERT_EQ(original_text, decompressed_data);
  5325. }
  5326. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5327. std::string original_text = "Raw deflate without gzip";
  5328. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5329. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5330. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5331. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5332. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5333. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5334. std::string decompressed_data;
  5335. {
  5336. httplib::detail::gzip_decompressor decompressor;
  5337. bool result = decompressor.decompress(
  5338. compressed_data.data(), compressed_data.size(),
  5339. [&](const char *decompressed_data_chunk,
  5340. size_t decompressed_data_chunk_size) {
  5341. decompressed_data.insert(decompressed_data.size(),
  5342. decompressed_data_chunk,
  5343. decompressed_data_chunk_size);
  5344. return true;
  5345. });
  5346. ASSERT_TRUE(result);
  5347. }
  5348. ASSERT_EQ(original_text, decompressed_data);
  5349. }
  5350. #endif
  5351. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5352. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5353. Headers headers;
  5354. headers.emplace("Accept-Encoding", "br");
  5355. auto res = cli_.Get("/streamed-chunked", headers);
  5356. ASSERT_TRUE(res);
  5357. EXPECT_EQ(StatusCode::OK_200, res->status);
  5358. EXPECT_EQ(std::string("123456789"), res->body);
  5359. }
  5360. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5361. Headers headers;
  5362. headers.emplace("Accept-Encoding", "br");
  5363. auto res = cli_.Get("/streamed-chunked2", headers);
  5364. ASSERT_TRUE(res);
  5365. EXPECT_EQ(StatusCode::OK_200, res->status);
  5366. EXPECT_EQ(std::string("123456789"), res->body);
  5367. }
  5368. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5369. cli_.set_compress(true);
  5370. auto res = cli_.Put(
  5371. "/put", 3,
  5372. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5373. sink.os << "PUT";
  5374. return true;
  5375. },
  5376. "text/plain");
  5377. ASSERT_TRUE(res);
  5378. EXPECT_EQ(StatusCode::OK_200, res->status);
  5379. EXPECT_EQ("PUT", res->body);
  5380. }
  5381. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5382. cli_.set_compress(true);
  5383. auto res = cli_.Put(
  5384. "/put",
  5385. [](size_t /*offset*/, DataSink &sink) {
  5386. sink.os << "PUT";
  5387. sink.done();
  5388. return true;
  5389. },
  5390. "text/plain");
  5391. ASSERT_TRUE(res);
  5392. EXPECT_EQ(StatusCode::OK_200, res->status);
  5393. EXPECT_EQ("PUT", res->body);
  5394. }
  5395. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5396. cli_.set_compress(true);
  5397. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5398. ASSERT_TRUE(res);
  5399. EXPECT_EQ(StatusCode::OK_200, res->status);
  5400. EXPECT_EQ(LARGE_DATA, res->body);
  5401. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5402. }
  5403. #endif
  5404. TEST_F(ServerTest, Patch) {
  5405. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5406. ASSERT_TRUE(res);
  5407. EXPECT_EQ(StatusCode::OK_200, res->status);
  5408. EXPECT_EQ("PATCH", res->body);
  5409. }
  5410. TEST_F(ServerTest, Delete) {
  5411. auto res = cli_.Delete("/delete");
  5412. ASSERT_TRUE(res);
  5413. EXPECT_EQ(StatusCode::OK_200, res->status);
  5414. EXPECT_EQ("DELETE", res->body);
  5415. }
  5416. TEST_F(ServerTest, DeleteContentReceiver) {
  5417. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5418. ASSERT_TRUE(res);
  5419. EXPECT_EQ(StatusCode::OK_200, res->status);
  5420. EXPECT_EQ("content", res->body);
  5421. }
  5422. TEST_F(ServerTest, Options) {
  5423. auto res = cli_.Options("*");
  5424. ASSERT_TRUE(res);
  5425. EXPECT_EQ(StatusCode::OK_200, res->status);
  5426. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5427. EXPECT_TRUE(res->body.empty());
  5428. }
  5429. TEST_F(ServerTest, URL) {
  5430. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5431. ASSERT_TRUE(res);
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. }
  5434. TEST_F(ServerTest, ArrayParam) {
  5435. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5436. ASSERT_TRUE(res);
  5437. EXPECT_EQ(StatusCode::OK_200, res->status);
  5438. }
  5439. TEST_F(ServerTest, ArrayParamValues) {
  5440. auto res =
  5441. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5442. ASSERT_TRUE(res);
  5443. EXPECT_EQ(StatusCode::OK_200, res->status);
  5444. }
  5445. TEST_F(ServerTest, NoMultipleHeaders) {
  5446. Headers headers = {{"Content-Length", "5"}};
  5447. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5448. "text/plain");
  5449. ASSERT_TRUE(res);
  5450. EXPECT_EQ(StatusCode::OK_200, res->status);
  5451. }
  5452. TEST_F(ServerTest, PostContentReceiver) {
  5453. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5454. ASSERT_TRUE(res);
  5455. ASSERT_EQ(StatusCode::OK_200, res->status);
  5456. ASSERT_EQ("content", res->body);
  5457. }
  5458. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5459. UploadFormDataItems items = {
  5460. {"text1", "text default", "", ""},
  5461. {"text2", "aωb", "", ""},
  5462. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5463. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5464. {"file3", "", "", "application/octet-stream"},
  5465. };
  5466. auto res = cli_.Post("/content_receiver", items);
  5467. ASSERT_TRUE(res);
  5468. EXPECT_EQ(StatusCode::OK_200, res->status);
  5469. }
  5470. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5471. UploadFormDataItems items = {
  5472. {"text1", "text default", "", ""},
  5473. {"text2", "aωb", "", ""},
  5474. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5475. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5476. {"file3", "", "", "application/octet-stream"},
  5477. };
  5478. auto boundary = std::string("+++++");
  5479. std::string body;
  5480. for (const auto &item : items) {
  5481. body += "--" + boundary + "\r\n";
  5482. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5483. if (!item.filename.empty()) {
  5484. body += "; filename=\"" + item.filename + "\"";
  5485. }
  5486. body += "\r\n";
  5487. if (!item.content_type.empty()) {
  5488. body += "Content-Type: " + item.content_type + "\r\n";
  5489. }
  5490. body += "\r\n";
  5491. body += item.content + "\r\n";
  5492. }
  5493. body += "--" + boundary + "--\r\n";
  5494. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5495. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5496. ASSERT_TRUE(res);
  5497. EXPECT_EQ(StatusCode::OK_200, res->status);
  5498. }
  5499. TEST_F(ServerTest, PostContentReceiverGzip) {
  5500. cli_.set_compress(true);
  5501. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5502. ASSERT_TRUE(res);
  5503. ASSERT_EQ(StatusCode::OK_200, res->status);
  5504. ASSERT_EQ("content", res->body);
  5505. }
  5506. TEST_F(ServerTest, PutContentReceiver) {
  5507. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5508. ASSERT_TRUE(res);
  5509. ASSERT_EQ(StatusCode::OK_200, res->status);
  5510. ASSERT_EQ("content", res->body);
  5511. }
  5512. TEST_F(ServerTest, PatchContentReceiver) {
  5513. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5514. ASSERT_TRUE(res);
  5515. ASSERT_EQ(StatusCode::OK_200, res->status);
  5516. ASSERT_EQ("content", res->body);
  5517. }
  5518. template <typename ClientType>
  5519. void TestWithHeadersAndContentReceiver(
  5520. ClientType &cli,
  5521. std::function<Result(ClientType &, const std::string &, const Headers &,
  5522. const std::string &, const std::string &,
  5523. ContentReceiver, DownloadProgress)>
  5524. request_func) {
  5525. Headers headers;
  5526. headers.emplace("X-Custom-Header", "test-value");
  5527. std::string received_body;
  5528. auto res = request_func(
  5529. cli, "/content_receiver", headers, "content", "application/json",
  5530. [&](const char *data, size_t data_length) {
  5531. received_body.append(data, data_length);
  5532. return true;
  5533. },
  5534. nullptr);
  5535. ASSERT_TRUE(res);
  5536. EXPECT_EQ(StatusCode::OK_200, res->status);
  5537. EXPECT_EQ("content", received_body);
  5538. }
  5539. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5540. #ifdef CPPHTTPLIB_SSL_ENABLED
  5541. using ClientT = SSLClient;
  5542. #else
  5543. using ClientT = Client;
  5544. #endif
  5545. TestWithHeadersAndContentReceiver<ClientT>(
  5546. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5547. const std::string &body, const std::string &content_type,
  5548. ContentReceiver receiver, DownloadProgress progress) {
  5549. return cli.Post(path, headers, body, content_type, receiver, progress);
  5550. });
  5551. }
  5552. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5553. #ifdef CPPHTTPLIB_SSL_ENABLED
  5554. using ClientT = SSLClient;
  5555. #else
  5556. using ClientT = Client;
  5557. #endif
  5558. TestWithHeadersAndContentReceiver<ClientT>(
  5559. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5560. const std::string &body, const std::string &content_type,
  5561. ContentReceiver receiver, DownloadProgress progress) {
  5562. return cli.Put(path, headers, body, content_type, receiver, progress);
  5563. });
  5564. }
  5565. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5566. #ifdef CPPHTTPLIB_SSL_ENABLED
  5567. using ClientT = SSLClient;
  5568. #else
  5569. using ClientT = Client;
  5570. #endif
  5571. TestWithHeadersAndContentReceiver<ClientT>(
  5572. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5573. const std::string &body, const std::string &content_type,
  5574. ContentReceiver receiver, DownloadProgress progress) {
  5575. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5576. });
  5577. }
  5578. template <typename ClientType>
  5579. void TestWithHeadersAndContentReceiverWithProgress(
  5580. ClientType &cli,
  5581. std::function<Result(ClientType &, const std::string &, const Headers &,
  5582. const std::string &, const std::string &,
  5583. ContentReceiver, DownloadProgress)>
  5584. request_func) {
  5585. Headers headers;
  5586. headers.emplace("X-Test-Header", "progress-test");
  5587. std::string received_body;
  5588. auto progress_called = false;
  5589. auto res = request_func(
  5590. cli, "/content_receiver", headers, "content", "text/plain",
  5591. [&](const char *data, size_t data_length) {
  5592. received_body.append(data, data_length);
  5593. return true;
  5594. },
  5595. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5596. progress_called = true;
  5597. return true;
  5598. });
  5599. ASSERT_TRUE(res);
  5600. EXPECT_EQ(StatusCode::OK_200, res->status);
  5601. EXPECT_EQ("content", received_body);
  5602. EXPECT_TRUE(progress_called);
  5603. }
  5604. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5605. #ifdef CPPHTTPLIB_SSL_ENABLED
  5606. using ClientT = SSLClient;
  5607. #else
  5608. using ClientT = Client;
  5609. #endif
  5610. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5611. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5612. const std::string &body, const std::string &content_type,
  5613. ContentReceiver receiver, DownloadProgress progress) {
  5614. return cli.Post(path, headers, body, content_type, receiver, progress);
  5615. });
  5616. }
  5617. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5618. #ifdef CPPHTTPLIB_SSL_ENABLED
  5619. using ClientT = SSLClient;
  5620. #else
  5621. using ClientT = Client;
  5622. #endif
  5623. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5624. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5625. const std::string &body, const std::string &content_type,
  5626. ContentReceiver receiver, DownloadProgress progress) {
  5627. return cli.Put(path, headers, body, content_type, receiver, progress);
  5628. });
  5629. }
  5630. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5631. #ifdef CPPHTTPLIB_SSL_ENABLED
  5632. using ClientT = SSLClient;
  5633. #else
  5634. using ClientT = Client;
  5635. #endif
  5636. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5637. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5638. const std::string &body, const std::string &content_type,
  5639. ContentReceiver receiver, DownloadProgress progress) {
  5640. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5641. });
  5642. }
  5643. template <typename ClientType>
  5644. void TestWithHeadersAndContentReceiverError(
  5645. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5646. const Headers &, const std::string &,
  5647. const std::string &, ContentReceiver)>
  5648. request_func) {
  5649. Headers headers;
  5650. headers.emplace("X-Error-Test", "true");
  5651. std::string received_body;
  5652. auto receiver_failed = false;
  5653. auto res =
  5654. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5655. [&](const char *data, size_t data_length) {
  5656. received_body.append(data, data_length);
  5657. receiver_failed = true;
  5658. return false;
  5659. });
  5660. ASSERT_FALSE(res);
  5661. EXPECT_TRUE(receiver_failed);
  5662. }
  5663. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5664. #ifdef CPPHTTPLIB_SSL_ENABLED
  5665. using ClientT = SSLClient;
  5666. #else
  5667. using ClientT = Client;
  5668. #endif
  5669. TestWithHeadersAndContentReceiverError<ClientT>(
  5670. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5671. const std::string &body, const std::string &content_type,
  5672. ContentReceiver receiver) {
  5673. return cli.Post(path, headers, body, content_type, receiver);
  5674. });
  5675. }
  5676. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5677. #ifdef CPPHTTPLIB_SSL_ENABLED
  5678. using ClientT = SSLClient;
  5679. #else
  5680. using ClientT = Client;
  5681. #endif
  5682. TestWithHeadersAndContentReceiverError<ClientT>(
  5683. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5684. const std::string &body, const std::string &content_type,
  5685. ContentReceiver receiver) {
  5686. return cli.Put(path, headers, body, content_type, receiver);
  5687. });
  5688. }
  5689. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5690. #ifdef CPPHTTPLIB_SSL_ENABLED
  5691. using ClientT = SSLClient;
  5692. #else
  5693. using ClientT = Client;
  5694. #endif
  5695. TestWithHeadersAndContentReceiverError<ClientT>(
  5696. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5697. const std::string &body, const std::string &content_type,
  5698. ContentReceiver receiver) {
  5699. return cli.Patch(path, headers, body, content_type, receiver);
  5700. });
  5701. }
  5702. TEST_F(ServerTest, PostQueryStringAndBody) {
  5703. auto res =
  5704. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5705. ASSERT_TRUE(res);
  5706. ASSERT_EQ(StatusCode::OK_200, res->status);
  5707. }
  5708. TEST_F(ServerTest, HTTP2Magic) {
  5709. Request req;
  5710. req.method = "PRI";
  5711. req.path = "*";
  5712. req.body = "SM";
  5713. auto res = std::make_shared<Response>();
  5714. auto error = Error::Success;
  5715. auto ret = cli_.send(req, *res, error);
  5716. ASSERT_TRUE(ret);
  5717. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5718. }
  5719. TEST_F(ServerTest, KeepAlive) {
  5720. auto res = cli_.Get("/hi");
  5721. ASSERT_TRUE(res);
  5722. EXPECT_EQ(StatusCode::OK_200, res->status);
  5723. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5724. EXPECT_EQ("Hello World!", res->body);
  5725. res = cli_.Get("/hi");
  5726. ASSERT_TRUE(res);
  5727. EXPECT_EQ(StatusCode::OK_200, res->status);
  5728. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5729. EXPECT_EQ("Hello World!", res->body);
  5730. res = cli_.Get("/hi");
  5731. ASSERT_TRUE(res);
  5732. EXPECT_EQ(StatusCode::OK_200, res->status);
  5733. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5734. EXPECT_EQ("Hello World!", res->body);
  5735. res = cli_.Get("/not-exist");
  5736. ASSERT_TRUE(res);
  5737. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5738. res = cli_.Post("/empty", "", "text/plain");
  5739. ASSERT_TRUE(res);
  5740. EXPECT_EQ(StatusCode::OK_200, res->status);
  5741. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5742. EXPECT_EQ("empty", res->body);
  5743. EXPECT_EQ("close", res->get_header_value("Connection"));
  5744. res = cli_.Post(
  5745. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5746. "text/plain");
  5747. ASSERT_TRUE(res);
  5748. EXPECT_EQ(StatusCode::OK_200, res->status);
  5749. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5750. EXPECT_EQ("empty", res->body);
  5751. cli_.set_keep_alive(false);
  5752. res = cli_.Get("/last-request");
  5753. ASSERT_TRUE(res);
  5754. EXPECT_EQ(StatusCode::OK_200, res->status);
  5755. EXPECT_EQ("close", res->get_header_value("Connection"));
  5756. }
  5757. TEST_F(ServerTest, TooManyRedirect) {
  5758. cli_.set_follow_location(true);
  5759. auto res = cli_.Get("/redirect/0");
  5760. ASSERT_TRUE(!res);
  5761. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5762. }
  5763. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5764. Request req;
  5765. req.method = "FOOBAR";
  5766. req.path = "/hi";
  5767. cli_.set_keep_alive(true);
  5768. auto res = cli_.send(req);
  5769. ASSERT_TRUE(res);
  5770. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5771. EXPECT_EQ("close", res->get_header_value("Connection"));
  5772. EXPECT_FALSE(cli_.is_socket_open());
  5773. }
  5774. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5775. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5776. TEST_F(ServerTest, Gzip) {
  5777. Headers headers;
  5778. headers.emplace("Accept-Encoding", "gzip, deflate");
  5779. auto res = cli_.Get("/compress", headers);
  5780. ASSERT_TRUE(res);
  5781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5782. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5783. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5784. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5785. "7890123456789012345678901234567890",
  5786. res->body);
  5787. EXPECT_EQ(StatusCode::OK_200, res->status);
  5788. }
  5789. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5790. Headers headers;
  5791. headers.emplace("Accept-Encoding", "gzip, deflate");
  5792. auto res = cli_.Get("/compress-with-charset", headers);
  5793. ASSERT_TRUE(res);
  5794. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5795. EXPECT_EQ("application/json; charset=utf-8",
  5796. res->get_header_value("Content-Type"));
  5797. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5798. "7890123456789012345678901234567890",
  5799. res->body);
  5800. EXPECT_EQ(StatusCode::OK_200, res->status);
  5801. }
  5802. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5803. Headers headers;
  5804. headers.emplace("Accept-Encoding", "");
  5805. auto res = cli_.Get("/compress", headers);
  5806. ASSERT_TRUE(res);
  5807. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5808. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5809. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5810. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5811. "7890123456789012345678901234567890",
  5812. res->body);
  5813. EXPECT_EQ(StatusCode::OK_200, res->status);
  5814. }
  5815. TEST_F(ServerTest, GzipWithContentReceiver) {
  5816. Headers headers;
  5817. headers.emplace("Accept-Encoding", "gzip, deflate");
  5818. std::string body;
  5819. auto res = cli_.Get("/compress", headers,
  5820. [&](const char *data, uint64_t data_length) {
  5821. EXPECT_EQ(100U, data_length);
  5822. body.append(data, data_length);
  5823. return true;
  5824. });
  5825. ASSERT_TRUE(res);
  5826. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5827. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5828. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5829. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5830. "7890123456789012345678901234567890",
  5831. body);
  5832. EXPECT_EQ(StatusCode::OK_200, res->status);
  5833. }
  5834. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5835. Headers headers;
  5836. headers.emplace("Accept-Encoding", "gzip, deflate");
  5837. cli_.set_decompress(false);
  5838. auto res = cli_.Get("/compress", headers);
  5839. ASSERT_TRUE(res);
  5840. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5841. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5842. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5843. EXPECT_EQ(33U, res->body.size());
  5844. EXPECT_EQ(StatusCode::OK_200, res->status);
  5845. }
  5846. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5847. Headers headers;
  5848. headers.emplace("Accept-Encoding", "");
  5849. std::string body;
  5850. auto res = cli_.Get("/compress", headers,
  5851. [&](const char *data, uint64_t data_length) {
  5852. EXPECT_EQ(100U, data_length);
  5853. body.append(data, data_length);
  5854. return true;
  5855. });
  5856. ASSERT_TRUE(res);
  5857. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5858. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5859. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5860. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5861. "7890123456789012345678901234567890",
  5862. body);
  5863. EXPECT_EQ(StatusCode::OK_200, res->status);
  5864. }
  5865. TEST_F(ServerTest, NoGzip) {
  5866. Headers headers;
  5867. headers.emplace("Accept-Encoding", "gzip, deflate");
  5868. auto res = cli_.Get("/nocompress", headers);
  5869. ASSERT_TRUE(res);
  5870. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5871. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5872. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5873. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5874. "7890123456789012345678901234567890",
  5875. res->body);
  5876. EXPECT_EQ(StatusCode::OK_200, res->status);
  5877. }
  5878. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5879. Headers headers;
  5880. headers.emplace("Accept-Encoding", "gzip, deflate");
  5881. std::string body;
  5882. auto res = cli_.Get("/nocompress", headers,
  5883. [&](const char *data, uint64_t data_length) {
  5884. EXPECT_EQ(100U, data_length);
  5885. body.append(data, data_length);
  5886. return true;
  5887. });
  5888. ASSERT_TRUE(res);
  5889. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5890. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5891. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5892. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5893. "7890123456789012345678901234567890",
  5894. body);
  5895. EXPECT_EQ(StatusCode::OK_200, res->status);
  5896. }
  5897. TEST_F(ServerTest, MultipartFormDataGzip) {
  5898. UploadFormDataItems items = {
  5899. {"key1", "test", "", ""},
  5900. {"key2", "--abcdefg123", "", ""},
  5901. };
  5902. cli_.set_compress(true);
  5903. auto res = cli_.Post("/compress-multipart", items);
  5904. ASSERT_TRUE(res);
  5905. EXPECT_EQ(StatusCode::OK_200, res->status);
  5906. }
  5907. #endif
  5908. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5909. TEST_F(ServerTest, Brotli) {
  5910. Headers headers;
  5911. headers.emplace("Accept-Encoding", "br");
  5912. auto res = cli_.Get("/compress", headers);
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5915. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5916. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5917. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5918. "7890123456789012345678901234567890",
  5919. res->body);
  5920. EXPECT_EQ(StatusCode::OK_200, res->status);
  5921. }
  5922. #endif
  5923. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5924. TEST_F(ServerTest, Zstd) {
  5925. Headers headers;
  5926. headers.emplace("Accept-Encoding", "zstd");
  5927. auto res = cli_.Get("/compress", headers);
  5928. ASSERT_TRUE(res);
  5929. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5930. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5931. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5932. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5933. "7890123456789012345678901234567890",
  5934. res->body);
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. }
  5937. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5938. Headers headers;
  5939. headers.emplace("Accept-Encoding", "");
  5940. auto res = cli_.Get("/compress", headers);
  5941. ASSERT_TRUE(res);
  5942. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5944. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5945. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5946. "7890123456789012345678901234567890",
  5947. res->body);
  5948. EXPECT_EQ(StatusCode::OK_200, res->status);
  5949. }
  5950. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5951. Headers headers;
  5952. headers.emplace("Accept-Encoding", "zstd");
  5953. std::string body;
  5954. auto res = cli_.Get("/compress", headers,
  5955. [&](const char *data, uint64_t data_length) {
  5956. EXPECT_EQ(100U, data_length);
  5957. body.append(data, data_length);
  5958. return true;
  5959. });
  5960. ASSERT_TRUE(res);
  5961. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5962. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5963. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5964. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5965. "7890123456789012345678901234567890",
  5966. body);
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. }
  5969. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5970. Headers headers;
  5971. headers.emplace("Accept-Encoding", "zstd");
  5972. cli_.set_decompress(false);
  5973. auto res = cli_.Get("/compress", headers);
  5974. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5975. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5976. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5977. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5978. ASSERT_TRUE(res);
  5979. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5980. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5981. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5982. EXPECT_EQ(StatusCode::OK_200, res->status);
  5983. ASSERT_EQ(26U, res->body.size());
  5984. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5985. 0);
  5986. }
  5987. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5988. Headers headers;
  5989. headers.emplace("Accept-Encoding", "");
  5990. std::string body;
  5991. auto res = cli_.Get("/compress", headers,
  5992. [&](const char *data, uint64_t data_length) {
  5993. EXPECT_EQ(100U, data_length);
  5994. body.append(data, data_length);
  5995. return true;
  5996. });
  5997. ASSERT_TRUE(res);
  5998. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5999. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6000. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6001. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6002. "7890123456789012345678901234567890",
  6003. body);
  6004. EXPECT_EQ(StatusCode::OK_200, res->status);
  6005. }
  6006. TEST_F(ServerTest, NoZstd) {
  6007. Headers headers;
  6008. headers.emplace("Accept-Encoding", "zstd");
  6009. auto res = cli_.Get("/nocompress", headers);
  6010. ASSERT_TRUE(res);
  6011. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6012. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6013. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6014. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6015. "7890123456789012345678901234567890",
  6016. res->body);
  6017. EXPECT_EQ(StatusCode::OK_200, res->status);
  6018. }
  6019. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6020. Headers headers;
  6021. headers.emplace("Accept-Encoding", "zstd");
  6022. std::string body;
  6023. auto res = cli_.Get("/nocompress", headers,
  6024. [&](const char *data, uint64_t data_length) {
  6025. EXPECT_EQ(100U, data_length);
  6026. body.append(data, data_length);
  6027. return true;
  6028. });
  6029. ASSERT_TRUE(res);
  6030. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6031. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6032. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6033. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6034. "7890123456789012345678901234567890",
  6035. body);
  6036. EXPECT_EQ(StatusCode::OK_200, res->status);
  6037. }
  6038. // TODO: How to enable zstd ??
  6039. TEST_F(ServerTest, MultipartFormDataZstd) {
  6040. UploadFormDataItems items = {
  6041. {"key1", "test", "", ""},
  6042. {"key2", "--abcdefg123", "", ""},
  6043. };
  6044. Headers headers;
  6045. headers.emplace("Accept-Encoding", "zstd");
  6046. cli_.set_compress(true);
  6047. auto res = cli_.Post("/compress-multipart", headers, items);
  6048. ASSERT_TRUE(res);
  6049. EXPECT_EQ(StatusCode::OK_200, res->status);
  6050. }
  6051. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6052. Headers headers;
  6053. headers.emplace("Accept-Encoding", "zstd");
  6054. cli_.set_compress(true);
  6055. auto res = cli_.Put(
  6056. "/put", headers, 3,
  6057. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6058. sink.os << "PUT";
  6059. return true;
  6060. },
  6061. "text/plain");
  6062. ASSERT_TRUE(res);
  6063. EXPECT_EQ(StatusCode::OK_200, res->status);
  6064. EXPECT_EQ("PUT", res->body);
  6065. }
  6066. // Pre-compression logging tests
  6067. TEST_F(ServerTest, PreCompressionLogging) {
  6068. // Test data for compression (matches the actual /compress endpoint content)
  6069. const std::string test_content =
  6070. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6071. "3456789012345678901234567890";
  6072. // Variables to capture logging data
  6073. std::string pre_compression_body;
  6074. std::string pre_compression_content_type;
  6075. std::string pre_compression_content_encoding;
  6076. std::string post_compression_body;
  6077. std::string post_compression_content_type;
  6078. std::string post_compression_content_encoding;
  6079. // Set up pre-compression logger
  6080. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6081. const Response &res) {
  6082. pre_compression_body = res.body;
  6083. pre_compression_content_type = res.get_header_value("Content-Type");
  6084. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6085. });
  6086. // Set up post-compression logger
  6087. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6088. post_compression_body = res.body;
  6089. post_compression_content_type = res.get_header_value("Content-Type");
  6090. post_compression_content_encoding =
  6091. res.get_header_value("Content-Encoding");
  6092. });
  6093. // Test with gzip compression
  6094. Headers headers;
  6095. headers.emplace("Accept-Encoding", "gzip");
  6096. auto res = cli_.Get("/compress", headers);
  6097. // Verify response was compressed
  6098. ASSERT_TRUE(res);
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6101. // Verify pre-compression logger captured uncompressed content
  6102. EXPECT_EQ(test_content, pre_compression_body);
  6103. EXPECT_EQ("text/plain", pre_compression_content_type);
  6104. EXPECT_TRUE(pre_compression_content_encoding
  6105. .empty()); // No encoding header before compression
  6106. // Verify post-compression logger captured compressed content
  6107. EXPECT_NE(test_content,
  6108. post_compression_body); // Should be different after compression
  6109. EXPECT_EQ("text/plain", post_compression_content_type);
  6110. EXPECT_EQ("gzip", post_compression_content_encoding);
  6111. // Verify compressed content is smaller
  6112. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6113. }
  6114. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6115. const std::string test_content =
  6116. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6117. "3456789012345678901234567890";
  6118. std::string pre_compression_body;
  6119. std::string post_compression_body;
  6120. svr_.set_pre_compression_logger(
  6121. [&](const Request & /*req*/, const Response &res) {
  6122. pre_compression_body = res.body;
  6123. });
  6124. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6125. post_compression_body = res.body;
  6126. });
  6127. Headers headers;
  6128. headers.emplace("Accept-Encoding", "br");
  6129. auto res = cli_.Get("/compress", headers);
  6130. ASSERT_TRUE(res);
  6131. EXPECT_EQ(StatusCode::OK_200, res->status);
  6132. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6133. // Verify pre-compression content is uncompressed
  6134. EXPECT_EQ(test_content, pre_compression_body);
  6135. // Verify post-compression content is compressed
  6136. EXPECT_NE(test_content, post_compression_body);
  6137. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6138. }
  6139. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6140. const std::string test_content =
  6141. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6142. "3456789012345678901234567890";
  6143. std::string pre_compression_body;
  6144. std::string post_compression_body;
  6145. svr_.set_pre_compression_logger(
  6146. [&](const Request & /*req*/, const Response &res) {
  6147. pre_compression_body = res.body;
  6148. });
  6149. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6150. post_compression_body = res.body;
  6151. });
  6152. // Request without compression (use /nocompress endpoint)
  6153. Headers headers;
  6154. auto res = cli_.Get("/nocompress", headers);
  6155. ASSERT_TRUE(res);
  6156. EXPECT_EQ(StatusCode::OK_200, res->status);
  6157. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6158. // Pre-compression logger should not be called when no compression is applied
  6159. EXPECT_TRUE(
  6160. pre_compression_body.empty()); // Pre-compression logger not called
  6161. EXPECT_EQ(
  6162. test_content,
  6163. post_compression_body); // Post-compression logger captures final content
  6164. }
  6165. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6166. const std::string test_content =
  6167. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6168. "3456789012345678901234567890";
  6169. std::string pre_compression_body;
  6170. bool pre_logger_called = false;
  6171. // Set only pre-compression logger
  6172. svr_.set_pre_compression_logger(
  6173. [&](const Request & /*req*/, const Response &res) {
  6174. pre_compression_body = res.body;
  6175. pre_logger_called = true;
  6176. });
  6177. Headers headers;
  6178. headers.emplace("Accept-Encoding", "gzip");
  6179. auto res = cli_.Get("/compress", headers);
  6180. ASSERT_TRUE(res);
  6181. EXPECT_EQ(StatusCode::OK_200, res->status);
  6182. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6183. // Verify pre-compression logger was called
  6184. EXPECT_TRUE(pre_logger_called);
  6185. EXPECT_EQ(test_content, pre_compression_body);
  6186. }
  6187. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6188. {
  6189. // Test with Expect: 100-continue header - success case
  6190. // Server returns 100 Continue, client sends body, server returns 200 OK
  6191. Request req;
  6192. req.method = "POST";
  6193. req.path = "/post-large";
  6194. req.set_header("Expect", "100-continue");
  6195. req.body = LARGE_DATA;
  6196. Response res;
  6197. auto error = Error::Success;
  6198. cli_.set_keep_alive(true);
  6199. auto ret = cli_.send(req, res, error);
  6200. EXPECT_TRUE(ret);
  6201. EXPECT_EQ(StatusCode::OK_200, res.status);
  6202. EXPECT_EQ(LARGE_DATA, res.body);
  6203. }
  6204. {
  6205. // Test with Expect: 100-continue header - error case
  6206. // Client should not send the body when server returns an error
  6207. Request req;
  6208. req.method = "POST";
  6209. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6210. req.set_header("Expect", "100-continue");
  6211. req.body = LARGE_DATA;
  6212. Response res;
  6213. auto error = Error::Success;
  6214. auto start = std::chrono::high_resolution_clock::now();
  6215. cli_.set_keep_alive(true);
  6216. auto ret = cli_.send(req, res, error);
  6217. auto end = std::chrono::high_resolution_clock::now();
  6218. auto elapsed =
  6219. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6220. .count();
  6221. // With Expect: 100-continue, request completes successfully but with error
  6222. EXPECT_TRUE(ret);
  6223. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6224. EXPECT_EQ("close", res.get_header_value("Connection"));
  6225. EXPECT_FALSE(cli_.is_socket_open());
  6226. EXPECT_LE(elapsed, 2000);
  6227. }
  6228. {
  6229. // Send an extra GET request to ensure error recovery without hanging
  6230. Request req;
  6231. req.method = "GET";
  6232. req.path = "/hi";
  6233. auto start = std::chrono::high_resolution_clock::now();
  6234. auto res = cli_.send(req);
  6235. auto end = std::chrono::high_resolution_clock::now();
  6236. auto elapsed =
  6237. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6238. .count();
  6239. ASSERT_TRUE(res);
  6240. EXPECT_EQ(StatusCode::OK_200, res->status);
  6241. EXPECT_EQ("Hello World!", res->body);
  6242. EXPECT_LE(elapsed, 500);
  6243. }
  6244. }
  6245. TEST(ZstdDecompressor, ChunkedDecompression) {
  6246. std::string data;
  6247. for (size_t i = 0; i < 32 * 1024; ++i) {
  6248. data.push_back(static_cast<char>('a' + i % 26));
  6249. }
  6250. std::string compressed_data;
  6251. {
  6252. httplib::detail::zstd_compressor compressor;
  6253. bool result = compressor.compress(
  6254. data.data(), data.size(),
  6255. /*last=*/true,
  6256. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6257. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6258. compressed_data_size);
  6259. return true;
  6260. });
  6261. ASSERT_TRUE(result);
  6262. }
  6263. std::string decompressed_data;
  6264. {
  6265. httplib::detail::zstd_decompressor decompressor;
  6266. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6267. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6268. size_t chunk_size = 130;
  6269. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6270. chunk_begin += chunk_size) {
  6271. size_t current_chunk_size =
  6272. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6273. bool result = decompressor.decompress(
  6274. compressed_data.data() + chunk_begin, current_chunk_size,
  6275. [&](const char *decompressed_data_chunk,
  6276. size_t decompressed_data_chunk_size) {
  6277. decompressed_data.insert(decompressed_data.size(),
  6278. decompressed_data_chunk,
  6279. decompressed_data_chunk_size);
  6280. return true;
  6281. });
  6282. ASSERT_TRUE(result);
  6283. }
  6284. }
  6285. ASSERT_EQ(data, decompressed_data);
  6286. }
  6287. TEST(ZstdDecompressor, Decompress) {
  6288. std::string original_text = "Compressed with ZSTD";
  6289. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6290. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6291. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6292. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6293. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6294. std::string decompressed_data;
  6295. {
  6296. httplib::detail::zstd_decompressor decompressor;
  6297. bool result = decompressor.decompress(
  6298. compressed_data.data(), compressed_data.size(),
  6299. [&](const char *decompressed_data_chunk,
  6300. size_t decompressed_data_chunk_size) {
  6301. decompressed_data.insert(decompressed_data.size(),
  6302. decompressed_data_chunk,
  6303. decompressed_data_chunk_size);
  6304. return true;
  6305. });
  6306. ASSERT_TRUE(result);
  6307. }
  6308. ASSERT_EQ(original_text, decompressed_data);
  6309. }
  6310. #endif
  6311. // Sends a raw request to a server listening at HOST:PORT.
  6312. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6313. std::string *resp = nullptr) {
  6314. auto error = Error::Success;
  6315. auto client_sock = detail::create_client_socket(
  6316. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6317. /*connection_timeout_sec=*/5, 0,
  6318. /*read_timeout_sec=*/5, 0,
  6319. /*write_timeout_sec=*/5, 0, std::string(), error);
  6320. if (client_sock == INVALID_SOCKET) { return false; }
  6321. auto ret = detail::process_client_socket(
  6322. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6323. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6324. if (req.size() !=
  6325. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6326. return false;
  6327. }
  6328. char buf[512];
  6329. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6330. while (line_reader.getline()) {
  6331. if (resp) { *resp += line_reader.ptr(); }
  6332. }
  6333. return true;
  6334. });
  6335. detail::close_socket(client_sock);
  6336. return ret;
  6337. }
  6338. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6339. Server svr;
  6340. std::string header_value;
  6341. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6342. header_value = req.get_header_value("foo");
  6343. res.set_content("ok", "text/plain");
  6344. });
  6345. thread t = thread([&] { svr.listen(HOST, PORT); });
  6346. auto se = detail::scope_exit([&] {
  6347. svr.stop();
  6348. t.join();
  6349. ASSERT_FALSE(svr.is_running());
  6350. });
  6351. svr.wait_until_ready();
  6352. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6353. // like characters are not treated the same - use vertical tab and escape.
  6354. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6355. "foo: \t \v bar \x1B\t \r\n"
  6356. "Connection: close\r\n"
  6357. "\r\n";
  6358. std::string res;
  6359. ASSERT_TRUE(send_request(5, req, &res));
  6360. EXPECT_EQ(header_value, "");
  6361. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6362. }
  6363. // Sends a raw request and verifies that there isn't a crash or exception.
  6364. static void test_raw_request(const std::string &req,
  6365. std::string *out = nullptr) {
  6366. Server svr;
  6367. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6368. res.set_content("ok", "text/plain");
  6369. });
  6370. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6371. res.set_content("ok", "text/plain");
  6372. });
  6373. svr.Get("/header_field_value_check",
  6374. [&](const Request & /*req*/, Response &res) {
  6375. res.set_content("ok", "text/plain");
  6376. });
  6377. // Server read timeout must be longer than the client read timeout for the
  6378. // bug to reproduce, probably to force the server to process a request
  6379. // without a trailing blank line.
  6380. const time_t client_read_timeout_sec = 1;
  6381. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6382. bool listen_thread_ok = false;
  6383. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6384. auto se = detail::scope_exit([&] {
  6385. svr.stop();
  6386. t.join();
  6387. ASSERT_FALSE(svr.is_running());
  6388. EXPECT_TRUE(listen_thread_ok);
  6389. });
  6390. svr.wait_until_ready();
  6391. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6392. }
  6393. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6394. // A certain header line causes an exception if the header property is parsed
  6395. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6396. test_raw_request(
  6397. "GET /hi HTTP/1.1\r\n"
  6398. " : "
  6399. " "
  6400. " ");
  6401. }
  6402. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6403. // A certain header line causes an exception if the header property *name* is
  6404. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6405. // greedy matcher and requires backtracking when there are a lot of ":"
  6406. // characters.
  6407. // This occurs with libc++ but not libstdc++.
  6408. test_raw_request(
  6409. "GET /hi HTTP/1.1\r\n"
  6410. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6411. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6412. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6413. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6414. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6415. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6416. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6417. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6418. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6419. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6420. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6421. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6422. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6423. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6424. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6425. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6426. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6427. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6428. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6429. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6430. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6431. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6432. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6433. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6434. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6435. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6436. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6437. "&&&%%%");
  6438. }
  6439. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6440. // Make sure this doesn't crash the server.
  6441. // In a previous version of the header line regex, the "\r" rendered the line
  6442. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6443. // a new position where the leading white space ended and the field value
  6444. // began.
  6445. // The crash occurs with libc++ but not libstdc++.
  6446. test_raw_request("GET /hi HTTP/1.1\r\n"
  6447. "a:" +
  6448. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6449. "\r\n"
  6450. "\r\n");
  6451. }
  6452. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6453. std::string out;
  6454. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6455. "Content-Type: text/plain\r\n"
  6456. "Transfer-Encoding: chunked\r\n"
  6457. "\r\n"
  6458. "nothex\r\n",
  6459. &out);
  6460. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6461. }
  6462. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6463. std::string out;
  6464. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6465. "Content-Type: text/plain\r\n"
  6466. "Transfer-Encoding: chunked\r\n"
  6467. "\r\n"
  6468. "3\r\n"
  6469. "xyz\r\n"
  6470. "NaN\r\n",
  6471. &out);
  6472. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6473. }
  6474. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6475. std::string out;
  6476. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6477. "Content-Type: text/plain\r\n"
  6478. "Transfer-Encoding: chunked\r\n"
  6479. "\r\n"
  6480. // Length is too large for 64 bits.
  6481. "1ffffffffffffffff\r\n"
  6482. "xyz\r\n",
  6483. &out);
  6484. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6485. }
  6486. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6487. test_raw_request("GET /hi HTTP/1.1\r\n"
  6488. "Content-Type: text/plain\r\n\r");
  6489. }
  6490. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6491. std::string out;
  6492. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6493. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6494. }
  6495. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6496. Server svr;
  6497. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6498. EXPECT_TRUE(!req.remote_addr.empty());
  6499. });
  6500. thread t = thread([&] { svr.listen(HOST, PORT); });
  6501. auto se = detail::scope_exit([&] {
  6502. svr.stop();
  6503. t.join();
  6504. ASSERT_FALSE(svr.is_running());
  6505. });
  6506. svr.wait_until_ready();
  6507. // Send an invalid request line to trigger Bad Request
  6508. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6509. std::string out;
  6510. ASSERT_TRUE(send_request(5, bad_req, &out));
  6511. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6512. }
  6513. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6514. std::string out;
  6515. std::string request(
  6516. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6517. test_raw_request(request, &out);
  6518. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6519. }
  6520. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6521. std::string out;
  6522. std::string request(
  6523. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6524. test_raw_request(request, &out);
  6525. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6526. }
  6527. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6528. std::string out;
  6529. std::string request(
  6530. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6531. test_raw_request(request, &out);
  6532. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6533. }
  6534. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6535. std::string out;
  6536. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6537. "Test: \r\n\r\n",
  6538. &out);
  6539. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6540. }
  6541. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6542. Server svr;
  6543. std::string x_custom;
  6544. std::string cookie;
  6545. std::string xff;
  6546. std::string x_unicode;
  6547. std::string x_iis;
  6548. svr.Get("/check", [&](const Request &req, Response &res) {
  6549. x_custom = req.get_header_value("X-Custom");
  6550. cookie = req.get_header_value("Cookie");
  6551. xff = req.get_header_value("X-Forwarded-For");
  6552. x_unicode = req.get_header_value("X-Unicode");
  6553. x_iis = req.get_header_value("X-IIS");
  6554. res.set_content("ok", "text/plain");
  6555. });
  6556. thread t = thread([&] { svr.listen(HOST, PORT); });
  6557. auto se = detail::scope_exit([&] {
  6558. svr.stop();
  6559. t.join();
  6560. ASSERT_FALSE(svr.is_running());
  6561. });
  6562. svr.wait_until_ready();
  6563. const std::string req = "GET /check HTTP/1.1\r\n"
  6564. "Host: localhost\r\n"
  6565. "X-Custom: a%0D%0AInjected: b\r\n"
  6566. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6567. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6568. "X-Unicode: %E3%81%82\r\n"
  6569. "X-IIS: %u00E9\r\n"
  6570. "Connection: close\r\n"
  6571. "\r\n";
  6572. std::string res;
  6573. ASSERT_TRUE(send_request(5, req, &res));
  6574. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6575. // Every value must be returned verbatim (wire form), with no decoding.
  6576. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6577. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6578. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6579. EXPECT_EQ("%E3%81%82", x_unicode);
  6580. EXPECT_EQ("%u00E9", x_iis);
  6581. }
  6582. // Applications that previously relied on automatic percent-decoding can
  6583. // reproduce the old behavior by explicitly calling decode_path_component()
  6584. // or, for RFC 3986 conformance, decode_uri_component().
  6585. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6586. Server svr;
  6587. std::string decoded;
  6588. svr.Get("/check", [&](const Request &req, Response &res) {
  6589. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6590. res.set_content("ok", "text/plain");
  6591. });
  6592. thread t = thread([&] { svr.listen(HOST, PORT); });
  6593. auto se = detail::scope_exit([&] {
  6594. svr.stop();
  6595. t.join();
  6596. ASSERT_FALSE(svr.is_running());
  6597. });
  6598. svr.wait_until_ready();
  6599. const std::string req = "GET /check HTTP/1.1\r\n"
  6600. "Host: localhost\r\n"
  6601. "X-Custom: hello%20world\r\n"
  6602. "Connection: close\r\n"
  6603. "\r\n";
  6604. std::string res;
  6605. ASSERT_TRUE(send_request(5, req, &res));
  6606. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6607. EXPECT_EQ("hello world", decoded);
  6608. }
  6609. // Regression test for #2033. Browsers send Referer values that include
  6610. // percent-encoded characters such as %0A inside the URL. Decoding the
  6611. // header value would either trip the post-decode CR/LF/NUL guard (the
  6612. // original bug, returning 400) or, after that guard was relaxed, silently
  6613. // store a literal LF — both unacceptable. The wire form must round-trip.
  6614. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6615. Server svr;
  6616. std::string referer;
  6617. svr.Get("/check", [&](const Request &req, Response &res) {
  6618. referer = req.get_header_value("Referer");
  6619. res.set_content("ok", "text/plain");
  6620. });
  6621. thread t = thread([&] { svr.listen(HOST, PORT); });
  6622. auto se = detail::scope_exit([&] {
  6623. svr.stop();
  6624. t.join();
  6625. ASSERT_FALSE(svr.is_running());
  6626. });
  6627. svr.wait_until_ready();
  6628. const std::string req = "GET /check HTTP/1.1\r\n"
  6629. "Host: localhost\r\n"
  6630. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6631. "Connection: close\r\n"
  6632. "\r\n";
  6633. std::string res;
  6634. ASSERT_TRUE(send_request(5, req, &res));
  6635. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6636. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6637. }
  6638. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6639. Server svr;
  6640. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6641. res.set_header("Cache-Control", "no-cache");
  6642. res.set_chunked_content_provider(
  6643. "text/event-stream", [](size_t offset, DataSink &sink) {
  6644. std::string s = "data:";
  6645. s += std::to_string(offset);
  6646. s += "\n\n";
  6647. auto ret = sink.write(s.data(), s.size());
  6648. EXPECT_TRUE(ret);
  6649. std::this_thread::sleep_for(std::chrono::seconds(1));
  6650. return true;
  6651. });
  6652. });
  6653. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6654. svr.wait_until_ready();
  6655. Client client(HOST, PORT);
  6656. const Headers headers = {{"Accept", "text/event-stream"}};
  6657. auto get_thread = std::thread([&client, &headers]() {
  6658. auto res = client.Get(
  6659. "/events", headers,
  6660. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6661. });
  6662. auto se = detail::scope_exit([&] {
  6663. svr.stop();
  6664. get_thread.join();
  6665. listen_thread.join();
  6666. ASSERT_FALSE(svr.is_running());
  6667. });
  6668. // Give GET time to get a few messages.
  6669. std::this_thread::sleep_for(std::chrono::seconds(2));
  6670. }
  6671. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6672. httplib::Server svr;
  6673. svr.Post("/hi",
  6674. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6675. res.status = StatusCode::OK_200;
  6676. });
  6677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6678. svr.wait_until_ready();
  6679. Client cli(HOST, PORT);
  6680. auto res = cli.Post("/hi", "data", "text/plain");
  6681. ASSERT_TRUE(res);
  6682. EXPECT_EQ(StatusCode::OK_200, res->status);
  6683. svr.stop();
  6684. thread.join();
  6685. ASSERT_FALSE(svr.is_running());
  6686. res = cli.Post("/hi", "data", "text/plain");
  6687. ASSERT_FALSE(res);
  6688. }
  6689. TEST(ServerStopTest, ListenFailure) {
  6690. Server svr;
  6691. auto t = thread([&]() {
  6692. auto ret = svr.listen("????", PORT);
  6693. EXPECT_FALSE(ret);
  6694. });
  6695. svr.wait_until_ready();
  6696. svr.stop();
  6697. t.join();
  6698. }
  6699. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6700. TEST(ServerStopTest, Decommision) {
  6701. Server svr;
  6702. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6703. for (int i = 0; i < 4; i++) {
  6704. auto is_even = !(i % 2);
  6705. std::thread t{[&] {
  6706. try {
  6707. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6708. if (is_even) {
  6709. throw std::runtime_error("Some thing that happens to go wrong.");
  6710. }
  6711. svr.listen(HOST, PORT);
  6712. } catch (...) { svr.decommission(); }
  6713. }};
  6714. svr.wait_until_ready();
  6715. // Server is up
  6716. {
  6717. Client cli(HOST, PORT);
  6718. auto res = cli.Get("/hi");
  6719. if (is_even) {
  6720. EXPECT_FALSE(res);
  6721. } else {
  6722. EXPECT_TRUE(res);
  6723. EXPECT_EQ("hi...", res->body);
  6724. }
  6725. }
  6726. svr.stop();
  6727. t.join();
  6728. // Server is down...
  6729. {
  6730. Client cli(HOST, PORT);
  6731. auto res = cli.Get("/hi");
  6732. EXPECT_FALSE(res);
  6733. }
  6734. }
  6735. }
  6736. #endif
  6737. // Helper function for string body upload progress tests
  6738. template <typename SetupHandler, typename ClientCall>
  6739. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6740. ClientCall &&client_call,
  6741. const string &body) {
  6742. Server svr;
  6743. setup_handler(svr);
  6744. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6745. auto se = detail::scope_exit([&] {
  6746. svr.stop();
  6747. t.join();
  6748. });
  6749. svr.wait_until_ready();
  6750. Client cli(HOST, PORT);
  6751. vector<uint64_t> progress_values;
  6752. bool progress_called = false;
  6753. auto res =
  6754. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6755. progress_values.push_back(current);
  6756. progress_called = true;
  6757. return true;
  6758. });
  6759. ASSERT_TRUE(res);
  6760. EXPECT_EQ(200, res->status);
  6761. EXPECT_TRUE(progress_called);
  6762. }
  6763. TEST(UploadProgressTest, PostStringBodyBasic) {
  6764. TestStringBodyUploadProgress(
  6765. [](Server &svr) {
  6766. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6767. res.set_content("received", "text/plain");
  6768. });
  6769. },
  6770. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6771. return cli.Post("/test", body, "text/plain", progress_callback);
  6772. },
  6773. "test data for upload progress");
  6774. }
  6775. TEST(UploadProgressTest, PutStringBodyBasic) {
  6776. TestStringBodyUploadProgress(
  6777. [](Server &svr) {
  6778. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6779. res.set_content("put received", "text/plain");
  6780. });
  6781. },
  6782. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6783. return cli.Put("/test", body, "text/plain", progress_callback);
  6784. },
  6785. "put test data for upload progress");
  6786. }
  6787. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6788. TestStringBodyUploadProgress(
  6789. [](Server &svr) {
  6790. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6791. res.set_content("patch received", "text/plain");
  6792. });
  6793. },
  6794. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6795. return cli.Patch("/test", body, "text/plain", progress_callback);
  6796. },
  6797. "patch test data for upload progress");
  6798. }
  6799. // Helper function for content provider upload progress tests
  6800. template <typename SetupHandler, typename ClientCall>
  6801. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6802. ClientCall &&client_call) {
  6803. Server svr;
  6804. setup_handler(svr);
  6805. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6806. auto se = detail::scope_exit([&] {
  6807. svr.stop();
  6808. t.join();
  6809. });
  6810. svr.wait_until_ready();
  6811. Client cli(HOST, PORT);
  6812. vector<uint64_t> progress_values;
  6813. auto res =
  6814. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6815. progress_values.push_back(current);
  6816. return true;
  6817. });
  6818. ASSERT_TRUE(res);
  6819. EXPECT_EQ(200, res->status);
  6820. EXPECT_FALSE(progress_values.empty());
  6821. }
  6822. TEST(UploadProgressTest, PostContentProviderProgress) {
  6823. TestContentProviderUploadProgress(
  6824. [](Server &svr) {
  6825. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6826. res.set_content("provider received", "text/plain");
  6827. });
  6828. },
  6829. [](Client &cli, UploadProgress progress_callback) {
  6830. return cli.Post(
  6831. "/test", 10,
  6832. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6833. sink.os << "test data";
  6834. return true;
  6835. },
  6836. "text/plain", progress_callback);
  6837. });
  6838. }
  6839. // Helper function for multipart upload progress tests
  6840. template <typename SetupHandler, typename ClientCall>
  6841. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6842. ClientCall &&client_call,
  6843. const string &endpoint) {
  6844. Server svr;
  6845. setup_handler(svr);
  6846. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6847. auto se = detail::scope_exit([&] {
  6848. svr.stop();
  6849. t.join();
  6850. });
  6851. svr.wait_until_ready();
  6852. Client cli(HOST, PORT);
  6853. vector<uint64_t> progress_values;
  6854. UploadFormDataItems items = {
  6855. {"field1", "value1", "", ""},
  6856. {"field2", "longer value for progress tracking test", "", ""},
  6857. {"file1", "file content data for upload progress", "test.txt",
  6858. "text/plain"}};
  6859. auto res = client_call(cli, endpoint, items,
  6860. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6861. progress_values.push_back(current);
  6862. return true;
  6863. });
  6864. ASSERT_TRUE(res);
  6865. EXPECT_EQ(200, res->status);
  6866. EXPECT_FALSE(progress_values.empty());
  6867. }
  6868. TEST(UploadProgressTest, PostMultipartProgress) {
  6869. TestMultipartUploadProgress(
  6870. [](Server &svr) {
  6871. svr.Post("/multipart", [](const Request &req, Response &res) {
  6872. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6873. res.set_content("multipart received", "text/plain");
  6874. });
  6875. },
  6876. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6877. UploadProgress progress_callback) {
  6878. return cli.Post(endpoint, items, progress_callback);
  6879. },
  6880. "/multipart");
  6881. }
  6882. // Helper function for basic download progress tests
  6883. template <typename SetupHandler, typename ClientCall>
  6884. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6885. ClientCall &&client_call, const string &endpoint,
  6886. size_t expected_content_size) {
  6887. Server svr;
  6888. setup_handler(svr);
  6889. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6890. auto se = detail::scope_exit([&] {
  6891. svr.stop();
  6892. t.join();
  6893. });
  6894. svr.wait_until_ready();
  6895. Client cli(HOST, PORT);
  6896. vector<uint64_t> progress_values;
  6897. auto res = client_call(cli, endpoint,
  6898. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6899. progress_values.push_back(current);
  6900. return true;
  6901. });
  6902. ASSERT_TRUE(res);
  6903. EXPECT_EQ(200, res->status);
  6904. EXPECT_FALSE(progress_values.empty());
  6905. EXPECT_EQ(expected_content_size, res->body.size());
  6906. }
  6907. TEST(DownloadProgressTest, GetBasic) {
  6908. TestBasicDownloadProgress(
  6909. [](Server &svr) {
  6910. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6911. string content(1000, 'D');
  6912. res.set_content(content, "text/plain");
  6913. });
  6914. },
  6915. [](Client &cli, const string &endpoint,
  6916. DownloadProgress progress_callback) {
  6917. return cli.Get(endpoint, progress_callback);
  6918. },
  6919. "/download", 1000u);
  6920. }
  6921. // Helper function for content receiver download progress tests
  6922. template <typename SetupHandler, typename ClientCall>
  6923. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6924. ClientCall &&client_call,
  6925. const string &endpoint,
  6926. size_t expected_content_size) {
  6927. Server svr;
  6928. setup_handler(svr);
  6929. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6930. auto se = detail::scope_exit([&] {
  6931. svr.stop();
  6932. t.join();
  6933. });
  6934. svr.wait_until_ready();
  6935. Client cli(HOST, PORT);
  6936. vector<uint64_t> progress_values;
  6937. string received_body;
  6938. auto res = client_call(
  6939. cli, endpoint,
  6940. [&](const char *data, size_t data_length) -> bool {
  6941. received_body.append(data, data_length);
  6942. return true;
  6943. },
  6944. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6945. progress_values.push_back(current);
  6946. return true;
  6947. });
  6948. ASSERT_TRUE(res);
  6949. EXPECT_EQ(200, res->status);
  6950. EXPECT_FALSE(progress_values.empty());
  6951. EXPECT_EQ(expected_content_size, received_body.size());
  6952. EXPECT_TRUE(res->body.empty());
  6953. }
  6954. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6955. TestContentReceiverDownloadProgress(
  6956. [](Server &svr) {
  6957. svr.Get("/download-receiver",
  6958. [](const Request & /*req*/, Response &res) {
  6959. string content(2000, 'R');
  6960. res.set_content(content, "text/plain");
  6961. });
  6962. },
  6963. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6964. DownloadProgress progress_callback) {
  6965. return cli.Get(endpoint, content_receiver, progress_callback);
  6966. },
  6967. "/download-receiver", 2000u);
  6968. }
  6969. TEST(StreamingTest, NoContentLengthStreaming) {
  6970. Server svr;
  6971. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6972. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6973. if (offset < 6) {
  6974. sink.os << (offset < 3 ? "a" : "b");
  6975. } else {
  6976. sink.done();
  6977. }
  6978. return true;
  6979. });
  6980. });
  6981. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6982. auto listen_se = detail::scope_exit([&] {
  6983. svr.stop();
  6984. listen_thread.join();
  6985. ASSERT_FALSE(svr.is_running());
  6986. });
  6987. svr.wait_until_ready();
  6988. Client client(HOST, PORT);
  6989. auto get_thread = std::thread([&client]() {
  6990. std::string s;
  6991. auto res =
  6992. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6993. s += std::string(data, len);
  6994. return true;
  6995. });
  6996. ASSERT_TRUE(res);
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. EXPECT_EQ("aaabbb", s);
  6999. });
  7000. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7001. // Give GET time to get a few messages.
  7002. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7003. }
  7004. TEST(MountTest, Unmount) {
  7005. Server svr;
  7006. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7007. auto se = detail::scope_exit([&] {
  7008. svr.stop();
  7009. listen_thread.join();
  7010. ASSERT_FALSE(svr.is_running());
  7011. });
  7012. svr.wait_until_ready();
  7013. Client cli("localhost", PORT);
  7014. svr.set_mount_point("/mount2", "./www2");
  7015. auto res = cli.Get("/");
  7016. ASSERT_TRUE(res);
  7017. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7018. res = cli.Get("/mount2/dir/test.html");
  7019. ASSERT_TRUE(res);
  7020. EXPECT_EQ(StatusCode::OK_200, res->status);
  7021. svr.set_mount_point("/", "./www");
  7022. res = cli.Get("/dir/");
  7023. ASSERT_TRUE(res);
  7024. EXPECT_EQ(StatusCode::OK_200, res->status);
  7025. svr.remove_mount_point("/");
  7026. res = cli.Get("/dir/");
  7027. ASSERT_TRUE(res);
  7028. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7029. svr.remove_mount_point("/mount2");
  7030. res = cli.Get("/mount2/dir/test.html");
  7031. ASSERT_TRUE(res);
  7032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7033. }
  7034. TEST(MountTest, Redicect) {
  7035. Server svr;
  7036. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7037. auto se = detail::scope_exit([&] {
  7038. svr.stop();
  7039. listen_thread.join();
  7040. ASSERT_FALSE(svr.is_running());
  7041. });
  7042. svr.set_mount_point("/", "./www");
  7043. svr.wait_until_ready();
  7044. Client cli("localhost", PORT);
  7045. auto res = cli.Get("/dir/");
  7046. ASSERT_TRUE(res);
  7047. EXPECT_EQ(StatusCode::OK_200, res->status);
  7048. res = cli.Get("/dir");
  7049. ASSERT_TRUE(res);
  7050. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7051. res = cli.Get("/file");
  7052. ASSERT_TRUE(res);
  7053. EXPECT_EQ(StatusCode::OK_200, res->status);
  7054. res = cli.Get("/file/");
  7055. ASSERT_TRUE(res);
  7056. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7057. cli.set_follow_location(true);
  7058. res = cli.Get("/dir");
  7059. ASSERT_TRUE(res);
  7060. EXPECT_EQ(StatusCode::OK_200, res->status);
  7061. }
  7062. TEST(MountTest, MultibytesPathName) {
  7063. Server svr;
  7064. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7065. auto se = detail::scope_exit([&] {
  7066. svr.stop();
  7067. listen_thread.join();
  7068. ASSERT_FALSE(svr.is_running());
  7069. });
  7070. svr.set_mount_point("/", "./www");
  7071. svr.wait_until_ready();
  7072. Client cli("localhost", PORT);
  7073. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7074. ASSERT_TRUE(res);
  7075. EXPECT_EQ(StatusCode::OK_200, res->status);
  7076. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7077. }
  7078. #ifdef _WIN32
  7079. // Issue #2435: mmap::open() must succeed even when another handle holds
  7080. // the file open for writing (e.g. an active log file).
  7081. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7082. const char *path = "mmap_concurrent_writer_test.txt";
  7083. const char *content = "hello";
  7084. {
  7085. std::ofstream f(path, std::ios::binary);
  7086. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7087. }
  7088. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7089. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7090. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7091. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7092. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7093. detail::mmap m(path);
  7094. ASSERT_TRUE(m.is_open());
  7095. EXPECT_EQ(strlen(content), m.size());
  7096. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7097. }
  7098. #endif
  7099. TEST(KeepAliveTest, ReadTimeout) {
  7100. Server svr;
  7101. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7102. std::this_thread::sleep_for(std::chrono::seconds(2));
  7103. res.set_content("a", "text/plain");
  7104. });
  7105. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7106. res.set_content("b", "text/plain");
  7107. });
  7108. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7109. auto se = detail::scope_exit([&] {
  7110. svr.stop();
  7111. listen_thread.join();
  7112. ASSERT_FALSE(svr.is_running());
  7113. });
  7114. svr.wait_until_ready();
  7115. Client cli("localhost", PORT);
  7116. cli.set_keep_alive(true);
  7117. cli.set_read_timeout(std::chrono::seconds(1));
  7118. auto resa = cli.Get("/a");
  7119. ASSERT_FALSE(resa);
  7120. EXPECT_EQ(Error::Read, resa.error());
  7121. auto resb = cli.Get("/b");
  7122. ASSERT_TRUE(resb);
  7123. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7124. EXPECT_EQ("b", resb->body);
  7125. }
  7126. TEST(KeepAliveTest, MaxCount) {
  7127. size_t keep_alive_max_count = 3;
  7128. Server svr;
  7129. svr.set_keep_alive_max_count(keep_alive_max_count);
  7130. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7131. res.set_content("Hello World!", "text/plain");
  7132. });
  7133. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7134. auto se = detail::scope_exit([&] {
  7135. svr.stop();
  7136. listen_thread.join();
  7137. ASSERT_FALSE(svr.is_running());
  7138. });
  7139. svr.wait_until_ready();
  7140. Client cli(HOST, PORT);
  7141. cli.set_keep_alive(true);
  7142. for (size_t i = 0; i < 5; i++) {
  7143. auto result = cli.Get("/hi");
  7144. ASSERT_TRUE(result);
  7145. EXPECT_EQ(StatusCode::OK_200, result->status);
  7146. if (i == keep_alive_max_count - 1) {
  7147. EXPECT_EQ("close", result->get_header_value("Connection"));
  7148. } else {
  7149. EXPECT_FALSE(result->has_header("Connection"));
  7150. }
  7151. }
  7152. }
  7153. TEST(KeepAliveTest, Issue1041) {
  7154. Server svr;
  7155. svr.set_keep_alive_timeout(3);
  7156. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7157. res.set_content("Hello World!", "text/plain");
  7158. });
  7159. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7160. auto se = detail::scope_exit([&] {
  7161. svr.stop();
  7162. listen_thread.join();
  7163. ASSERT_FALSE(svr.is_running());
  7164. });
  7165. svr.wait_until_ready();
  7166. Client cli(HOST, PORT);
  7167. cli.set_keep_alive(true);
  7168. auto result = cli.Get("/hi");
  7169. ASSERT_TRUE(result);
  7170. EXPECT_EQ(StatusCode::OK_200, result->status);
  7171. std::this_thread::sleep_for(std::chrono::seconds(5));
  7172. result = cli.Get("/hi");
  7173. ASSERT_TRUE(result);
  7174. EXPECT_EQ(StatusCode::OK_200, result->status);
  7175. }
  7176. TEST(KeepAliveTest, Issue1959) {
  7177. Server svr;
  7178. svr.set_keep_alive_timeout(5);
  7179. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7180. res.set_content("a", "text/plain");
  7181. });
  7182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7183. auto se = detail::scope_exit([&] {
  7184. if (!svr.is_running()) return;
  7185. svr.stop();
  7186. listen_thread.join();
  7187. ASSERT_FALSE(svr.is_running());
  7188. });
  7189. svr.wait_until_ready();
  7190. Client cli("localhost", PORT);
  7191. cli.set_keep_alive(true);
  7192. using namespace std::chrono;
  7193. auto start = steady_clock::now();
  7194. cli.Get("/a");
  7195. svr.stop();
  7196. listen_thread.join();
  7197. auto end = steady_clock::now();
  7198. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7199. EXPECT_LT(elapsed, 5000);
  7200. }
  7201. #ifdef CPPHTTPLIB_SSL_ENABLED
  7202. TEST(KeepAliveTest, SSLClientReconnection) {
  7203. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7204. ASSERT_TRUE(svr.is_valid());
  7205. svr.set_keep_alive_timeout(1);
  7206. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7207. res.set_content("Hello World!", "text/plain");
  7208. });
  7209. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7210. auto se = detail::scope_exit([&] {
  7211. svr.stop();
  7212. listen_thread.join();
  7213. ASSERT_FALSE(svr.is_running());
  7214. });
  7215. svr.wait_until_ready();
  7216. SSLClient cli(HOST, PORT);
  7217. cli.enable_server_certificate_verification(false);
  7218. cli.set_keep_alive(true);
  7219. auto result = cli.Get("/hi");
  7220. ASSERT_TRUE(result);
  7221. EXPECT_EQ(StatusCode::OK_200, result->status);
  7222. result = cli.Get("/hi");
  7223. ASSERT_TRUE(result);
  7224. EXPECT_EQ(StatusCode::OK_200, result->status);
  7225. std::this_thread::sleep_for(std::chrono::seconds(2));
  7226. // Recoonect
  7227. result = cli.Get("/hi");
  7228. ASSERT_TRUE(result);
  7229. EXPECT_EQ(StatusCode::OK_200, result->status);
  7230. result = cli.Get("/hi");
  7231. ASSERT_TRUE(result);
  7232. EXPECT_EQ(StatusCode::OK_200, result->status);
  7233. }
  7234. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7236. ASSERT_TRUE(svr.is_valid());
  7237. svr.set_keep_alive_timeout(1);
  7238. std::string content = "reconnect";
  7239. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7240. res.set_content("Hello World!", "text/plain");
  7241. });
  7242. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7243. auto se = detail::scope_exit([&] {
  7244. svr.stop();
  7245. listen_thread.join();
  7246. ASSERT_FALSE(svr.is_running());
  7247. });
  7248. svr.wait_until_ready();
  7249. SSLClient cli(HOST, PORT);
  7250. cli.enable_server_certificate_verification(false);
  7251. cli.set_keep_alive(true);
  7252. auto result = cli.Post(
  7253. "/hi", content.size(),
  7254. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7255. sink.write(content.c_str(), content.size());
  7256. return true;
  7257. },
  7258. "text/plain");
  7259. ASSERT_TRUE(result);
  7260. EXPECT_EQ(200, result->status);
  7261. std::this_thread::sleep_for(std::chrono::seconds(2));
  7262. // Recoonect
  7263. result = cli.Post(
  7264. "/hi", content.size(),
  7265. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7266. sink.write(content.c_str(), content.size());
  7267. return true;
  7268. },
  7269. "text/plain");
  7270. ASSERT_TRUE(result);
  7271. EXPECT_EQ(200, result->status);
  7272. result = cli.Post(
  7273. "/hi", content.size(),
  7274. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7275. sink.write(content.c_str(), content.size());
  7276. return true;
  7277. },
  7278. "text/plain");
  7279. ASSERT_TRUE(result);
  7280. EXPECT_EQ(200, result->status);
  7281. }
  7282. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7283. using namespace httplib::tls;
  7284. {
  7285. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7286. ASSERT_TRUE(svr.is_valid());
  7287. svr.Get("/sni", [&](const Request &req, Response &res) {
  7288. std::string expected = req.sni();
  7289. EXPECT_EQ(expected, req.get_param_value("expected"));
  7290. res.set_content("ok", "text/plain");
  7291. });
  7292. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7293. auto se = detail::scope_exit([&] {
  7294. svr.stop();
  7295. listen_thread.join();
  7296. ASSERT_FALSE(svr.is_running());
  7297. });
  7298. svr.wait_until_ready();
  7299. {
  7300. SSLClient cli("localhost", PORT);
  7301. cli.enable_server_certificate_verification(false);
  7302. auto res = cli.Get("/sni?expected=localhost");
  7303. ASSERT_TRUE(res);
  7304. }
  7305. {
  7306. SSLClient cli("::1", PORT);
  7307. cli.enable_server_certificate_verification(false);
  7308. auto res = cli.Get("/sni?expected=");
  7309. // NOTE: This may fail if the server is listening on IPv4 only
  7310. // (e.g., when localhost resolves to 127.0.0.1 only)
  7311. if (res) {
  7312. EXPECT_EQ(StatusCode::OK_200, res->status);
  7313. } else {
  7314. EXPECT_EQ(Error::Connection, res.error());
  7315. }
  7316. }
  7317. }
  7318. }
  7319. #endif
  7320. TEST(ClientProblemDetectionTest, ContentProvider) {
  7321. Server svr;
  7322. size_t content_length = 1024 * 1024;
  7323. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7324. res.set_content_provider(
  7325. content_length, "text/plain",
  7326. [&](size_t offset, size_t length, DataSink &sink) {
  7327. auto out_len = std::min(length, static_cast<size_t>(1024));
  7328. std::string out(out_len, '@');
  7329. sink.write(out.data(), out_len);
  7330. return offset < 4096;
  7331. },
  7332. [](bool success) { ASSERT_FALSE(success); });
  7333. });
  7334. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7335. res.set_content_provider(
  7336. 0, "text/plain",
  7337. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7338. EXPECT_TRUE(false);
  7339. return true;
  7340. },
  7341. [](bool success) { ASSERT_FALSE(success); });
  7342. });
  7343. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7344. auto se = detail::scope_exit([&] {
  7345. svr.stop();
  7346. listen_thread.join();
  7347. ASSERT_FALSE(svr.is_running());
  7348. });
  7349. svr.wait_until_ready();
  7350. Client cli("localhost", PORT);
  7351. {
  7352. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7353. size_t /*data_length*/) { return false; });
  7354. ASSERT_FALSE(res);
  7355. }
  7356. {
  7357. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7358. size_t /*data_length*/) { return false; });
  7359. ASSERT_TRUE(res);
  7360. }
  7361. }
  7362. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7363. Server svr;
  7364. svr.set_error_handler([](Request const &, Response &res) -> void {
  7365. res.set_chunked_content_provider(
  7366. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7367. sink.os << "hello";
  7368. sink.os << "world";
  7369. sink.done();
  7370. return true;
  7371. });
  7372. });
  7373. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7374. auto se = detail::scope_exit([&] {
  7375. svr.stop();
  7376. listen_thread.join();
  7377. ASSERT_FALSE(svr.is_running());
  7378. });
  7379. svr.wait_until_ready();
  7380. Client cli("localhost", PORT);
  7381. auto res = cli.Get("/");
  7382. ASSERT_TRUE(res);
  7383. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7384. EXPECT_EQ("helloworld", res->body);
  7385. }
  7386. TEST(LongPollingTest, ClientCloseDetection) {
  7387. Server svr;
  7388. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7389. res.set_chunked_content_provider(
  7390. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7391. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7392. sink.os << "hello";
  7393. auto count = 10;
  7394. while (count > 0 && sink.is_writable()) {
  7395. this_thread::sleep_for(chrono::milliseconds(10));
  7396. count--;
  7397. }
  7398. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7399. return true;
  7400. });
  7401. });
  7402. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7403. auto se = detail::scope_exit([&] {
  7404. svr.stop();
  7405. listen_thread.join();
  7406. ASSERT_FALSE(svr.is_running());
  7407. });
  7408. svr.wait_until_ready();
  7409. Client cli("localhost", PORT);
  7410. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7411. EXPECT_EQ("hello", string(data, data_length));
  7412. return false; // close the socket immediately.
  7413. });
  7414. ASSERT_FALSE(res);
  7415. }
  7416. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7417. Server svr;
  7418. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7419. res.set_chunked_content_provider(
  7420. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7421. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7422. sink.os << "hello";
  7423. EXPECT_TRUE(sink.os.good());
  7424. // Wait for the client to close the connection
  7425. auto count = 10;
  7426. while (count > 0 && sink.is_writable()) {
  7427. this_thread::sleep_for(chrono::milliseconds(10));
  7428. count--;
  7429. }
  7430. // After client disconnect, write repeatedly until the socket
  7431. // write actually fails (small writes may be absorbed by the
  7432. // kernel buffer)
  7433. std::string chunk(1024, 'x');
  7434. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7435. sink.os << chunk;
  7436. }
  7437. EXPECT_TRUE(sink.os.fail());
  7438. return true;
  7439. });
  7440. });
  7441. auto port = svr.bind_to_any_port("localhost");
  7442. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7443. auto se = detail::scope_exit([&] {
  7444. svr.stop();
  7445. listen_thread.join();
  7446. ASSERT_FALSE(svr.is_running());
  7447. });
  7448. svr.wait_until_ready();
  7449. Client cli("localhost", port);
  7450. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7451. EXPECT_EQ("hello", string(data, data_length));
  7452. return false; // close the socket immediately.
  7453. });
  7454. ASSERT_FALSE(res);
  7455. }
  7456. TEST(GetWithParametersTest, GetWithParameters) {
  7457. Server svr;
  7458. svr.Get("/", [&](const Request &req, Response &) {
  7459. EXPECT_EQ("world", req.get_param_value("hello"));
  7460. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7461. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7462. });
  7463. svr.Get("/params", [&](const Request &req, Response &) {
  7464. EXPECT_EQ("world", req.get_param_value("hello"));
  7465. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7466. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7467. });
  7468. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7469. EXPECT_EQ("resource-id", req.matches[1]);
  7470. EXPECT_EQ("foo", req.get_param_value("param1"));
  7471. EXPECT_EQ("bar", req.get_param_value("param2"));
  7472. });
  7473. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7474. EXPECT_EQ("user-id", req.path_params.at("id"));
  7475. EXPECT_EQ("foo", req.get_param_value("param1"));
  7476. EXPECT_EQ("bar", req.get_param_value("param2"));
  7477. });
  7478. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, 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. {
  7486. Client cli(HOST, PORT);
  7487. Params params;
  7488. params.emplace("hello", "world");
  7489. params.emplace("hello2", "world2");
  7490. params.emplace("hello3", "world3");
  7491. auto res = cli.Get("/", params, Headers{});
  7492. ASSERT_TRUE(res);
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. }
  7495. {
  7496. Client cli(HOST, PORT);
  7497. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7498. ASSERT_TRUE(res);
  7499. EXPECT_EQ(StatusCode::OK_200, res->status);
  7500. }
  7501. {
  7502. Client cli(HOST, PORT);
  7503. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7504. ASSERT_TRUE(res);
  7505. EXPECT_EQ(StatusCode::OK_200, res->status);
  7506. }
  7507. {
  7508. Client cli(HOST, PORT);
  7509. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7510. ASSERT_TRUE(res);
  7511. EXPECT_EQ(StatusCode::OK_200, res->status);
  7512. }
  7513. }
  7514. TEST(GetWithParametersTest, GetWithParameters2) {
  7515. Server svr;
  7516. svr.Get("/", [&](const Request &req, Response &res) {
  7517. auto text = req.get_param_value("hello");
  7518. res.set_content(text, "text/plain");
  7519. });
  7520. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7521. auto se = detail::scope_exit([&] {
  7522. svr.stop();
  7523. listen_thread.join();
  7524. ASSERT_FALSE(svr.is_running());
  7525. });
  7526. svr.wait_until_ready();
  7527. Client cli("localhost", PORT);
  7528. Params params;
  7529. params.emplace("hello", "world");
  7530. std::string body;
  7531. auto res = cli.Get("/", params, Headers{},
  7532. [&](const char *data, size_t data_length) {
  7533. body.append(data, data_length);
  7534. return true;
  7535. });
  7536. ASSERT_TRUE(res);
  7537. EXPECT_EQ(StatusCode::OK_200, res->status);
  7538. EXPECT_EQ("world", body);
  7539. }
  7540. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7541. auto host = "httpbingo.org";
  7542. auto path = std::string{"/range/32"};
  7543. #ifdef CPPHTTPLIB_SSL_ENABLED
  7544. SSLClient cli(host);
  7545. #else
  7546. Client cli(host);
  7547. #endif
  7548. cli.set_default_headers({make_range_header({{1, 10}})});
  7549. cli.set_connection_timeout(5);
  7550. {
  7551. auto res = cli.Get(path);
  7552. ASSERT_TRUE(res);
  7553. EXPECT_EQ("bcdefghijk", res->body);
  7554. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7555. }
  7556. {
  7557. auto res = cli.Get(path);
  7558. ASSERT_TRUE(res);
  7559. EXPECT_EQ("bcdefghijk", res->body);
  7560. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7561. }
  7562. }
  7563. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7564. Server svr;
  7565. svr.set_default_headers({{"Hello", "World"}});
  7566. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7567. res.set_content("ok", "text/plain");
  7568. });
  7569. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7570. auto se = detail::scope_exit([&] {
  7571. svr.stop();
  7572. listen_thread.join();
  7573. ASSERT_FALSE(svr.is_running());
  7574. });
  7575. svr.wait_until_ready();
  7576. Client cli("localhost", PORT);
  7577. auto res = cli.Get("/");
  7578. ASSERT_TRUE(res);
  7579. EXPECT_EQ(StatusCode::OK_200, res->status);
  7580. EXPECT_EQ("ok", res->body);
  7581. EXPECT_EQ("World", res->get_header_value("Hello"));
  7582. }
  7583. #ifdef CPPHTTPLIB_SSL_ENABLED
  7584. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7585. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7586. ASSERT_TRUE(svr.is_valid());
  7587. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7588. std::this_thread::sleep_for(std::chrono::seconds(2));
  7589. res.set_content("a", "text/plain");
  7590. });
  7591. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7592. res.set_content("b", "text/plain");
  7593. });
  7594. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7595. auto se = detail::scope_exit([&] {
  7596. svr.stop();
  7597. listen_thread.join();
  7598. ASSERT_FALSE(svr.is_running());
  7599. });
  7600. svr.wait_until_ready();
  7601. SSLClient cli("localhost", PORT);
  7602. cli.enable_server_certificate_verification(false);
  7603. cli.set_keep_alive(true);
  7604. cli.set_read_timeout(std::chrono::seconds(1));
  7605. auto resa = cli.Get("/a");
  7606. ASSERT_TRUE(!resa);
  7607. EXPECT_EQ(Error::Read, resa.error());
  7608. auto resb = cli.Get("/b");
  7609. ASSERT_TRUE(resb);
  7610. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7611. EXPECT_EQ("b", resb->body);
  7612. }
  7613. #endif
  7614. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7615. protected:
  7616. ServerTestWithAI_PASSIVE()
  7617. : cli_(HOST, PORT)
  7618. #ifdef CPPHTTPLIB_SSL_ENABLED
  7619. ,
  7620. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7621. #endif
  7622. {
  7623. #ifdef CPPHTTPLIB_SSL_ENABLED
  7624. cli_.enable_server_certificate_verification(false);
  7625. #endif
  7626. }
  7627. virtual void SetUp() {
  7628. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7629. res.set_content("Hello World!", "text/plain");
  7630. });
  7631. t_ = thread(
  7632. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7633. svr_.wait_until_ready();
  7634. }
  7635. virtual void TearDown() {
  7636. svr_.stop();
  7637. t_.join();
  7638. }
  7639. #ifdef CPPHTTPLIB_SSL_ENABLED
  7640. SSLClient cli_;
  7641. SSLServer svr_;
  7642. #else
  7643. Client cli_;
  7644. Server svr_;
  7645. #endif
  7646. thread t_;
  7647. };
  7648. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7649. auto res = cli_.Get("/hi");
  7650. ASSERT_TRUE(res);
  7651. EXPECT_EQ(StatusCode::OK_200, res->status);
  7652. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7653. EXPECT_EQ("Hello World!", res->body);
  7654. }
  7655. class ServerUpDownTest : public ::testing::Test {
  7656. protected:
  7657. ServerUpDownTest() : cli_(HOST, PORT) {}
  7658. virtual void SetUp() {
  7659. t_ = thread([&]() {
  7660. svr_.bind_to_any_port(HOST);
  7661. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7662. ASSERT_TRUE(svr_.listen_after_bind());
  7663. });
  7664. svr_.wait_until_ready();
  7665. }
  7666. virtual void TearDown() {
  7667. svr_.stop();
  7668. t_.join();
  7669. }
  7670. Client cli_;
  7671. Server svr_;
  7672. thread t_;
  7673. };
  7674. TEST_F(ServerUpDownTest, QuickStartStop) {
  7675. // Should not crash, especially when run with
  7676. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7677. }
  7678. class PayloadMaxLengthTest : public ::testing::Test {
  7679. protected:
  7680. PayloadMaxLengthTest()
  7681. : cli_(HOST, PORT)
  7682. #ifdef CPPHTTPLIB_SSL_ENABLED
  7683. ,
  7684. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7685. #endif
  7686. {
  7687. #ifdef CPPHTTPLIB_SSL_ENABLED
  7688. cli_.enable_server_certificate_verification(false);
  7689. #endif
  7690. }
  7691. virtual void SetUp() {
  7692. svr_.set_payload_max_length(8);
  7693. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7694. res.set_content("test", "text/plain");
  7695. });
  7696. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7697. svr_.wait_until_ready();
  7698. }
  7699. virtual void TearDown() {
  7700. svr_.stop();
  7701. t_.join();
  7702. }
  7703. #ifdef CPPHTTPLIB_SSL_ENABLED
  7704. SSLClient cli_;
  7705. SSLServer svr_;
  7706. #else
  7707. Client cli_;
  7708. Server svr_;
  7709. #endif
  7710. thread t_;
  7711. };
  7712. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7713. auto res = cli_.Post("/test", "123456789", "text/plain");
  7714. ASSERT_TRUE(res);
  7715. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7716. res = cli_.Post("/test", "12345678", "text/plain");
  7717. ASSERT_TRUE(res);
  7718. EXPECT_EQ(StatusCode::OK_200, res->status);
  7719. }
  7720. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7721. // Test chunked encoding with payload exceeding the 8-byte limit
  7722. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7723. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7724. ASSERT_TRUE(res);
  7725. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7726. }
  7727. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7728. // Test chunked encoding with payload within the 8-byte limit
  7729. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7730. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7731. ASSERT_TRUE(res);
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. }
  7734. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7735. // Test using send_request to send chunked data exceeding payload limit
  7736. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7737. "Host: " +
  7738. std::string(HOST) + ":" + std::to_string(PORT) +
  7739. "\r\n"
  7740. "Transfer-Encoding: chunked\r\n"
  7741. "Connection: close\r\n"
  7742. "\r\n"
  7743. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7744. "0123456789\r\n"
  7745. "0\r\n" // End chunk
  7746. "\r\n";
  7747. std::string response;
  7748. bool result = send_request(1, chunked_request, &response);
  7749. if (!result) {
  7750. // If send_request fails, it might be because the server closed the
  7751. // connection due to payload limit enforcement, which is acceptable
  7752. SUCCEED()
  7753. << "Server rejected oversized chunked request (connection closed)";
  7754. } else {
  7755. // If we got a response, check if it's an error response or connection was
  7756. // closed early Short response length indicates connection was closed due to
  7757. // payload limit
  7758. if (response.length() <= 10) {
  7759. SUCCEED() << "Server closed connection for oversized chunked request";
  7760. } else {
  7761. // Check for error status codes
  7762. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7763. response.find("Payload Too Large") != std::string::npos ||
  7764. response.find("400") != std::string::npos);
  7765. }
  7766. }
  7767. }
  7768. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7769. // Test request without Content-Length header exceeding payload limit
  7770. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7771. "Host: " +
  7772. std::string(HOST) + ":" +
  7773. std::to_string(PORT) +
  7774. "\r\n"
  7775. "Connection: close\r\n"
  7776. "\r\n";
  7777. // Add payload exceeding the 8-byte limit
  7778. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7779. request_without_content_length += large_payload;
  7780. std::string response;
  7781. bool result = send_request(1, request_without_content_length, &response);
  7782. if (!result) {
  7783. // If send_request fails, server likely closed connection due to payload
  7784. // limit
  7785. SUCCEED() << "Server rejected oversized request without Content-Length "
  7786. "(connection closed)";
  7787. } else {
  7788. // Check if server responded with error or closed connection early
  7789. if (response.length() <= 10) {
  7790. SUCCEED() << "Server closed connection for oversized request without "
  7791. "Content-Length";
  7792. } else {
  7793. // Check for error status codes
  7794. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7795. response.find("Payload Too Large") != std::string::npos ||
  7796. response.find("400") != std::string::npos);
  7797. }
  7798. }
  7799. }
  7800. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7801. // Test request without Content-Length header within payload 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 payload within the 8-byte limit
  7810. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7811. request_without_content_length += small_payload;
  7812. std::string response;
  7813. bool result = send_request(1, request_without_content_length, &response);
  7814. // For requests without Content-Length, the server may have different behavior
  7815. // The key is that it should not reject due to payload limit for small
  7816. // payloads
  7817. if (result) {
  7818. // Check for any HTTP response (success or error, but not connection closed)
  7819. if (response.length() > 10) {
  7820. SUCCEED()
  7821. << "Server processed request without Content-Length within limit";
  7822. } else {
  7823. // Short response might indicate connection closed, which is acceptable
  7824. SUCCEED() << "Server closed connection for request without "
  7825. "Content-Length (acceptable behavior)";
  7826. }
  7827. } else {
  7828. // Connection failure might be due to protocol requirements
  7829. SUCCEED() << "Connection issue with request without Content-Length "
  7830. "(environment-specific)";
  7831. }
  7832. }
  7833. class LargePayloadMaxLengthTest : public ::testing::Test {
  7834. protected:
  7835. LargePayloadMaxLengthTest()
  7836. : cli_(HOST, PORT)
  7837. #ifdef CPPHTTPLIB_SSL_ENABLED
  7838. ,
  7839. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7840. #endif
  7841. {
  7842. #ifdef CPPHTTPLIB_SSL_ENABLED
  7843. cli_.enable_server_certificate_verification(false);
  7844. #endif
  7845. }
  7846. virtual void SetUp() {
  7847. // Set 10MB payload limit
  7848. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7849. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7850. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7851. res.set_content("Large payload test", "text/plain");
  7852. });
  7853. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7854. svr_.wait_until_ready();
  7855. }
  7856. virtual void TearDown() {
  7857. svr_.stop();
  7858. t_.join();
  7859. }
  7860. #ifdef CPPHTTPLIB_SSL_ENABLED
  7861. SSLClient cli_;
  7862. SSLServer svr_;
  7863. #else
  7864. Client cli_;
  7865. Server svr_;
  7866. #endif
  7867. thread t_;
  7868. };
  7869. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7870. // Test chunked encoding with payload within 10MB limit
  7871. std::string medium_payload(5 * 1024 * 1024,
  7872. 'A'); // 5MB payload, within 10MB limit
  7873. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7874. ASSERT_TRUE(res);
  7875. EXPECT_EQ(StatusCode::OK_200, res->status);
  7876. }
  7877. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7878. // Test chunked encoding with payload exceeding 10MB limit
  7879. std::string large_payload(12 * 1024 * 1024,
  7880. 'B'); // 12MB payload, exceeds 10MB limit
  7881. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7882. // Server may either return 413 or close the connection
  7883. if (res) {
  7884. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7885. } else {
  7886. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7887. }
  7888. }
  7889. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7890. // Test request without Content-Length header within 10MB limit
  7891. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7892. "Host: " +
  7893. std::string(HOST) + ":" +
  7894. std::to_string(PORT) +
  7895. "\r\n"
  7896. "Connection: close\r\n"
  7897. "\r\n";
  7898. // Add 1MB payload (within 10MB limit)
  7899. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7900. request_without_content_length += medium_payload;
  7901. std::string response;
  7902. bool result = send_request(5, request_without_content_length, &response);
  7903. if (result) {
  7904. // Should get a proper HTTP response for payloads within limit
  7905. if (response.length() > 10) {
  7906. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7907. "10MB limit";
  7908. } else {
  7909. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7910. "Content-Length)";
  7911. }
  7912. } else {
  7913. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7914. }
  7915. }
  7916. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7917. // Test request without Content-Length header exceeding 10MB limit
  7918. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7919. "Host: " +
  7920. std::string(HOST) + ":" +
  7921. std::to_string(PORT) +
  7922. "\r\n"
  7923. "Connection: close\r\n"
  7924. "\r\n";
  7925. // Add 12MB payload (exceeds 10MB limit)
  7926. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7927. request_without_content_length += large_payload;
  7928. std::string response;
  7929. bool result = send_request(10, request_without_content_length, &response);
  7930. if (!result) {
  7931. // Server should close connection due to payload limit
  7932. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7933. "(connection closed)";
  7934. } else {
  7935. // Check for error response
  7936. if (response.length() <= 10) {
  7937. SUCCEED()
  7938. << "Server closed connection for 12MB request exceeding 10MB limit";
  7939. } else {
  7940. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7941. response.find("Payload Too Large") != std::string::npos ||
  7942. response.find("400") != std::string::npos);
  7943. }
  7944. }
  7945. }
  7946. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7947. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7948. // path.
  7949. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7950. Server svr;
  7951. const size_t LIMIT = 64 * 1024; // 64KB
  7952. svr.set_payload_max_length(LIMIT);
  7953. size_t total = 0;
  7954. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7955. const ContentReader &content_reader) {
  7956. content_reader([&](const char * /*data*/, size_t len) {
  7957. total += len;
  7958. return true;
  7959. });
  7960. res.status = 200;
  7961. res.set_content("stream_ok", "text/plain");
  7962. });
  7963. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7964. auto se = detail::scope_exit([&] {
  7965. svr.stop();
  7966. thread.join();
  7967. ASSERT_FALSE(svr.is_running());
  7968. });
  7969. svr.wait_until_ready();
  7970. // Prepare 256KB raw data and gzip-compress it
  7971. std::string raw(256 * 1024, 'A');
  7972. std::string gz;
  7973. {
  7974. z_stream zs{};
  7975. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7976. Z_DEFAULT_STRATEGY);
  7977. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7978. zs.avail_in = static_cast<uInt>(raw.size());
  7979. char outbuf[4096];
  7980. int ret;
  7981. do {
  7982. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7983. zs.avail_out = sizeof(outbuf);
  7984. ret = deflate(&zs, Z_FINISH);
  7985. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7986. } while (ret != Z_STREAM_END);
  7987. deflateEnd(&zs);
  7988. }
  7989. Client cli(HOST, PORT);
  7990. cli.set_connection_timeout(std::chrono::seconds(5));
  7991. Headers headers = {{"Content-Encoding", "gzip"}};
  7992. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7993. "application/octet-stream");
  7994. ASSERT_TRUE(res);
  7995. // Server must reject oversized decompressed payloads with 413.
  7996. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7997. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7998. EXPECT_LE(total, LIMIT);
  7999. }
  8000. #endif
  8001. // Regression test for DoS vulnerability: a malicious server sending a response
  8002. // without Content-Length header must not cause unbounded memory consumption on
  8003. // the client side. The client should stop reading after a reasonable limit,
  8004. // similar to the server-side set_payload_max_length protection.
  8005. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8006. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8007. #ifndef _WIN32
  8008. signal(SIGPIPE, SIG_IGN);
  8009. #endif
  8010. auto server_thread = std::thread([] {
  8011. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8012. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8013. default_socket_options(srv);
  8014. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8015. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8016. sockaddr_in addr{};
  8017. addr.sin_family = AF_INET;
  8018. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8019. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8020. int opt = 1;
  8021. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8022. #ifdef _WIN32
  8023. reinterpret_cast<const char *>(&opt),
  8024. #else
  8025. &opt,
  8026. #endif
  8027. sizeof(opt));
  8028. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8029. ::listen(srv, 1);
  8030. sockaddr_in cli_addr{};
  8031. socklen_t cli_len = sizeof(cli_addr);
  8032. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8033. if (cli != INVALID_SOCKET) {
  8034. char buf[4096];
  8035. ::recv(cli, buf, sizeof(buf), 0);
  8036. // Malicious response: no Content-Length, no chunked encoding
  8037. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8038. "Connection: close\r\n"
  8039. "\r\n";
  8040. ::send(cli,
  8041. #ifdef _WIN32
  8042. static_cast<const char *>(response_header.c_str()),
  8043. static_cast<int>(response_header.size()),
  8044. #else
  8045. response_header.c_str(), response_header.size(),
  8046. #endif
  8047. 0);
  8048. // Send 10MB of data
  8049. std::string chunk(64 * 1024, 'A');
  8050. size_t total_sent = 0;
  8051. while (total_sent < MALICIOUS_DATA_SIZE) {
  8052. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8053. auto sent = ::send(cli,
  8054. #ifdef _WIN32
  8055. static_cast<const char *>(chunk.c_str()),
  8056. static_cast<int>(to_send),
  8057. #else
  8058. chunk.c_str(), to_send,
  8059. #endif
  8060. 0);
  8061. if (sent <= 0) break;
  8062. total_sent += static_cast<size_t>(sent);
  8063. }
  8064. detail::close_socket(cli);
  8065. }
  8066. detail::close_socket(srv);
  8067. });
  8068. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8069. size_t total_read = 0;
  8070. {
  8071. Client cli("127.0.0.1", PORT + 2);
  8072. cli.set_read_timeout(5, 0);
  8073. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8074. auto stream = cli.open_stream("GET", "/malicious");
  8075. ASSERT_TRUE(stream.is_valid());
  8076. char buffer[64 * 1024];
  8077. ssize_t n;
  8078. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8079. total_read += static_cast<size_t>(n);
  8080. }
  8081. } // StreamHandle and Client destroyed here, closing the socket
  8082. server_thread.join();
  8083. // With set_payload_max_length, the client must stop reading before consuming
  8084. // all 10MB. The read loop should be cut off at or near the configured limit.
  8085. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8086. << "Client read " << total_read << " bytes, exceeding the configured "
  8087. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8088. }
  8089. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8090. // the entire response body without truncation.
  8091. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8092. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8093. #ifndef _WIN32
  8094. signal(SIGPIPE, SIG_IGN);
  8095. #endif
  8096. auto server_thread = std::thread([] {
  8097. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8098. default_socket_options(srv);
  8099. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8100. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8101. sockaddr_in addr{};
  8102. addr.sin_family = AF_INET;
  8103. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8104. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8105. int opt = 1;
  8106. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8107. #ifdef _WIN32
  8108. reinterpret_cast<const char *>(&opt),
  8109. #else
  8110. &opt,
  8111. #endif
  8112. sizeof(opt));
  8113. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8114. ::listen(srv, 1);
  8115. sockaddr_in cli_addr{};
  8116. socklen_t cli_len = sizeof(cli_addr);
  8117. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8118. if (cli != INVALID_SOCKET) {
  8119. char buf[4096];
  8120. ::recv(cli, buf, sizeof(buf), 0);
  8121. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8122. "Connection: close\r\n"
  8123. "\r\n";
  8124. ::send(cli,
  8125. #ifdef _WIN32
  8126. static_cast<const char *>(response_header.c_str()),
  8127. static_cast<int>(response_header.size()),
  8128. #else
  8129. response_header.c_str(), response_header.size(),
  8130. #endif
  8131. 0);
  8132. std::string chunk(64 * 1024, 'A');
  8133. size_t total_sent = 0;
  8134. while (total_sent < DATA_SIZE) {
  8135. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8136. auto sent = ::send(cli,
  8137. #ifdef _WIN32
  8138. static_cast<const char *>(chunk.c_str()),
  8139. static_cast<int>(to_send),
  8140. #else
  8141. chunk.c_str(), to_send,
  8142. #endif
  8143. 0);
  8144. if (sent <= 0) break;
  8145. total_sent += static_cast<size_t>(sent);
  8146. }
  8147. #ifdef _WIN32
  8148. ::shutdown(cli, SD_SEND);
  8149. #else
  8150. ::shutdown(cli, SHUT_WR);
  8151. #endif
  8152. // Drain until the client closes its end, ensuring all data is delivered
  8153. char drain[1024];
  8154. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8155. detail::close_socket(cli);
  8156. }
  8157. detail::close_socket(srv);
  8158. });
  8159. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8160. size_t total_read = 0;
  8161. {
  8162. Client cli("127.0.0.1", PORT + 2);
  8163. cli.set_read_timeout(5, 0);
  8164. cli.set_payload_max_length(0); // 0 means no limit
  8165. auto stream = cli.open_stream("GET", "/data");
  8166. ASSERT_TRUE(stream.is_valid());
  8167. char buffer[64 * 1024];
  8168. ssize_t n;
  8169. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8170. total_read += static_cast<size_t>(n);
  8171. }
  8172. }
  8173. server_thread.join();
  8174. EXPECT_EQ(total_read, DATA_SIZE)
  8175. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8176. << " bytes without truncation, but only read " << total_read << " bytes.";
  8177. }
  8178. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8179. // enormous Content-Length must not cause the client to pre-allocate a huge
  8180. // response body buffer. The reservation is capped at payload_max_length_, and
  8181. // the read itself fails when the body exceeds the limit.
  8182. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8183. #ifndef _WIN32
  8184. signal(SIGPIPE, SIG_IGN);
  8185. #endif
  8186. auto server_thread = std::thread([] {
  8187. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8188. default_socket_options(srv);
  8189. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8190. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8191. sockaddr_in addr{};
  8192. addr.sin_family = AF_INET;
  8193. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8194. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8195. int opt = 1;
  8196. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8197. #ifdef _WIN32
  8198. reinterpret_cast<const char *>(&opt),
  8199. #else
  8200. &opt,
  8201. #endif
  8202. sizeof(opt));
  8203. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8204. ::listen(srv, 1);
  8205. sockaddr_in cli_addr{};
  8206. socklen_t cli_len = sizeof(cli_addr);
  8207. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8208. if (cli != INVALID_SOCKET) {
  8209. char buf[4096];
  8210. ::recv(cli, buf, sizeof(buf), 0);
  8211. // Malicious response: claim a 20GB body but send only a tiny payload.
  8212. std::string response = "HTTP/1.1 200 OK\r\n"
  8213. "Content-Length: 20000000000\r\n"
  8214. "\r\n"
  8215. "abc";
  8216. ::send(cli,
  8217. #ifdef _WIN32
  8218. static_cast<const char *>(response.c_str()),
  8219. static_cast<int>(response.size()),
  8220. #else
  8221. response.c_str(), response.size(),
  8222. #endif
  8223. 0);
  8224. detail::close_socket(cli);
  8225. }
  8226. detail::close_socket(srv);
  8227. });
  8228. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8229. {
  8230. Client cli("127.0.0.1", PORT + 2);
  8231. cli.set_read_timeout(5, 0);
  8232. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8233. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8234. // (server claims more bytes than payload_max_length permits), but it must
  8235. // not exhaust memory before getting there.
  8236. auto res = cli.Get("/malicious");
  8237. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8238. }
  8239. server_thread.join();
  8240. }
  8241. // Verify that content_receiver bypasses the default payload_max_length,
  8242. // allowing streaming downloads larger than 100MB without requiring an explicit
  8243. // set_payload_max_length call.
  8244. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8245. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8246. #ifndef _WIN32
  8247. signal(SIGPIPE, SIG_IGN);
  8248. #endif
  8249. auto server_thread = std::thread([] {
  8250. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8251. default_socket_options(srv);
  8252. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8253. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8254. sockaddr_in addr{};
  8255. addr.sin_family = AF_INET;
  8256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8257. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8258. int opt = 1;
  8259. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8260. #ifdef _WIN32
  8261. reinterpret_cast<const char *>(&opt),
  8262. #else
  8263. &opt,
  8264. #endif
  8265. sizeof(opt));
  8266. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8267. ::listen(srv, 1);
  8268. sockaddr_in cli_addr{};
  8269. socklen_t cli_len = sizeof(cli_addr);
  8270. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8271. if (cli != INVALID_SOCKET) {
  8272. char buf[4096];
  8273. ::recv(cli, buf, sizeof(buf), 0);
  8274. // Response with Content-Length larger than default 100MB limit
  8275. auto content_length = std::to_string(DATA_SIZE);
  8276. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8277. "Content-Length: " +
  8278. content_length +
  8279. "\r\n"
  8280. "Connection: close\r\n"
  8281. "\r\n";
  8282. ::send(cli,
  8283. #ifdef _WIN32
  8284. static_cast<const char *>(response_header.c_str()),
  8285. static_cast<int>(response_header.size()),
  8286. #else
  8287. response_header.c_str(), response_header.size(),
  8288. #endif
  8289. 0);
  8290. std::string chunk(64 * 1024, 'A');
  8291. size_t total_sent = 0;
  8292. while (total_sent < DATA_SIZE) {
  8293. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8294. auto sent = ::send(cli,
  8295. #ifdef _WIN32
  8296. static_cast<const char *>(chunk.c_str()),
  8297. static_cast<int>(to_send),
  8298. #else
  8299. chunk.c_str(), to_send,
  8300. #endif
  8301. 0);
  8302. if (sent <= 0) break;
  8303. total_sent += static_cast<size_t>(sent);
  8304. }
  8305. detail::close_socket(cli);
  8306. }
  8307. detail::close_socket(srv);
  8308. });
  8309. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8310. size_t total_received = 0;
  8311. {
  8312. Client cli("127.0.0.1", PORT + 2);
  8313. cli.set_read_timeout(10, 0);
  8314. // Do NOT call set_payload_max_length — use the default 100MB limit
  8315. auto res =
  8316. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8317. total_received += data_length;
  8318. return true;
  8319. });
  8320. ASSERT_TRUE(res);
  8321. EXPECT_EQ(StatusCode::OK_200, res->status);
  8322. }
  8323. server_thread.join();
  8324. EXPECT_EQ(total_received, DATA_SIZE)
  8325. << "With content_receiver, the client should read all " << DATA_SIZE
  8326. << " bytes despite the default 100MB payload_max_length, but only read "
  8327. << total_received << " bytes.";
  8328. }
  8329. // Verify that an explicit set_payload_max_length smaller than the response is
  8330. // enforced even when a content_receiver is used.
  8331. TEST(ClientVulnerabilityTest,
  8332. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8333. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8334. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8335. #ifndef _WIN32
  8336. signal(SIGPIPE, SIG_IGN);
  8337. #endif
  8338. auto server_thread = std::thread([] {
  8339. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8340. default_socket_options(srv);
  8341. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8342. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8343. sockaddr_in addr{};
  8344. addr.sin_family = AF_INET;
  8345. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8346. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8347. int opt = 1;
  8348. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8349. #ifdef _WIN32
  8350. reinterpret_cast<const char *>(&opt),
  8351. #else
  8352. &opt,
  8353. #endif
  8354. sizeof(opt));
  8355. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8356. ::listen(srv, 1);
  8357. sockaddr_in cli_addr{};
  8358. socklen_t cli_len = sizeof(cli_addr);
  8359. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8360. if (cli != INVALID_SOCKET) {
  8361. char buf[4096];
  8362. ::recv(cli, buf, sizeof(buf), 0);
  8363. auto content_length = std::to_string(DATA_SIZE);
  8364. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8365. "Content-Length: " +
  8366. content_length +
  8367. "\r\n"
  8368. "Connection: close\r\n"
  8369. "\r\n";
  8370. ::send(cli,
  8371. #ifdef _WIN32
  8372. static_cast<const char *>(response_header.c_str()),
  8373. static_cast<int>(response_header.size()),
  8374. #else
  8375. response_header.c_str(), response_header.size(),
  8376. #endif
  8377. 0);
  8378. std::string chunk(64 * 1024, 'A');
  8379. size_t total_sent = 0;
  8380. while (total_sent < DATA_SIZE) {
  8381. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8382. auto sent = ::send(cli,
  8383. #ifdef _WIN32
  8384. static_cast<const char *>(chunk.c_str()),
  8385. static_cast<int>(to_send),
  8386. #else
  8387. chunk.c_str(), to_send,
  8388. #endif
  8389. 0);
  8390. if (sent <= 0) break;
  8391. total_sent += static_cast<size_t>(sent);
  8392. }
  8393. detail::close_socket(cli);
  8394. }
  8395. detail::close_socket(srv);
  8396. });
  8397. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8398. size_t total_received = 0;
  8399. {
  8400. Client cli("127.0.0.1", PORT + 2);
  8401. cli.set_read_timeout(10, 0);
  8402. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8403. auto res =
  8404. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8405. total_received += data_length;
  8406. return true;
  8407. });
  8408. // Should fail because 200MB exceeds the explicit 150MB limit
  8409. EXPECT_FALSE(res);
  8410. }
  8411. server_thread.join();
  8412. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8413. << "Client with content_receiver should respect the explicit "
  8414. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8415. << total_received << " bytes.";
  8416. }
  8417. // Verify that an explicit set_payload_max_length larger than the response
  8418. // allows the content_receiver to read all data successfully.
  8419. TEST(ClientVulnerabilityTest,
  8420. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8421. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8422. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8423. #ifndef _WIN32
  8424. signal(SIGPIPE, SIG_IGN);
  8425. #endif
  8426. auto server_thread = std::thread([] {
  8427. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8428. default_socket_options(srv);
  8429. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8430. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8431. sockaddr_in addr{};
  8432. addr.sin_family = AF_INET;
  8433. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8434. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8435. int opt = 1;
  8436. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8437. #ifdef _WIN32
  8438. reinterpret_cast<const char *>(&opt),
  8439. #else
  8440. &opt,
  8441. #endif
  8442. sizeof(opt));
  8443. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8444. ::listen(srv, 1);
  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. char buf[4096];
  8450. ::recv(cli, buf, sizeof(buf), 0);
  8451. auto content_length = std::to_string(DATA_SIZE);
  8452. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8453. "Content-Length: " +
  8454. content_length +
  8455. "\r\n"
  8456. "Connection: close\r\n"
  8457. "\r\n";
  8458. ::send(cli,
  8459. #ifdef _WIN32
  8460. static_cast<const char *>(response_header.c_str()),
  8461. static_cast<int>(response_header.size()),
  8462. #else
  8463. response_header.c_str(), response_header.size(),
  8464. #endif
  8465. 0);
  8466. std::string chunk(64 * 1024, 'A');
  8467. size_t total_sent = 0;
  8468. while (total_sent < DATA_SIZE) {
  8469. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8470. auto sent = ::send(cli,
  8471. #ifdef _WIN32
  8472. static_cast<const char *>(chunk.c_str()),
  8473. static_cast<int>(to_send),
  8474. #else
  8475. chunk.c_str(), to_send,
  8476. #endif
  8477. 0);
  8478. if (sent <= 0) break;
  8479. total_sent += static_cast<size_t>(sent);
  8480. }
  8481. #ifdef _WIN32
  8482. ::shutdown(cli, SD_SEND);
  8483. #else
  8484. ::shutdown(cli, SHUT_WR);
  8485. #endif
  8486. char drain[1024];
  8487. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8488. detail::close_socket(cli);
  8489. }
  8490. detail::close_socket(srv);
  8491. });
  8492. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8493. size_t total_received = 0;
  8494. {
  8495. Client cli("127.0.0.1", PORT + 2);
  8496. cli.set_read_timeout(10, 0);
  8497. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8498. auto res =
  8499. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8500. total_received += data_length;
  8501. return true;
  8502. });
  8503. ASSERT_TRUE(res);
  8504. EXPECT_EQ(StatusCode::OK_200, res->status);
  8505. }
  8506. server_thread.join();
  8507. EXPECT_EQ(total_received, DATA_SIZE)
  8508. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8509. << " bytes (larger than " << DATA_SIZE
  8510. << " bytes response), content_receiver should read all data, but only "
  8511. "read "
  8512. << total_received << " bytes.";
  8513. }
  8514. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8515. // Regression test for "zip bomb" attack on the client side: a malicious server
  8516. // sends a small gzip-compressed response that decompresses to a huge payload.
  8517. // The client must enforce payload_max_length on the decompressed size.
  8518. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8519. constexpr size_t DECOMPRESSED_SIZE =
  8520. 10 * 1024 * 1024; // 10MB after decompression
  8521. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8522. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8523. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8524. std::string compressed;
  8525. {
  8526. httplib::detail::gzip_compressor compressor;
  8527. bool ok =
  8528. compressor.compress(uncompressed.data(), uncompressed.size(),
  8529. /*last=*/true, [&](const char *buf, size_t len) {
  8530. compressed.append(buf, len);
  8531. return true;
  8532. });
  8533. ASSERT_TRUE(ok);
  8534. }
  8535. // Sanity: compressed data should be much smaller than the decompressed size
  8536. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8537. #ifndef _WIN32
  8538. signal(SIGPIPE, SIG_IGN);
  8539. #endif
  8540. // Set up the listening socket in the main thread so the server is guaranteed
  8541. // to be ready before the client connects (eliminates race condition).
  8542. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8543. default_socket_options(srv);
  8544. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8545. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8546. sockaddr_in addr{};
  8547. addr.sin_family = AF_INET;
  8548. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8549. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8550. int opt = 1;
  8551. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8552. #ifdef _WIN32
  8553. reinterpret_cast<const char *>(&opt),
  8554. #else
  8555. &opt,
  8556. #endif
  8557. sizeof(opt));
  8558. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8559. ASSERT_EQ(0, ::listen(srv, 1));
  8560. auto server_thread = std::thread([&compressed, srv] {
  8561. sockaddr_in cli_addr{};
  8562. socklen_t cli_len = sizeof(cli_addr);
  8563. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8564. if (cli != INVALID_SOCKET) {
  8565. // Read the full HTTP request (until \r\n\r\n)
  8566. char buf[4096];
  8567. size_t total = 0;
  8568. while (total < sizeof(buf)) {
  8569. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8570. if (n <= 0) break;
  8571. total += static_cast<size_t>(n);
  8572. // Check for end of headers
  8573. if (total >= 4) {
  8574. std::string req(buf, total);
  8575. if (req.find("\r\n\r\n") != std::string::npos) break;
  8576. }
  8577. }
  8578. // Malicious response: gzip-compressed body, no Content-Length
  8579. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8580. "Content-Encoding: gzip\r\n"
  8581. "Connection: close\r\n"
  8582. "\r\n";
  8583. ::send(cli,
  8584. #ifdef _WIN32
  8585. static_cast<const char *>(response_header.c_str()),
  8586. static_cast<int>(response_header.size()),
  8587. #else
  8588. response_header.c_str(), response_header.size(),
  8589. #endif
  8590. 0);
  8591. // Send the compressed payload (small on the wire, huge when decompressed)
  8592. size_t total_sent = 0;
  8593. while (total_sent < compressed.size()) {
  8594. auto to_send = std::min(compressed.size() - total_sent,
  8595. static_cast<size_t>(64 * 1024));
  8596. auto sent =
  8597. ::send(cli,
  8598. #ifdef _WIN32
  8599. static_cast<const char *>(compressed.c_str() + total_sent),
  8600. static_cast<int>(to_send),
  8601. #else
  8602. compressed.c_str() + total_sent, to_send,
  8603. #endif
  8604. 0);
  8605. if (sent <= 0) break;
  8606. total_sent += static_cast<size_t>(sent);
  8607. }
  8608. detail::close_socket(cli);
  8609. }
  8610. });
  8611. auto se = detail::scope_exit([&] {
  8612. detail::close_socket(srv);
  8613. server_thread.join();
  8614. });
  8615. size_t total_decompressed = 0;
  8616. {
  8617. Client cli("127.0.0.1", PORT + 3);
  8618. cli.set_read_timeout(5, 0);
  8619. cli.set_decompress(true);
  8620. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8621. auto stream = cli.open_stream("GET", "/zipbomb");
  8622. ASSERT_TRUE(stream.is_valid());
  8623. char buffer[64 * 1024];
  8624. ssize_t n;
  8625. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8626. total_decompressed += static_cast<size_t>(n);
  8627. }
  8628. }
  8629. // The decompressed size must be capped by payload_max_length. Without
  8630. // protection, the client would decompress the full 10MB from a tiny
  8631. // compressed payload, enabling a zip bomb DoS attack.
  8632. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8633. << "Client decompressed " << total_decompressed
  8634. << " bytes from a gzip response. The decompressed size should be "
  8635. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8636. }
  8637. #endif
  8638. TEST(HostAndPortPropertiesTest, NoSSL) {
  8639. httplib::Client cli("www.google.com", 1234);
  8640. ASSERT_EQ("www.google.com", cli.host());
  8641. ASSERT_EQ(1234, cli.port());
  8642. }
  8643. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8644. httplib::Client cli("www.google.com:1234");
  8645. ASSERT_EQ("www.google.com", cli.host());
  8646. ASSERT_EQ(1234, cli.port());
  8647. }
  8648. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8649. // Port number that overflows int — should not crash, client becomes invalid
  8650. httplib::Client cli("http://www.google.com:99999999999999999999");
  8651. ASSERT_FALSE(cli.is_valid());
  8652. }
  8653. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8654. // Port 99999 exceeds valid range (1-65535) — should not crash
  8655. httplib::Client cli("http://www.google.com:99999");
  8656. ASSERT_FALSE(cli.is_valid());
  8657. }
  8658. #ifdef CPPHTTPLIB_SSL_ENABLED
  8659. TEST(HostAndPortPropertiesTest, SSL) {
  8660. httplib::SSLClient cli("www.google.com");
  8661. ASSERT_EQ("www.google.com", cli.host());
  8662. ASSERT_EQ(443, cli.port());
  8663. }
  8664. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8665. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8666. std::string cert;
  8667. read_file(CA_CERT_FILE, cert);
  8668. httplib::SSLClient httplib_client("www.google.com");
  8669. // Load CA store first time
  8670. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8671. // Load CA store second time (update)
  8672. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8673. // Verify client is still valid and can make connections
  8674. httplib_client.enable_server_certificate_verification(true);
  8675. auto res = httplib_client.Get("/");
  8676. ASSERT_TRUE(res);
  8677. // Google may return 200 or 301 depending on various factors
  8678. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8679. res->status == StatusCode::MovedPermanently_301);
  8680. }
  8681. TEST(SSLClientTest, ServerNameIndication_Online) {
  8682. auto host = "httpbingo.org";
  8683. auto path = std::string{"/get"};
  8684. SSLClient cli(host, 443);
  8685. auto res = cli.Get(path);
  8686. ASSERT_TRUE(res);
  8687. ASSERT_EQ(StatusCode::OK_200, res->status);
  8688. }
  8689. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8690. // Use a site that will cause SSL verification failure due to self-signed cert
  8691. SSLClient cli("self-signed.badssl.com", 443);
  8692. cli.enable_server_certificate_verification(true);
  8693. auto res = cli.Get("/");
  8694. ASSERT_TRUE(!res);
  8695. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8696. // Verify backend error is captured for SSLServerVerification
  8697. // This occurs when certificate verification fails
  8698. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8699. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8700. EXPECT_NE(0UL, res.ssl_backend_error());
  8701. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8702. // For OpenSSL, ssl_error is 0 for verification errors
  8703. EXPECT_EQ(0, res.ssl_error());
  8704. #if !defined(_WIN32) || \
  8705. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8706. // On non-Windows or when Windows Schannel is disabled, the error comes
  8707. // from OpenSSL's verification
  8708. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8709. res.ssl_backend_error());
  8710. #endif
  8711. #endif
  8712. }
  8713. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8714. // Use a site where hostname doesn't match the certificate
  8715. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8716. SSLClient cli("wrong.host.badssl.com", 443);
  8717. cli.enable_server_certificate_verification(true);
  8718. cli.enable_server_hostname_verification(true);
  8719. auto res = cli.Get("/");
  8720. ASSERT_TRUE(!res);
  8721. // The error type depends on when hostname verification occurs:
  8722. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8723. // - Mbed TLS: SSLServerVerification (during handshake)
  8724. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8725. res.error() == Error::SSLServerVerification);
  8726. // Verify backend error is captured for hostname verification failure
  8727. EXPECT_NE(0UL, res.ssl_backend_error());
  8728. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8729. // For OpenSSL, ssl_error is 0 for verification errors
  8730. EXPECT_EQ(0, res.ssl_error());
  8731. #if !defined(_WIN32) || \
  8732. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8733. // On non-Windows or when Windows Schannel is disabled, the error comes
  8734. // from OpenSSL's hostname verification
  8735. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8736. res.ssl_backend_error());
  8737. #endif
  8738. #endif
  8739. }
  8740. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8741. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8742. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8743. SSLClient cli("www.google.com", 443);
  8744. cli.enable_server_certificate_verification(true);
  8745. auto res = cli.Get("/");
  8746. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8747. }
  8748. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8749. SSLClient cli("www.google.com", 443);
  8750. cli.enable_server_certificate_verification(true);
  8751. cli.enable_windows_certificate_verification(false);
  8752. auto res = cli.Get("/");
  8753. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8754. }
  8755. #endif
  8756. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8757. Client cli("https://google.com");
  8758. auto res = cli.Get("/");
  8759. ASSERT_TRUE(res);
  8760. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8761. }
  8762. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8763. SSLClient cli("google.com");
  8764. cli.set_ca_cert_path(CA_CERT_FILE);
  8765. auto res = cli.Get("/");
  8766. ASSERT_TRUE(res);
  8767. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8768. }
  8769. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8770. SSLClient cli("google.com");
  8771. cli.enable_server_certificate_verification(true);
  8772. cli.set_ca_cert_path("hello");
  8773. auto res = cli.Get("/");
  8774. ASSERT_TRUE(!res);
  8775. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8776. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8777. // should be set
  8778. EXPECT_EQ(0, res.ssl_error());
  8779. // Verify backend error is captured for SSLLoadingCerts
  8780. // This error occurs when loading CA certificates fails
  8781. EXPECT_NE(0UL, res.ssl_backend_error());
  8782. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8783. // OpenSSL specific error codes:
  8784. // > openssl errstr 0x80000002
  8785. // error:80000002:system library::No such file or directory
  8786. // > openssl errstr 0xA000126
  8787. // error:0A000126:SSL routines::unexpected eof while reading
  8788. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8789. res.ssl_backend_error() == 0xA000126);
  8790. #endif
  8791. }
  8792. TEST(SSLClientTest, ServerCertificateVerification4) {
  8793. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8794. ASSERT_TRUE(svr.is_valid());
  8795. svr.Get("/test", [&](const Request &, Response &res) {
  8796. res.set_content("test", "text/plain");
  8797. svr.stop();
  8798. ASSERT_TRUE(true);
  8799. });
  8800. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8801. auto se = detail::scope_exit([&] {
  8802. t.join();
  8803. ASSERT_FALSE(svr.is_running());
  8804. });
  8805. svr.wait_until_ready();
  8806. SSLClient cli("127.0.0.1", PORT);
  8807. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8808. cli.enable_server_certificate_verification(true);
  8809. cli.set_connection_timeout(30);
  8810. auto res = cli.Get("/test");
  8811. ASSERT_TRUE(res);
  8812. ASSERT_EQ(StatusCode::OK_200, res->status);
  8813. }
  8814. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8815. std::string cert;
  8816. read_file(CA_CERT_FILE, cert);
  8817. SSLClient cli("google.com");
  8818. cli.load_ca_cert_store(cert.data(), cert.size());
  8819. const auto res = cli.Get("/");
  8820. ASSERT_TRUE(res);
  8821. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8822. }
  8823. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8824. // clang-format off
  8825. static constexpr char cert[] =
  8826. "GlobalSign Root CA\n"
  8827. "==================\n"
  8828. "-----BEGIN CERTIFICATE-----\n"
  8829. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8830. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8831. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8832. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8833. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8834. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8835. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8836. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8837. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8838. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8839. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8840. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8841. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8842. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8843. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8844. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8845. "-----END CERTIFICATE-----\n";
  8846. // clang-format on
  8847. SSLClient cli("google.com");
  8848. cli.load_ca_cert_store(cert, sizeof(cert));
  8849. const auto res = cli.Get("/");
  8850. ASSERT_TRUE(res);
  8851. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8852. }
  8853. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8854. SSLClient cli("www.youtube.com");
  8855. cli.set_ca_cert_path(CA_CERT_FILE);
  8856. cli.enable_server_certificate_verification(true);
  8857. cli.set_follow_location(true);
  8858. auto res = cli.Get("/");
  8859. ASSERT_TRUE(res);
  8860. ASSERT_EQ(StatusCode::OK_200, res->status);
  8861. }
  8862. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8863. SSLClient cli("wWw.YouTube.Com");
  8864. cli.set_ca_cert_path(CA_CERT_FILE);
  8865. cli.enable_server_certificate_verification(true);
  8866. cli.enable_server_hostname_verification(true);
  8867. cli.set_follow_location(true);
  8868. auto res = cli.Get("/");
  8869. ASSERT_TRUE(res);
  8870. ASSERT_EQ(StatusCode::OK_200, res->status);
  8871. }
  8872. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8873. SSLClient cli("gOoGlE.COm");
  8874. cli.enable_server_certificate_verification(true);
  8875. cli.enable_server_hostname_verification(true);
  8876. cli.set_follow_location(true);
  8877. auto res = cli.Get("/");
  8878. ASSERT_TRUE(res);
  8879. ASSERT_EQ(StatusCode::OK_200, res->status);
  8880. }
  8881. TEST(SSLClientTest, Issue2004_Online) {
  8882. Client client("https://google.com");
  8883. client.set_follow_location(true);
  8884. auto res = client.Get("/");
  8885. ASSERT_TRUE(res);
  8886. ASSERT_EQ(StatusCode::OK_200, res->status);
  8887. auto body = res->body;
  8888. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8889. }
  8890. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8891. // Create SSLClient with invalid cert/key to make is_valid() return false
  8892. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8893. "nonexistent_key.pem");
  8894. // is_valid() should be false due to cert loading failure
  8895. ASSERT_FALSE(cli.is_valid());
  8896. auto res = cli.Get("/");
  8897. ASSERT_FALSE(res);
  8898. EXPECT_EQ(Error::SSLConnection, res.error());
  8899. }
  8900. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8901. // Test for Issue #2251: SSL error not properly reported when client cert
  8902. // and key paths are swapped or mismatched
  8903. // This simulates the scenario where user accidentally swaps the cert and key
  8904. // files
  8905. // Using client cert file as private key and vice versa (completely wrong)
  8906. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8907. // Should fail validation due to cert/key mismatch
  8908. ASSERT_FALSE(cli.is_valid());
  8909. // Attempt to make a request should fail with proper error
  8910. auto res = cli.Get("/");
  8911. ASSERT_FALSE(res);
  8912. EXPECT_EQ(Error::SSLConnection, res.error());
  8913. // SSL error should be recorded in the Result object (this is the key fix for
  8914. // Issue #2251)
  8915. auto backend_error = res.ssl_backend_error();
  8916. EXPECT_NE(0u, backend_error);
  8917. }
  8918. // Tests cert/key mismatch detection at the TLS context level
  8919. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8920. // Test that using mismatched cert/key causes connection failure.
  8921. // We verify this at the SSLClient level rather than through internal
  8922. // TLS API functions.
  8923. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8924. cli.enable_server_certificate_verification(false);
  8925. cli.set_connection_timeout(2);
  8926. // The mismatch should cause a connection or handshake error
  8927. auto res = cli.Get("/test");
  8928. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8929. // Either way, the request should fail
  8930. EXPECT_FALSE(res);
  8931. }
  8932. #endif
  8933. #if 0
  8934. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8935. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8936. ASSERT_TRUE(cli != nullptr);
  8937. cli->set_address_family(AF_INET6);
  8938. cli->set_interface("en0");
  8939. auto res = cli->Get("/get");
  8940. ASSERT_TRUE(res);
  8941. ASSERT_EQ(StatusCode::OK_200, res->status);
  8942. }
  8943. #endif
  8944. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8945. #ifdef CPPHTTPLIB_SSL_ENABLED
  8946. void ClientCertPresent(
  8947. const std::string &client_cert_file,
  8948. const std::string &client_private_key_file,
  8949. const std::string &client_encrypted_private_key_pass = std::string()) {
  8950. using namespace httplib::tls;
  8951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8952. CLIENT_CA_CERT_DIR);
  8953. ASSERT_TRUE(svr.is_valid());
  8954. svr.Get("/test", [&](const Request &req, Response &res) {
  8955. res.set_content("test", "text/plain");
  8956. auto cert = req.peer_cert();
  8957. ASSERT_TRUE(static_cast<bool>(cert));
  8958. std::string common_name = cert.subject_cn();
  8959. EXPECT_EQ("Common Name", common_name);
  8960. });
  8961. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8962. auto se = detail::scope_exit([&] {
  8963. svr.stop();
  8964. t.join();
  8965. ASSERT_FALSE(svr.is_running());
  8966. });
  8967. svr.wait_until_ready();
  8968. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8969. client_encrypted_private_key_pass);
  8970. cli.enable_server_certificate_verification(false);
  8971. cli.set_connection_timeout(30);
  8972. auto res = cli.Get("/test");
  8973. ASSERT_TRUE(res);
  8974. ASSERT_EQ(StatusCode::OK_200, res->status);
  8975. }
  8976. TEST(SSLClientServerTest, ClientCertPresent) {
  8977. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8978. }
  8979. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8980. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8981. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8982. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8983. }
  8984. // PEM memory-based constructor tests (works with all TLS backends)
  8985. void PemMemoryClientCertPresent(
  8986. const std::string &client_cert_file,
  8987. const std::string &client_private_key_file,
  8988. const std::string &client_encrypted_private_key_pass = std::string()) {
  8989. // Read PEM files into memory
  8990. std::string server_cert_pem, server_key_pem;
  8991. std::string client_ca_pem;
  8992. std::string client_cert_pem, client_key_pem;
  8993. read_file(SERVER_CERT_FILE, server_cert_pem);
  8994. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8995. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8996. read_file(client_cert_file, client_cert_pem);
  8997. read_file(client_private_key_file, client_key_pem);
  8998. // Create server with PEM memory
  8999. SSLServer::PemMemory server_pem = {
  9000. server_cert_pem.c_str(),
  9001. server_cert_pem.size(),
  9002. server_key_pem.c_str(),
  9003. server_key_pem.size(),
  9004. client_ca_pem.c_str(),
  9005. client_ca_pem.size(),
  9006. nullptr // no password for server key
  9007. };
  9008. SSLServer svr(server_pem);
  9009. ASSERT_TRUE(svr.is_valid());
  9010. svr.Get("/test", [&](const Request &, Response &res) {
  9011. res.set_content("test", "text/plain");
  9012. });
  9013. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9014. auto se = detail::scope_exit([&] {
  9015. svr.stop();
  9016. t.join();
  9017. ASSERT_FALSE(svr.is_running());
  9018. });
  9019. svr.wait_until_ready();
  9020. // Create client with PEM memory
  9021. const char *password = client_encrypted_private_key_pass.empty()
  9022. ? nullptr
  9023. : client_encrypted_private_key_pass.c_str();
  9024. SSLClient::PemMemory client_pem = {
  9025. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9026. client_key_pem.size(), password};
  9027. SSLClient cli(HOST, PORT, client_pem);
  9028. cli.enable_server_certificate_verification(false);
  9029. cli.set_connection_timeout(30);
  9030. auto res = cli.Get("/test");
  9031. ASSERT_TRUE(res);
  9032. ASSERT_EQ(StatusCode::OK_200, res->status);
  9033. }
  9034. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9035. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9036. }
  9037. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9038. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9039. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9040. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9041. }
  9042. TEST(SSLClientServerTest, ClientCertMissing) {
  9043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9044. CLIENT_CA_CERT_DIR);
  9045. ASSERT_TRUE(svr.is_valid());
  9046. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9047. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9048. auto se = detail::scope_exit([&] {
  9049. svr.stop();
  9050. t.join();
  9051. ASSERT_FALSE(svr.is_running());
  9052. });
  9053. svr.wait_until_ready();
  9054. SSLClient cli(HOST, PORT);
  9055. cli.set_connection_timeout(30);
  9056. auto res = cli.Get("/test");
  9057. ASSERT_TRUE(!res);
  9058. // When client cert is missing and server requires it, connection fails
  9059. // Error type depends on backend implementation
  9060. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9061. res.error() == Error::SSLConnection);
  9062. // Verify backend error is captured
  9063. // Note: This test may have different error codes depending on the exact
  9064. // verification failure
  9065. EXPECT_NE(0UL, res.ssl_backend_error());
  9066. }
  9067. TEST(SSLClientServerTest, TrustDirOptional) {
  9068. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9069. ASSERT_TRUE(svr.is_valid());
  9070. svr.Get("/test", [&](const Request &, Response &res) {
  9071. res.set_content("test", "text/plain");
  9072. });
  9073. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9074. auto se = detail::scope_exit([&] {
  9075. svr.stop();
  9076. t.join();
  9077. ASSERT_FALSE(svr.is_running());
  9078. });
  9079. svr.wait_until_ready();
  9080. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9081. cli.enable_server_certificate_verification(false);
  9082. cli.set_connection_timeout(30);
  9083. auto res = cli.Get("/test");
  9084. ASSERT_TRUE(res);
  9085. ASSERT_EQ(StatusCode::OK_200, res->status);
  9086. }
  9087. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9088. class NoListenSSLServer : public SSLServer {
  9089. public:
  9090. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9091. const char *client_ca_cert_file_path,
  9092. const char *client_ca_cert_dir_path = nullptr)
  9093. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9094. client_ca_cert_dir_path),
  9095. stop_(false) {}
  9096. std::atomic_bool stop_;
  9097. private:
  9098. bool process_and_close_socket(socket_t /*sock*/) override {
  9099. // Don't create SSL context
  9100. while (!stop_.load()) {
  9101. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9102. }
  9103. return true;
  9104. }
  9105. };
  9106. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9107. CLIENT_CA_CERT_FILE);
  9108. ASSERT_TRUE(svr.is_valid());
  9109. svr.Get("/test", [&](const Request &, Response &res) {
  9110. res.set_content("test", "text/plain");
  9111. });
  9112. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9113. auto se = detail::scope_exit([&] {
  9114. svr.stop_ = true;
  9115. svr.stop();
  9116. t.join();
  9117. ASSERT_FALSE(svr.is_running());
  9118. });
  9119. svr.wait_until_ready();
  9120. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9121. cli.enable_server_certificate_verification(false);
  9122. cli.set_connection_timeout(1);
  9123. auto res = cli.Get("/test");
  9124. ASSERT_TRUE(!res);
  9125. EXPECT_EQ(Error::SSLConnection, res.error());
  9126. // Timeout results in WantRead error code (maps to backend-specific value)
  9127. EXPECT_NE(0, res.ssl_error());
  9128. }
  9129. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9130. // Test SSLServer with client certificate verification using the standard
  9131. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9133. CLIENT_CA_CERT_DIR);
  9134. ASSERT_TRUE(svr.is_valid());
  9135. svr.Get("/test", [&](const Request &req, Response &res) {
  9136. res.set_content("test", "text/plain");
  9137. auto cert = req.peer_cert();
  9138. ASSERT_TRUE(static_cast<bool>(cert));
  9139. auto common_name = cert.subject_cn();
  9140. EXPECT_EQ("Common Name", common_name);
  9141. });
  9142. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9143. auto se = detail::scope_exit([&] {
  9144. svr.stop();
  9145. t.join();
  9146. ASSERT_FALSE(svr.is_running());
  9147. });
  9148. svr.wait_until_ready();
  9149. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9150. cli.enable_server_certificate_verification(false);
  9151. cli.set_connection_timeout(30);
  9152. auto res = cli.Get("/test");
  9153. ASSERT_TRUE(res);
  9154. ASSERT_EQ(StatusCode::OK_200, res->status);
  9155. }
  9156. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9157. // Verifies that wildcard matching and exact matching work consistently
  9158. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9159. using namespace httplib::tls;
  9160. // We need a running server to test against
  9161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9162. ASSERT_TRUE(svr.is_valid());
  9163. svr.Get("/test", [](const Request &, Response &res) {
  9164. res.set_content("ok", "text/plain");
  9165. });
  9166. thread t([&]() { svr.listen(HOST, PORT); });
  9167. auto se = detail::scope_exit([&] {
  9168. svr.stop();
  9169. t.join();
  9170. });
  9171. svr.wait_until_ready();
  9172. bool verify_callback_called = false;
  9173. bool verify_result_wrong = false;
  9174. SSLClient cli(HOST, PORT);
  9175. cli.enable_server_certificate_verification(true);
  9176. cli.set_ca_cert_path(CA_CERT_FILE);
  9177. cli.set_connection_timeout(5);
  9178. // Note: Test certificate has CN="Common Name", not "localhost"
  9179. bool verify_result_cn = false;
  9180. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9181. verify_callback_called = true;
  9182. if (!ctx.cert) return false;
  9183. // Test 1: "Common Name" should match (our test server cert CN)
  9184. verify_result_cn = ctx.check_hostname("Common Name");
  9185. // Test 2: wrong hostname should not match
  9186. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9187. return true; // Accept for the purpose of this test
  9188. });
  9189. auto res = cli.Get("/test");
  9190. // The request may succeed or fail depending on cert configuration
  9191. // but the callback should have been called
  9192. ASSERT_TRUE(verify_callback_called)
  9193. << "Verify callback should have been called";
  9194. // CN="Common Name" should match our test certificate
  9195. //
  9196. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9197. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9198. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9199. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9200. // <openssl/base.h>, which is included transitively when
  9201. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9202. #if defined(OPENSSL_IS_BORINGSSL)
  9203. EXPECT_FALSE(verify_result_cn)
  9204. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9205. #else
  9206. EXPECT_TRUE(verify_result_cn)
  9207. << "verify_hostname should match 'Common Name' (certificate CN)";
  9208. #endif
  9209. // Wrong hostname should not match
  9210. EXPECT_FALSE(verify_result_wrong)
  9211. << "verify_hostname should not match 'wronghost.example.com'";
  9212. }
  9213. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9214. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9215. // X509_check_ip behavior and must hold for every backend.
  9216. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9217. using namespace httplib::tls;
  9218. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9219. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9220. ASSERT_TRUE(svr.is_valid());
  9221. svr.Get("/test", [](const Request &, Response &res) {
  9222. res.set_content("ok", "text/plain");
  9223. });
  9224. thread t([&]() { svr.listen(HOST, PORT); });
  9225. auto se = detail::scope_exit([&] {
  9226. svr.stop();
  9227. t.join();
  9228. });
  9229. svr.wait_until_ready();
  9230. bool verify_callback_called = false;
  9231. bool ip_matched_via_cn = true;
  9232. SSLClient cli(HOST, PORT);
  9233. cli.enable_server_certificate_verification(true);
  9234. cli.set_ca_cert_path(CA_CERT_FILE);
  9235. cli.set_connection_timeout(5);
  9236. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9237. verify_callback_called = true;
  9238. if (!ctx.cert) return false;
  9239. // The IP appears only in the CN, so it must NOT be accepted.
  9240. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9241. return true; // Accept for the purpose of this test
  9242. });
  9243. cli.Get("/test");
  9244. ASSERT_TRUE(verify_callback_called)
  9245. << "Verify callback should have been called";
  9246. EXPECT_FALSE(ip_matched_via_cn)
  9247. << "An IP host must not be authenticated via the certificate CN";
  9248. }
  9249. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9250. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9251. using namespace httplib::tls;
  9252. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9253. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9254. ASSERT_TRUE(svr.is_valid());
  9255. svr.Get("/test", [](const Request &, Response &res) {
  9256. res.set_content("ok", "text/plain");
  9257. });
  9258. thread t([&]() { svr.listen(HOST, PORT); });
  9259. auto se = detail::scope_exit([&] {
  9260. svr.stop();
  9261. t.join();
  9262. });
  9263. svr.wait_until_ready();
  9264. bool verify_callback_called = false;
  9265. bool san_matched = false;
  9266. bool wrong_ipv6_matched = true;
  9267. bool cn_ipv6_matched = true;
  9268. SSLClient cli(HOST, PORT);
  9269. cli.enable_server_certificate_verification(true);
  9270. cli.set_ca_cert_path(CA_CERT_FILE);
  9271. cli.set_connection_timeout(5);
  9272. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9273. verify_callback_called = true;
  9274. if (!ctx.cert) return false;
  9275. // Matches the IPv6 iPAddress SAN.
  9276. san_matched = ctx.check_hostname("2001:db8::1");
  9277. // A different IPv6 address must not match.
  9278. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9279. // "::1" lives only in the CN, so it must not be accepted.
  9280. cn_ipv6_matched = ctx.check_hostname("::1");
  9281. return true; // Accept for the purpose of this test
  9282. });
  9283. cli.Get("/test");
  9284. ASSERT_TRUE(verify_callback_called)
  9285. << "Verify callback should have been called";
  9286. EXPECT_TRUE(san_matched)
  9287. << "verify_hostname should match an IPv6 iPAddress SAN";
  9288. EXPECT_FALSE(wrong_ipv6_matched)
  9289. << "verify_hostname should not match a non-matching IPv6 address";
  9290. EXPECT_FALSE(cn_ipv6_matched)
  9291. << "An IPv6 host must not be authenticated via the certificate CN";
  9292. }
  9293. #endif
  9294. // mbedTLS-specific callback constructor test
  9295. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9296. #ifdef CPPHTTPLIB_SSL_ENABLED
  9297. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9298. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9299. ASSERT_TRUE(svr.is_valid());
  9300. // Set up a handler to verify client certificate is present
  9301. bool client_cert_verified = false;
  9302. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9303. // Verify that client certificate was provided
  9304. client_cert_verified = true;
  9305. res.set_content("success", "text/plain");
  9306. });
  9307. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9308. auto se = detail::scope_exit([&] {
  9309. svr.stop();
  9310. t.join();
  9311. ASSERT_FALSE(svr.is_running());
  9312. });
  9313. svr.wait_until_ready();
  9314. // Client with certificate
  9315. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9316. cli.enable_server_certificate_verification(false);
  9317. cli.set_connection_timeout(30);
  9318. auto res = cli.Get("/test");
  9319. ASSERT_TRUE(res);
  9320. ASSERT_EQ(StatusCode::OK_200, res->status);
  9321. ASSERT_TRUE(client_cert_verified);
  9322. EXPECT_EQ("success", res->body);
  9323. }
  9324. #endif
  9325. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9326. // backends
  9327. #ifdef CPPHTTPLIB_SSL_ENABLED
  9328. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9329. using namespace httplib::tls;
  9330. // Test that when client CA cert file is provided,
  9331. // the server properly requests and validates client certificates
  9332. // Create a server with client authentication
  9333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9334. ASSERT_TRUE(svr.is_valid());
  9335. bool handler_called = false;
  9336. svr.Get("/test", [&](const Request &req, Response &res) {
  9337. handler_called = true;
  9338. // Verify that a client certificate was provided
  9339. auto cert = req.peer_cert();
  9340. ASSERT_TRUE(static_cast<bool>(cert));
  9341. // Get the issuer name
  9342. std::string issuer_str = cert.issuer_name();
  9343. ASSERT_FALSE(issuer_str.empty());
  9344. // The client certificate should be issued by our test CA
  9345. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9346. res.set_content("authenticated", "text/plain");
  9347. });
  9348. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9349. auto se = detail::scope_exit([&] {
  9350. svr.stop();
  9351. t.join();
  9352. ASSERT_FALSE(svr.is_running());
  9353. });
  9354. svr.wait_until_ready();
  9355. // Connect with a client certificate issued by the CA
  9356. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9357. cli.enable_server_certificate_verification(false);
  9358. cli.set_connection_timeout(30);
  9359. auto res = cli.Get("/test");
  9360. ASSERT_TRUE(res);
  9361. ASSERT_EQ(StatusCode::OK_200, res->status);
  9362. ASSERT_TRUE(handler_called);
  9363. EXPECT_EQ("authenticated", res->body);
  9364. }
  9365. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9366. using namespace httplib::tls;
  9367. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9368. ASSERT_TRUE(svr.is_valid());
  9369. svr.Get("/test", [](const Request &, Response &res) {
  9370. res.set_content("ok", "text/plain");
  9371. });
  9372. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9373. auto se = detail::scope_exit([&] {
  9374. svr.stop();
  9375. t.join();
  9376. });
  9377. svr.wait_until_ready();
  9378. SSLClient cli(HOST, PORT);
  9379. cli.enable_server_certificate_verification(false);
  9380. cli.set_connection_timeout(30);
  9381. bool cert_checked = false;
  9382. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9383. if (ctx.cert) {
  9384. auto sans = ctx.sans();
  9385. // Test certificate may or may not have SANs - just verify the API
  9386. // works If SANs exist, verify the types are valid
  9387. for (const auto &san : sans) {
  9388. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9389. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9390. san.type == SanType::OTHER);
  9391. EXPECT_FALSE(san.value.empty());
  9392. }
  9393. cert_checked = true;
  9394. }
  9395. return true;
  9396. });
  9397. auto res = cli.Get("/test");
  9398. ASSERT_TRUE(res);
  9399. EXPECT_TRUE(cert_checked);
  9400. }
  9401. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9402. using namespace httplib::tls;
  9403. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9404. ASSERT_TRUE(svr.is_valid());
  9405. svr.Get("/test", [](const Request &, Response &res) {
  9406. res.set_content("ok", "text/plain");
  9407. });
  9408. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9409. auto se = detail::scope_exit([&] {
  9410. svr.stop();
  9411. t.join();
  9412. });
  9413. svr.wait_until_ready();
  9414. SSLClient cli(HOST, PORT);
  9415. cli.enable_server_certificate_verification(false);
  9416. cli.set_connection_timeout(30);
  9417. bool validity_checked = false;
  9418. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9419. if (ctx.cert) {
  9420. time_t not_before = 0, not_after = 0;
  9421. bool result = ctx.validity(not_before, not_after);
  9422. EXPECT_TRUE(result);
  9423. // Verify that not_before < now < not_after for a valid cert
  9424. time_t now = time(nullptr);
  9425. EXPECT_LT(not_before, now);
  9426. EXPECT_GT(not_after, now);
  9427. validity_checked = true;
  9428. }
  9429. return true;
  9430. });
  9431. auto res = cli.Get("/test");
  9432. ASSERT_TRUE(res);
  9433. EXPECT_TRUE(validity_checked);
  9434. }
  9435. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9436. using namespace httplib::tls;
  9437. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9438. ASSERT_TRUE(svr.is_valid());
  9439. svr.Get("/test", [](const Request &, Response &res) {
  9440. res.set_content("ok", "text/plain");
  9441. });
  9442. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9443. auto se = detail::scope_exit([&] {
  9444. svr.stop();
  9445. t.join();
  9446. });
  9447. svr.wait_until_ready();
  9448. SSLClient cli(HOST, PORT);
  9449. cli.enable_server_certificate_verification(false);
  9450. cli.set_connection_timeout(30);
  9451. bool serial_checked = false;
  9452. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9453. if (ctx.cert) {
  9454. std::string serial = ctx.serial();
  9455. EXPECT_FALSE(serial.empty());
  9456. // Serial should be a hex string
  9457. for (char c : serial) {
  9458. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9459. (c >= 'a' && c <= 'f'));
  9460. }
  9461. serial_checked = true;
  9462. }
  9463. return true;
  9464. });
  9465. auto res = cli.Get("/test");
  9466. ASSERT_TRUE(res);
  9467. EXPECT_TRUE(serial_checked);
  9468. }
  9469. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9470. // Test 1: Valid CA file - no error should be recorded
  9471. {
  9472. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9473. CLIENT_CA_CERT_FILE);
  9474. ASSERT_TRUE(svr.is_valid());
  9475. // With valid setup, last_ssl_error should be 0
  9476. EXPECT_EQ(0, svr.ssl_last_error());
  9477. }
  9478. // Test 2: Invalid CA file content
  9479. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9480. {
  9481. // Create a temporary file with completely invalid content
  9482. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9483. {
  9484. std::ofstream ofs(temp_invalid_ca);
  9485. ofs << "This is not a certificate file at all\n";
  9486. ofs << "Just plain text content\n";
  9487. }
  9488. // Create server with invalid CA file
  9489. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9490. // Clean up temporary file
  9491. std::remove(temp_invalid_ca);
  9492. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9493. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9494. // Note: SSL_CTX_load_verify_locations typically fails first,
  9495. // but our error handling code path is still exercised
  9496. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9497. }
  9498. }
  9499. TEST(VerifyCallbackTest, VerifyContextFields) {
  9500. using namespace httplib::tls;
  9501. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9502. ASSERT_TRUE(svr.is_valid());
  9503. svr.Get("/test", [](const Request &, Response &res) {
  9504. res.set_content("ok", "text/plain");
  9505. });
  9506. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9507. auto se = detail::scope_exit([&] {
  9508. svr.stop();
  9509. t.join();
  9510. });
  9511. svr.wait_until_ready();
  9512. SSLClient cli(HOST, PORT);
  9513. cli.enable_server_certificate_verification(false);
  9514. cli.set_connection_timeout(30);
  9515. int callback_count = 0;
  9516. bool saw_leaf_cert = false;
  9517. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9518. if (ctx.cert) {
  9519. callback_count++;
  9520. // We should see at least one certificate (the leaf)
  9521. std::string cn = ctx.subject_cn();
  9522. if (!cn.empty()) { saw_leaf_cert = true; }
  9523. // Verify context fields are populated
  9524. EXPECT_NE(ctx.session, nullptr);
  9525. EXPECT_GE(ctx.depth, 0);
  9526. }
  9527. return true;
  9528. });
  9529. auto res = cli.Get("/test");
  9530. ASSERT_TRUE(res);
  9531. EXPECT_GT(callback_count, 0);
  9532. EXPECT_TRUE(saw_leaf_cert);
  9533. }
  9534. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9535. using httplib::tls::TlsError;
  9536. // Test that verify_error_to_string returns empty for success
  9537. std::string success_str = TlsError::verify_error_to_string(0);
  9538. EXPECT_TRUE(success_str.empty());
  9539. // Test that verify_error_to_string returns non-empty for error codes
  9540. // Using a common error code (certificate expired)
  9541. std::string error_str =
  9542. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9543. EXPECT_FALSE(error_str.empty());
  9544. }
  9545. TEST(SessionVerifierTest, CertificateAccepted) {
  9546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9547. ASSERT_TRUE(svr.is_valid());
  9548. svr.Get("/test", [](const Request &, Response &res) {
  9549. res.set_content("ok", "text/plain");
  9550. });
  9551. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9552. auto se = detail::scope_exit([&] {
  9553. svr.stop();
  9554. t.join();
  9555. });
  9556. svr.wait_until_ready();
  9557. SSLClient cli(HOST, PORT);
  9558. cli.enable_server_certificate_verification(false);
  9559. cli.set_connection_timeout(30);
  9560. bool callback_called = false;
  9561. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9562. EXPECT_NE(session, nullptr);
  9563. callback_called = true;
  9564. return SSLVerifierResponse::CertificateAccepted;
  9565. });
  9566. auto res = cli.Get("/test");
  9567. ASSERT_TRUE(res);
  9568. EXPECT_EQ(200, res->status);
  9569. EXPECT_TRUE(callback_called);
  9570. }
  9571. TEST(SessionVerifierTest, CertificateRejected) {
  9572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9573. ASSERT_TRUE(svr.is_valid());
  9574. svr.Get("/test", [](const Request &, Response &res) {
  9575. res.set_content("ok", "text/plain");
  9576. });
  9577. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9578. auto se = detail::scope_exit([&] {
  9579. svr.stop();
  9580. t.join();
  9581. });
  9582. svr.wait_until_ready();
  9583. SSLClient cli(HOST, PORT);
  9584. cli.enable_server_certificate_verification(false);
  9585. cli.set_connection_timeout(30);
  9586. bool callback_called = false;
  9587. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9588. EXPECT_NE(session, nullptr);
  9589. callback_called = true;
  9590. return SSLVerifierResponse::CertificateRejected;
  9591. });
  9592. auto res = cli.Get("/test");
  9593. EXPECT_FALSE(res);
  9594. EXPECT_TRUE(callback_called);
  9595. }
  9596. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9598. ASSERT_TRUE(svr.is_valid());
  9599. svr.Get("/test", [](const Request &, Response &res) {
  9600. res.set_content("ok", "text/plain");
  9601. });
  9602. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9603. auto se = detail::scope_exit([&] {
  9604. svr.stop();
  9605. t.join();
  9606. });
  9607. svr.wait_until_ready();
  9608. // NoDecisionMade with verification disabled should succeed (no default check)
  9609. SSLClient cli(HOST, PORT);
  9610. cli.enable_server_certificate_verification(false);
  9611. cli.set_connection_timeout(30);
  9612. bool callback_called = false;
  9613. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9614. EXPECT_NE(session, nullptr);
  9615. callback_called = true;
  9616. return SSLVerifierResponse::NoDecisionMade;
  9617. });
  9618. auto res = cli.Get("/test");
  9619. ASSERT_TRUE(res);
  9620. EXPECT_EQ(200, res->status);
  9621. EXPECT_TRUE(callback_called);
  9622. }
  9623. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9625. ASSERT_TRUE(svr.is_valid());
  9626. svr.Get("/test", [](const Request &, Response &res) {
  9627. res.set_content("ok", "text/plain");
  9628. });
  9629. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9630. auto se = detail::scope_exit([&] {
  9631. svr.stop();
  9632. t.join();
  9633. });
  9634. svr.wait_until_ready();
  9635. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9636. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9637. // so we only check that the request fails, not whether the callback was
  9638. // called.
  9639. SSLClient cli(HOST, PORT);
  9640. cli.enable_server_certificate_verification(true);
  9641. cli.set_connection_timeout(30);
  9642. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9643. EXPECT_NE(session, nullptr);
  9644. return SSLVerifierResponse::NoDecisionMade;
  9645. });
  9646. auto res = cli.Get("/test");
  9647. EXPECT_FALSE(res);
  9648. }
  9649. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9650. // Test SSL server using PemMemory constructor with client CA certificates
  9651. // Read PEM files
  9652. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9653. read_file(SERVER_CERT_FILE, server_cert_pem);
  9654. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9655. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9656. // Create SSLServer with PemMemory constructor including client CA
  9657. SSLServer::PemMemory server_pem = {
  9658. server_cert_pem.c_str(),
  9659. server_cert_pem.size(),
  9660. server_key_pem.c_str(),
  9661. server_key_pem.size(),
  9662. client_ca_pem.c_str(),
  9663. client_ca_pem.size(),
  9664. nullptr // no password for server key
  9665. };
  9666. SSLServer svr(server_pem);
  9667. ASSERT_TRUE(svr.is_valid());
  9668. // No SSL error should be recorded for valid setup
  9669. EXPECT_EQ(0, svr.ssl_last_error());
  9670. // Set up server endpoints
  9671. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9672. res.set_content("ok", "text/plain");
  9673. });
  9674. // Start server in a thread
  9675. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9676. svr.wait_until_ready();
  9677. // Connect with client certificate (using constructor with paths)
  9678. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9679. cli.enable_server_certificate_verification(false);
  9680. auto res = cli.Get("/test-pem-ca");
  9681. ASSERT_TRUE(res);
  9682. EXPECT_EQ(200, res->status);
  9683. EXPECT_EQ("ok", res->body);
  9684. svr.stop();
  9685. server_thread.join();
  9686. }
  9687. #endif
  9688. #ifdef _WIN32
  9689. TEST(CleanupTest, WSACleanup) {
  9690. int ret = WSACleanup();
  9691. ASSERT_EQ(0, ret);
  9692. }
  9693. #endif
  9694. #ifndef CPPHTTPLIB_SSL_ENABLED
  9695. TEST(NoSSLSupport, SimpleInterface) {
  9696. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9697. }
  9698. #endif
  9699. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9700. TEST(InvalidScheme, SimpleInterface) {
  9701. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9702. }
  9703. #endif
  9704. TEST(NoScheme, SimpleInterface) {
  9705. Client cli("yahoo.com:80");
  9706. ASSERT_TRUE(cli.is_valid());
  9707. }
  9708. TEST(SendAPI, SimpleInterface_Online) {
  9709. Client cli("http://yahoo.com");
  9710. Request req;
  9711. req.method = "GET";
  9712. req.path = "/";
  9713. auto res = cli.send(req);
  9714. ASSERT_TRUE(res);
  9715. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9716. }
  9717. TEST(SendAPI, WithParamsInRequest) {
  9718. Server svr;
  9719. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9720. EXPECT_TRUE(req.has_param("test"));
  9721. EXPECT_EQ("test_value", req.get_param_value("test"));
  9722. });
  9723. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9724. auto se = detail::scope_exit([&] {
  9725. svr.stop();
  9726. t.join();
  9727. ASSERT_FALSE(svr.is_running());
  9728. });
  9729. svr.wait_until_ready();
  9730. Client cli(HOST, PORT);
  9731. {
  9732. Request req;
  9733. req.method = "GET";
  9734. req.path = "/";
  9735. req.params.emplace("test", "test_value");
  9736. auto res = cli.send(req);
  9737. ASSERT_TRUE(res);
  9738. }
  9739. {
  9740. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9741. ASSERT_TRUE(res);
  9742. }
  9743. }
  9744. TEST(ClientImplMethods, GetSocketTest) {
  9745. httplib::Server svr;
  9746. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9747. res.status = StatusCode::OK_200;
  9748. });
  9749. auto port = svr.bind_to_any_port("127.0.0.1");
  9750. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9751. auto se = detail::scope_exit([&] {
  9752. svr.stop();
  9753. thread.join();
  9754. ASSERT_FALSE(svr.is_running());
  9755. });
  9756. svr.wait_until_ready();
  9757. {
  9758. httplib::Client cli("127.0.0.1", port);
  9759. cli.set_keep_alive(true);
  9760. // Use the behavior of cpp-httplib of opening the connection
  9761. // only when the first request happens. If that changes,
  9762. // this test would be obsolete.
  9763. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9764. // This also implicitly tests the server. But other tests would fail much
  9765. // earlier than this one to be considered.
  9766. auto res = cli.Get("/");
  9767. ASSERT_TRUE(res);
  9768. EXPECT_EQ(StatusCode::OK_200, res->status);
  9769. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9770. }
  9771. }
  9772. #ifdef CPPHTTPLIB_SSL_ENABLED
  9773. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9774. Client cli("http://yahoo.com");
  9775. auto res = cli.Get("/");
  9776. ASSERT_TRUE(res);
  9777. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9778. cli.set_follow_location(true);
  9779. res = cli.Get("/");
  9780. ASSERT_TRUE(res);
  9781. EXPECT_EQ(StatusCode::OK_200, res->status);
  9782. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9783. }
  9784. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9785. Client cli("https://yahoo.com");
  9786. auto res = cli.Get("/");
  9787. ASSERT_TRUE(res);
  9788. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9789. cli.set_follow_location(true);
  9790. res = cli.Get("/");
  9791. ASSERT_TRUE(res);
  9792. EXPECT_EQ(StatusCode::OK_200, res->status);
  9793. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9794. }
  9795. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9796. Client cli("https://yahoo.com");
  9797. auto res = cli.Get("/");
  9798. ASSERT_TRUE(res);
  9799. ASSERT_FALSE(!res);
  9800. ASSERT_TRUE(res);
  9801. ASSERT_FALSE(res == nullptr);
  9802. ASSERT_TRUE(res != nullptr);
  9803. EXPECT_EQ(Error::Success, res.error());
  9804. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9805. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9806. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9807. cli.set_follow_location(true);
  9808. res = cli.Get("/");
  9809. ASSERT_TRUE(res);
  9810. EXPECT_EQ(Error::Success, res.error());
  9811. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9812. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9813. EXPECT_EQ(StatusCode::OK_200, res->status);
  9814. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9815. }
  9816. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9817. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9818. Client cli("https://cdnjs.cloudflare.com");
  9819. auto res =
  9820. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9821. ASSERT_TRUE(res);
  9822. EXPECT_EQ(StatusCode::OK_200, res->status);
  9823. EXPECT_EQ(287630U, res->body.size());
  9824. EXPECT_EQ("application/javascript; charset=utf-8",
  9825. res->get_header_value("Content-Type"));
  9826. }
  9827. #endif
  9828. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9829. #undef REDIR_HOST // Silence compiler warning
  9830. #define REDIR_HOST "https://httpbingo.org"
  9831. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9832. Client cli(REDIR_HOST);
  9833. cli.set_follow_location(true);
  9834. auto res =
  9835. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9836. ASSERT_TRUE(res);
  9837. EXPECT_EQ(StatusCode::OK_200, res->status);
  9838. }
  9839. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9840. Client cli(REDIR_HOST);
  9841. cli.set_follow_location(true);
  9842. Params params;
  9843. params.emplace("url", "http://example.com");
  9844. params.emplace("status_code", "302");
  9845. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9846. ASSERT_TRUE(res);
  9847. EXPECT_EQ(StatusCode::OK_200, res->status);
  9848. }
  9849. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9850. Client cli(REDIR_HOST);
  9851. cli.set_follow_location(true);
  9852. Params params;
  9853. params.emplace("url", "http://example.com");
  9854. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9855. ASSERT_TRUE(res);
  9856. EXPECT_EQ(StatusCode::OK_200, res->status);
  9857. }
  9858. TEST(HttpToHttpsRedirectTest, CertFile) {
  9859. auto ssl_port = PORT + 1;
  9860. Server svr;
  9861. ASSERT_TRUE(svr.is_valid());
  9862. svr.Get("/index", [&](const Request &, Response &res) {
  9863. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9864. "/index");
  9865. svr.stop();
  9866. });
  9867. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9868. ASSERT_TRUE(ssl_svr.is_valid());
  9869. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9870. res.set_content("test", "text/plain");
  9871. ssl_svr.stop();
  9872. });
  9873. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9874. thread t2 =
  9875. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9876. auto se = detail::scope_exit([&] {
  9877. t2.join();
  9878. t.join();
  9879. ASSERT_FALSE(svr.is_running());
  9880. });
  9881. svr.wait_until_ready();
  9882. ssl_svr.wait_until_ready();
  9883. Client cli("127.0.0.1", PORT);
  9884. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9885. cli.enable_server_certificate_verification(true);
  9886. cli.set_follow_location(true);
  9887. cli.set_connection_timeout(30);
  9888. auto res = cli.Get("/index");
  9889. ASSERT_TRUE(res);
  9890. ASSERT_EQ(StatusCode::OK_200, res->status);
  9891. }
  9892. TEST(SSLClientRedirectTest, CertFile) {
  9893. auto ssl_port = PORT + 1;
  9894. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9895. ASSERT_TRUE(ssl_svr1.is_valid());
  9896. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9897. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9898. "/index");
  9899. ssl_svr1.stop();
  9900. });
  9901. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9902. ASSERT_TRUE(ssl_svr2.is_valid());
  9903. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9904. res.set_content("test", "text/plain");
  9905. ssl_svr2.stop();
  9906. });
  9907. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9908. thread t2 =
  9909. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9910. auto se = detail::scope_exit([&] {
  9911. t2.join();
  9912. t.join();
  9913. ASSERT_FALSE(ssl_svr1.is_running());
  9914. });
  9915. ssl_svr1.wait_until_ready();
  9916. ssl_svr2.wait_until_ready();
  9917. SSLClient cli("127.0.0.1", PORT);
  9918. std::string cert;
  9919. read_file(SERVER_CERT2_FILE, cert);
  9920. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9921. cli.enable_server_certificate_verification(true);
  9922. cli.set_follow_location(true);
  9923. cli.set_connection_timeout(30);
  9924. auto res = cli.Get("/index");
  9925. ASSERT_TRUE(res);
  9926. ASSERT_EQ(StatusCode::OK_200, res->status);
  9927. }
  9928. #endif
  9929. #ifdef CPPHTTPLIB_SSL_ENABLED
  9930. // Test that set_ca_cert_store() skips system certs (consistent with
  9931. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9932. // should be trusted - system certs should NOT be loaded.
  9933. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9934. // Load a specific cert that is NOT a system CA cert
  9935. std::string cert;
  9936. read_file(SERVER_CERT2_FILE, cert);
  9937. SSLClient cli("google.com");
  9938. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9939. cli.enable_server_certificate_verification(true);
  9940. // This should FAIL because:
  9941. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9942. // 2. System certs should NOT be loaded when custom store is set
  9943. // If system certs WERE loaded, this would succeed
  9944. auto res = cli.Get("/");
  9945. ASSERT_FALSE(res);
  9946. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9947. }
  9948. // Same as above, but through the native store handle path. Regression test:
  9949. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  9950. // merged system certs into the user-provided store.
  9951. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  9952. std::string cert;
  9953. read_file(SERVER_CERT2_FILE, cert);
  9954. SSLClient cli("google.com");
  9955. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  9956. cli.enable_server_certificate_verification(true);
  9957. auto res = cli.Get("/");
  9958. ASSERT_FALSE(res);
  9959. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9960. }
  9961. // A custom store set via the native handle must still verify a server whose
  9962. // cert it does contain.
  9963. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  9964. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9965. ASSERT_TRUE(svr.is_valid());
  9966. svr.Get("/test", [&](const Request &, Response &res) {
  9967. res.set_content("test", "text/plain");
  9968. });
  9969. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9970. auto se = detail::scope_exit([&] {
  9971. svr.stop();
  9972. t.join();
  9973. ASSERT_FALSE(svr.is_running());
  9974. });
  9975. svr.wait_until_ready();
  9976. SSLClient cli("127.0.0.1", PORT);
  9977. std::string cert;
  9978. read_file(SERVER_CERT2_FILE, cert);
  9979. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  9980. cli.enable_server_certificate_verification(true);
  9981. cli.set_connection_timeout(30);
  9982. auto res = cli.Get("/test");
  9983. ASSERT_TRUE(res);
  9984. ASSERT_EQ(StatusCode::OK_200, res->status);
  9985. }
  9986. // CA certs loaded through the universal Client must be transferred to the
  9987. // client created internally for following an HTTPS redirect. Regression test:
  9988. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  9989. // the CA data for redirect transfer.
  9990. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  9991. auto ssl_port = PORT + 1;
  9992. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9993. ASSERT_TRUE(ssl_svr1.is_valid());
  9994. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9995. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9996. "/index");
  9997. });
  9998. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9999. ASSERT_TRUE(ssl_svr2.is_valid());
  10000. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10001. res.set_content("test", "text/plain");
  10002. });
  10003. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10004. thread t2 =
  10005. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10006. auto se = detail::scope_exit([&] {
  10007. ssl_svr2.stop();
  10008. ssl_svr1.stop();
  10009. t2.join();
  10010. t.join();
  10011. ASSERT_FALSE(ssl_svr1.is_running());
  10012. });
  10013. ssl_svr1.wait_until_ready();
  10014. ssl_svr2.wait_until_ready();
  10015. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10016. std::string cert;
  10017. read_file(SERVER_CERT2_FILE, cert);
  10018. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10019. cli.enable_server_certificate_verification(true);
  10020. cli.set_follow_location(true);
  10021. cli.set_connection_timeout(30);
  10022. auto res = cli.Get("/index");
  10023. ASSERT_TRUE(res);
  10024. ASSERT_EQ(StatusCode::OK_200, res->status);
  10025. }
  10026. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10027. // so a host signed by a system CA verifies even though a custom CA is set
  10028. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10029. std::string cert;
  10030. read_file(SERVER_CERT2_FILE, cert);
  10031. SSLClient cli("google.com");
  10032. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10033. cli.enable_system_ca(true);
  10034. cli.enable_server_certificate_verification(true);
  10035. auto res = cli.Get("/");
  10036. ASSERT_TRUE(res);
  10037. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10038. }
  10039. // The custom CA remains effective when combined with the system CA
  10040. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10041. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10042. ASSERT_TRUE(svr.is_valid());
  10043. svr.Get("/test", [&](const Request &, Response &res) {
  10044. res.set_content("test", "text/plain");
  10045. });
  10046. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10047. auto se = detail::scope_exit([&] {
  10048. svr.stop();
  10049. t.join();
  10050. ASSERT_FALSE(svr.is_running());
  10051. });
  10052. svr.wait_until_ready();
  10053. SSLClient cli("127.0.0.1", PORT);
  10054. std::string cert;
  10055. read_file(SERVER_CERT2_FILE, cert);
  10056. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10057. cli.enable_system_ca(true);
  10058. cli.enable_server_certificate_verification(true);
  10059. cli.set_connection_timeout(30);
  10060. auto res = cli.Get("/test");
  10061. ASSERT_TRUE(res);
  10062. ASSERT_EQ(StatusCode::OK_200, res->status);
  10063. }
  10064. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10065. // skip chain verification entirely (only the certificate identity was
  10066. // checked), so a server presenting an untrusted certificate with a matching
  10067. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10068. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10069. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10070. ASSERT_TRUE(svr.is_valid());
  10071. svr.Get("/test", [&](const Request &, Response &res) {
  10072. res.set_content("test", "text/plain");
  10073. });
  10074. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10075. auto se = detail::scope_exit([&] {
  10076. svr.stop();
  10077. t.join();
  10078. ASSERT_FALSE(svr.is_running());
  10079. });
  10080. svr.wait_until_ready();
  10081. SSLClient cli("127.0.0.1", PORT);
  10082. std::string cert;
  10083. // A trusted CA that did not sign the server certificate. The server cert
  10084. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10085. // this connection.
  10086. read_file(CLIENT_CA_CERT_FILE, cert);
  10087. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10088. cli.enable_server_certificate_verification(true);
  10089. cli.set_connection_timeout(30);
  10090. auto res = cli.Get("/test");
  10091. ASSERT_FALSE(res);
  10092. }
  10093. // enable_system_ca(false) prevents system CA loading entirely
  10094. TEST(SSLClientTest, DisableSystemCa_Online) {
  10095. SSLClient cli("google.com");
  10096. cli.enable_system_ca(false);
  10097. cli.enable_server_certificate_verification(true);
  10098. auto res = cli.Get("/");
  10099. ASSERT_FALSE(res);
  10100. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10101. // itself when the CA chain is empty
  10102. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10103. res.error() == Error::SSLConnection);
  10104. }
  10105. // The universal Client forwards enable_system_ca()
  10106. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10107. std::string cert;
  10108. read_file(SERVER_CERT2_FILE, cert);
  10109. Client cli("https://google.com");
  10110. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10111. cli.enable_system_ca(true);
  10112. cli.enable_server_certificate_verification(true);
  10113. auto res = cli.Get("/");
  10114. ASSERT_TRUE(res);
  10115. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10116. }
  10117. // The system CA policy must carry over to the client created internally for
  10118. // following a cross-host HTTPS redirect
  10119. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10120. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10121. ASSERT_TRUE(svr.is_valid());
  10122. svr.Get("/index", [&](const Request &, Response &res) {
  10123. res.set_redirect("https://www.google.com/");
  10124. });
  10125. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10126. auto se = detail::scope_exit([&] {
  10127. svr.stop();
  10128. t.join();
  10129. ASSERT_FALSE(svr.is_running());
  10130. });
  10131. svr.wait_until_ready();
  10132. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10133. std::string cert;
  10134. read_file(SERVER_CERT2_FILE, cert);
  10135. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10136. cli.enable_system_ca(true);
  10137. cli.enable_server_certificate_verification(true);
  10138. cli.set_follow_location(true);
  10139. cli.set_connection_timeout(30);
  10140. // Receiving any response proves the redirect client completed the TLS
  10141. // handshake with a system-CA-signed host
  10142. auto res = cli.Get("/index");
  10143. ASSERT_TRUE(res);
  10144. }
  10145. TEST(MultipartFormDataTest, LargeData) {
  10146. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10147. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10148. const ContentReader &content_reader) {
  10149. if (req.is_multipart_form_data()) {
  10150. std::vector<FormData> items;
  10151. content_reader(
  10152. [&](const FormData &file) {
  10153. items.push_back(file);
  10154. return true;
  10155. },
  10156. [&](const char *data, size_t data_length) {
  10157. items.back().content.append(data, data_length);
  10158. return true;
  10159. });
  10160. EXPECT_TRUE(std::string(items[0].name) == "document");
  10161. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10162. EXPECT_TRUE(items[0].filename == "2MB_data");
  10163. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10164. EXPECT_TRUE(items[1].name == "hello");
  10165. EXPECT_TRUE(items[1].content == "world");
  10166. EXPECT_TRUE(items[1].filename == "");
  10167. EXPECT_TRUE(items[1].content_type == "");
  10168. } else {
  10169. std::string body;
  10170. content_reader([&](const char *data, size_t data_length) {
  10171. body.append(data, data_length);
  10172. return true;
  10173. });
  10174. }
  10175. });
  10176. auto port = svr.bind_to_any_port(HOST);
  10177. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10178. auto se = detail::scope_exit([&] {
  10179. svr.stop();
  10180. t.join();
  10181. ASSERT_FALSE(svr.is_running());
  10182. });
  10183. svr.wait_until_ready();
  10184. {
  10185. std::string data(1024 * 1024 * 2, '.');
  10186. std::stringstream buffer;
  10187. buffer << data;
  10188. SSLClient cli(HOST, port);
  10189. cli.enable_server_certificate_verification(false);
  10190. UploadFormDataItems items{
  10191. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10192. {"hello", "world", "", ""},
  10193. };
  10194. auto res = cli.Post("/post", items);
  10195. ASSERT_TRUE(res);
  10196. ASSERT_EQ(StatusCode::OK_200, res->status);
  10197. }
  10198. }
  10199. TEST(MultipartFormDataTest, DataProviderItems) {
  10200. std::random_device seed_gen;
  10201. std::mt19937 random(seed_gen());
  10202. std::string rand1;
  10203. rand1.resize(1000);
  10204. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10205. std::string rand2;
  10206. rand2.resize(3000);
  10207. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10208. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10209. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10210. const ContentReader &content_reader) {
  10211. ASSERT_FALSE(req.is_multipart_form_data());
  10212. std::string body;
  10213. content_reader([&](const char *data, size_t data_length) {
  10214. body.append(data, data_length);
  10215. return true;
  10216. });
  10217. EXPECT_EQ(body, "");
  10218. });
  10219. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10220. const ContentReader &content_reader) {
  10221. ASSERT_TRUE(req.is_multipart_form_data());
  10222. std::vector<FormData> items;
  10223. content_reader(
  10224. [&](const FormData &file) {
  10225. items.push_back(file);
  10226. return true;
  10227. },
  10228. [&](const char *data, size_t data_length) {
  10229. items.back().content.append(data, data_length);
  10230. return true;
  10231. });
  10232. ASSERT_TRUE(items.size() == 2);
  10233. EXPECT_EQ(std::string(items[0].name), "name1");
  10234. EXPECT_EQ(items[0].content, "Testing123");
  10235. EXPECT_EQ(items[0].filename, "filename1");
  10236. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10237. EXPECT_EQ(items[1].name, "name2");
  10238. EXPECT_EQ(items[1].content, "Testing456");
  10239. EXPECT_EQ(items[1].filename, "");
  10240. EXPECT_EQ(items[1].content_type, "");
  10241. });
  10242. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10243. const ContentReader &content_reader) {
  10244. ASSERT_TRUE(req.is_multipart_form_data());
  10245. std::vector<FormData> items;
  10246. content_reader(
  10247. [&](const FormData &file) {
  10248. items.push_back(file);
  10249. return true;
  10250. },
  10251. [&](const char *data, size_t data_length) {
  10252. items.back().content.append(data, data_length);
  10253. return true;
  10254. });
  10255. ASSERT_TRUE(items.size() == 2);
  10256. EXPECT_EQ(items[0].name, "name3");
  10257. EXPECT_EQ(items[0].content, rand1);
  10258. EXPECT_EQ(items[0].filename, "filename3");
  10259. EXPECT_EQ(items[0].content_type, "");
  10260. EXPECT_EQ(items[1].name, "name4");
  10261. EXPECT_EQ(items[1].content, rand2);
  10262. EXPECT_EQ(items[1].filename, "filename4");
  10263. EXPECT_EQ(items[1].content_type, "");
  10264. });
  10265. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10266. const ContentReader &content_reader) {
  10267. ASSERT_TRUE(req.is_multipart_form_data());
  10268. std::vector<FormData> items;
  10269. content_reader(
  10270. [&](const FormData &file) {
  10271. items.push_back(file);
  10272. return true;
  10273. },
  10274. [&](const char *data, size_t data_length) {
  10275. items.back().content.append(data, data_length);
  10276. return true;
  10277. });
  10278. ASSERT_TRUE(items.size() == 4);
  10279. EXPECT_EQ(std::string(items[0].name), "name1");
  10280. EXPECT_EQ(items[0].content, "Testing123");
  10281. EXPECT_EQ(items[0].filename, "filename1");
  10282. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10283. EXPECT_EQ(items[1].name, "name2");
  10284. EXPECT_EQ(items[1].content, "Testing456");
  10285. EXPECT_EQ(items[1].filename, "");
  10286. EXPECT_EQ(items[1].content_type, "");
  10287. EXPECT_EQ(items[2].name, "name3");
  10288. EXPECT_EQ(items[2].content, rand1);
  10289. EXPECT_EQ(items[2].filename, "filename3");
  10290. EXPECT_EQ(items[2].content_type, "");
  10291. EXPECT_EQ(items[3].name, "name4");
  10292. EXPECT_EQ(items[3].content, rand2);
  10293. EXPECT_EQ(items[3].filename, "filename4");
  10294. EXPECT_EQ(items[3].content_type, "");
  10295. });
  10296. auto port = svr.bind_to_any_port("localhost");
  10297. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10298. auto se = detail::scope_exit([&] {
  10299. svr.stop();
  10300. t.join();
  10301. ASSERT_FALSE(svr.is_running());
  10302. });
  10303. svr.wait_until_ready();
  10304. {
  10305. SSLClient cli("localhost", port);
  10306. cli.enable_server_certificate_verification(false);
  10307. UploadFormDataItems items{
  10308. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10309. {"name2", "Testing456", "", ""}, // not a file
  10310. };
  10311. {
  10312. auto res = cli.Post("/post-none", {}, {}, {});
  10313. ASSERT_TRUE(res);
  10314. ASSERT_EQ(StatusCode::OK_200, res->status);
  10315. }
  10316. FormDataProviderItems providers;
  10317. {
  10318. auto res =
  10319. cli.Post("/post-items", {}, items, providers); // empty providers
  10320. ASSERT_TRUE(res);
  10321. ASSERT_EQ(StatusCode::OK_200, res->status);
  10322. }
  10323. providers.push_back({"name3",
  10324. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10325. // test the offset is given correctly at each step
  10326. if (!offset)
  10327. sink.os.write(rand1.data(), 30);
  10328. else if (offset == 30)
  10329. sink.os.write(rand1.data() + 30, 300);
  10330. else if (offset == 330)
  10331. sink.os.write(rand1.data() + 330, 670);
  10332. else if (offset == rand1.size())
  10333. sink.done();
  10334. return true;
  10335. },
  10336. "filename3",
  10337. {}});
  10338. providers.push_back({"name4",
  10339. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10340. // test the offset is given correctly at each step
  10341. if (!offset)
  10342. sink.os.write(rand2.data(), 2000);
  10343. else if (offset == 2000)
  10344. sink.os.write(rand2.data() + 2000, 1);
  10345. else if (offset == 2001)
  10346. sink.os.write(rand2.data() + 2001, 999);
  10347. else if (offset == rand2.size())
  10348. sink.done();
  10349. return true;
  10350. },
  10351. "filename4",
  10352. {}});
  10353. {
  10354. auto res = cli.Post("/post-providers", {}, {}, providers);
  10355. ASSERT_TRUE(res);
  10356. ASSERT_EQ(StatusCode::OK_200, res->status);
  10357. }
  10358. {
  10359. auto res = cli.Post("/post-both", {}, items, providers);
  10360. ASSERT_TRUE(res);
  10361. ASSERT_EQ(StatusCode::OK_200, res->status);
  10362. }
  10363. }
  10364. }
  10365. TEST(MultipartFormDataTest, BadHeader) {
  10366. Server svr;
  10367. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10368. res.set_content("ok", "text/plain");
  10369. });
  10370. thread t = thread([&] { svr.listen(HOST, PORT); });
  10371. auto se = detail::scope_exit([&] {
  10372. svr.stop();
  10373. t.join();
  10374. ASSERT_FALSE(svr.is_running());
  10375. });
  10376. svr.wait_until_ready();
  10377. const std::string body =
  10378. "This is the preamble. It is to be ignored, though it\r\n"
  10379. "is a handy place for composition agents to include an\r\n"
  10380. "explanatory note to non-MIME conformant readers.\r\n"
  10381. "\r\n"
  10382. "\r\n"
  10383. "--simple boundary\r\n"
  10384. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10385. ": BAD...\r\n"
  10386. "\r\n"
  10387. "value1\r\n"
  10388. "--simple boundary\r\n"
  10389. "Content-Disposition: form-data; name=\"field2\"; "
  10390. "filename=\"example.txt\"\r\n"
  10391. "\r\n"
  10392. "value2\r\n"
  10393. "--simple boundary--\r\n"
  10394. "This is the epilogue. It is also to be ignored.\r\n";
  10395. std::string content_type =
  10396. R"(multipart/form-data; boundary="simple boundary")";
  10397. Client cli(HOST, PORT);
  10398. auto res = cli.Post("/post", body, content_type.c_str());
  10399. ASSERT_TRUE(res);
  10400. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10401. }
  10402. TEST(MultipartFormDataTest, WithPreamble) {
  10403. Server svr;
  10404. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10405. res.set_content("ok", "text/plain");
  10406. });
  10407. thread t = thread([&] { svr.listen(HOST, PORT); });
  10408. auto se = detail::scope_exit([&] {
  10409. svr.stop();
  10410. t.join();
  10411. ASSERT_FALSE(svr.is_running());
  10412. });
  10413. svr.wait_until_ready();
  10414. const std::string body =
  10415. "This is the preamble. It is to be ignored, though it\r\n"
  10416. "is a handy place for composition agents to include an\r\n"
  10417. "explanatory note to non-MIME conformant readers.\r\n"
  10418. "\r\n"
  10419. "\r\n"
  10420. "--simple boundary\r\n"
  10421. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10422. "\r\n"
  10423. "value1\r\n"
  10424. "--simple boundary\r\n"
  10425. "Content-Disposition: form-data; name=\"field2\"; "
  10426. "filename=\"example.txt\"\r\n"
  10427. "\r\n"
  10428. "value2\r\n"
  10429. "--simple boundary--\r\n"
  10430. "This is the epilogue. It is also to be ignored.\r\n";
  10431. std::string content_type =
  10432. R"(multipart/form-data; boundary="simple boundary")";
  10433. Client cli(HOST, PORT);
  10434. auto res = cli.Post("/post", body, content_type.c_str());
  10435. ASSERT_TRUE(res);
  10436. EXPECT_EQ(StatusCode::OK_200, res->status);
  10437. }
  10438. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10439. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10440. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10441. const ContentReader &content_reader) {
  10442. if (req.is_multipart_form_data()) {
  10443. std::vector<FormData> items;
  10444. content_reader(
  10445. [&](const FormData &file) {
  10446. items.push_back(file);
  10447. return true;
  10448. },
  10449. [&](const char *data, size_t data_length) {
  10450. items.back().content.append(data, data_length);
  10451. return true;
  10452. });
  10453. EXPECT_TRUE(std::string(items[0].name) == "document");
  10454. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10455. EXPECT_TRUE(items[0].filename == "2MB_data");
  10456. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10457. EXPECT_TRUE(items[1].name == "hello");
  10458. EXPECT_TRUE(items[1].content == "world");
  10459. EXPECT_TRUE(items[1].filename == "");
  10460. EXPECT_TRUE(items[1].content_type == "");
  10461. } else {
  10462. std::string body;
  10463. content_reader([&](const char *data, size_t data_length) {
  10464. body.append(data, data_length);
  10465. return true;
  10466. });
  10467. }
  10468. });
  10469. auto port = svr.bind_to_any_port("localhost");
  10470. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10471. auto se = detail::scope_exit([&] {
  10472. svr.stop();
  10473. t.join();
  10474. ASSERT_FALSE(svr.is_running());
  10475. });
  10476. svr.wait_until_ready();
  10477. {
  10478. std::string data(1024 * 1024 * 2, '.');
  10479. std::stringstream buffer;
  10480. buffer << data;
  10481. SSLClient cli("localhost", port);
  10482. cli.enable_server_certificate_verification(false);
  10483. UploadFormDataItems items{
  10484. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10485. {"hello", "world", "", ""},
  10486. };
  10487. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10488. ASSERT_TRUE(res);
  10489. ASSERT_EQ(StatusCode::OK_200, res->status);
  10490. }
  10491. }
  10492. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10493. std::string data(1024 * 1024 * 2, '&');
  10494. std::stringstream buffer;
  10495. buffer << data;
  10496. Client cli("https://localhost:8080");
  10497. UploadFormDataItems items{
  10498. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10499. {"hello", "world", "", ""},
  10500. };
  10501. for (const char &c : " \t\r\n") {
  10502. auto res =
  10503. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10504. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10505. ASSERT_FALSE(res);
  10506. }
  10507. }
  10508. TEST(MultipartFormDataTest, PutFormData) {
  10509. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10510. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10511. const ContentReader &content_reader) {
  10512. if (req.is_multipart_form_data()) {
  10513. std::vector<FormData> items;
  10514. content_reader(
  10515. [&](const FormData &file) {
  10516. items.push_back(file);
  10517. return true;
  10518. },
  10519. [&](const char *data, size_t data_length) {
  10520. items.back().content.append(data, data_length);
  10521. return true;
  10522. });
  10523. EXPECT_TRUE(std::string(items[0].name) == "document");
  10524. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10525. EXPECT_TRUE(items[0].filename == "2MB_data");
  10526. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10527. EXPECT_TRUE(items[1].name == "hello");
  10528. EXPECT_TRUE(items[1].content == "world");
  10529. EXPECT_TRUE(items[1].filename == "");
  10530. EXPECT_TRUE(items[1].content_type == "");
  10531. } else {
  10532. std::string body;
  10533. content_reader([&](const char *data, size_t data_length) {
  10534. body.append(data, data_length);
  10535. return true;
  10536. });
  10537. }
  10538. });
  10539. auto port = svr.bind_to_any_port("localhost");
  10540. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10541. auto se = detail::scope_exit([&] {
  10542. svr.stop();
  10543. t.join();
  10544. ASSERT_FALSE(svr.is_running());
  10545. });
  10546. svr.wait_until_ready();
  10547. {
  10548. std::string data(1024 * 1024 * 2, '&');
  10549. std::stringstream buffer;
  10550. buffer << data;
  10551. SSLClient cli("localhost", port);
  10552. cli.enable_server_certificate_verification(false);
  10553. UploadFormDataItems items{
  10554. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10555. {"hello", "world", "", ""},
  10556. };
  10557. auto res = cli.Put("/put", items);
  10558. ASSERT_TRUE(res);
  10559. ASSERT_EQ(StatusCode::OK_200, res->status);
  10560. }
  10561. }
  10562. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10563. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10564. svr.Put("/put_customboundary",
  10565. [&](const Request &req, const Response & /*res*/,
  10566. const ContentReader &content_reader) {
  10567. if (req.is_multipart_form_data()) {
  10568. std::vector<FormData> items;
  10569. content_reader(
  10570. [&](const FormData &file) {
  10571. items.push_back(file);
  10572. return true;
  10573. },
  10574. [&](const char *data, size_t data_length) {
  10575. items.back().content.append(data, data_length);
  10576. return true;
  10577. });
  10578. EXPECT_TRUE(std::string(items[0].name) == "document");
  10579. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10580. EXPECT_TRUE(items[0].filename == "2MB_data");
  10581. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10582. EXPECT_TRUE(items[1].name == "hello");
  10583. EXPECT_TRUE(items[1].content == "world");
  10584. EXPECT_TRUE(items[1].filename == "");
  10585. EXPECT_TRUE(items[1].content_type == "");
  10586. } else {
  10587. std::string body;
  10588. content_reader([&](const char *data, size_t data_length) {
  10589. body.append(data, data_length);
  10590. return true;
  10591. });
  10592. }
  10593. });
  10594. auto port = svr.bind_to_any_port("localhost");
  10595. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10596. auto se = detail::scope_exit([&] {
  10597. svr.stop();
  10598. t.join();
  10599. ASSERT_FALSE(svr.is_running());
  10600. });
  10601. svr.wait_until_ready();
  10602. {
  10603. std::string data(1024 * 1024 * 2, '&');
  10604. std::stringstream buffer;
  10605. buffer << data;
  10606. SSLClient cli("localhost", port);
  10607. cli.enable_server_certificate_verification(false);
  10608. UploadFormDataItems items{
  10609. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10610. {"hello", "world", "", ""},
  10611. };
  10612. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10613. ASSERT_TRUE(res);
  10614. ASSERT_EQ(StatusCode::OK_200, res->status);
  10615. }
  10616. }
  10617. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10618. std::string data(1024 * 1024 * 2, '&');
  10619. std::stringstream buffer;
  10620. buffer << data;
  10621. Client cli("https://localhost:8080");
  10622. cli.enable_server_certificate_verification(false);
  10623. UploadFormDataItems items{
  10624. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10625. {"hello", "world", "", ""},
  10626. };
  10627. for (const char &c : " \t\r\n") {
  10628. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10629. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10630. ASSERT_FALSE(res);
  10631. }
  10632. }
  10633. TEST(MultipartFormDataTest, AlternateFilename) {
  10634. auto handled = false;
  10635. Server svr;
  10636. svr.Post("/test", [&](const Request &req, Response &res) {
  10637. ASSERT_EQ(2u, req.form.files.size());
  10638. ASSERT_EQ(1u, req.form.fields.size());
  10639. // Test files
  10640. const auto &file1 = req.form.get_file("file1");
  10641. ASSERT_EQ("file1", file1.name);
  10642. ASSERT_EQ("A.txt", file1.filename);
  10643. ASSERT_EQ("text/plain", file1.content_type);
  10644. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10645. const auto &file2 = req.form.get_file("file2");
  10646. ASSERT_EQ("file2", file2.name);
  10647. ASSERT_EQ("a.html", file2.filename);
  10648. ASSERT_EQ("text/html", file2.content_type);
  10649. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10650. file2.content);
  10651. // Test text field
  10652. const auto &text = req.form.get_field("text");
  10653. ASSERT_EQ("text default", text);
  10654. res.set_content("ok", "text/plain");
  10655. handled = true;
  10656. });
  10657. thread t = thread([&] { svr.listen(HOST, PORT); });
  10658. auto se = detail::scope_exit([&] {
  10659. svr.stop();
  10660. t.join();
  10661. ASSERT_FALSE(svr.is_running());
  10662. ASSERT_TRUE(handled);
  10663. });
  10664. svr.wait_until_ready();
  10665. auto req = "POST /test HTTP/1.1\r\n"
  10666. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10667. "Content-Length: 399\r\n"
  10668. "\r\n"
  10669. "----------\r\n"
  10670. "Content-Disposition: form-data; name=\"text\"\r\n"
  10671. "\r\n"
  10672. "text default\r\n"
  10673. "----------\r\n"
  10674. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10675. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10676. "Content-Type: text/plain\r\n"
  10677. "\r\n"
  10678. "Content of a.txt.\r\n"
  10679. "\r\n"
  10680. "----------\r\n"
  10681. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10682. "\"a.html\"\r\n"
  10683. "Content-Type: text/html\r\n"
  10684. "\r\n"
  10685. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10686. "\r\n"
  10687. "------------\r\n";
  10688. ASSERT_TRUE(send_request(1, req));
  10689. }
  10690. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10691. auto handled = false;
  10692. Server svr;
  10693. svr.Post("/test", [&](const Request &req, Response &res) {
  10694. // Case-insensitive "utf-8''" prefix with a long value
  10695. const auto &file = req.form.get_file("file1");
  10696. ASSERT_EQ("file1", file.name);
  10697. // 8000 chars exercises both the Content-Disposition parser and the
  10698. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10699. // Prior to the fix, std::regex_match on this header would cause O(N)
  10700. // stack recursion in libstdc++, leading to SIGSEGV.
  10701. std::string expected_filename(8000, 'A');
  10702. ASSERT_EQ(expected_filename, file.filename);
  10703. res.set_content("ok", "text/plain");
  10704. handled = true;
  10705. });
  10706. thread t = thread([&] { svr.listen(HOST, PORT); });
  10707. auto se = detail::scope_exit([&] {
  10708. svr.stop();
  10709. t.join();
  10710. ASSERT_FALSE(svr.is_running());
  10711. ASSERT_TRUE(handled);
  10712. });
  10713. svr.wait_until_ready();
  10714. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10715. // Regression test for GHSA-qq6v-r583-3h69
  10716. std::string long_filename(8000, 'A');
  10717. std::string body = "----------\r\n"
  10718. "Content-Disposition: form-data; name=\"file1\"; "
  10719. "filename*=\"Utf-8''" +
  10720. long_filename +
  10721. "\"\r\n"
  10722. "\r\n"
  10723. "hello\r\n"
  10724. "------------\r\n";
  10725. auto req = "POST /test HTTP/1.1\r\n"
  10726. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10727. "Content-Length: " +
  10728. std::to_string(body.size()) + "\r\n\r\n" + body;
  10729. ASSERT_TRUE(send_request(1, req));
  10730. }
  10731. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10732. auto handled = false;
  10733. Server svr;
  10734. svr.Post("/test", [&](const Request &req, Response &) {
  10735. ASSERT_EQ(2u, req.form.fields.size());
  10736. const auto &text1 = req.form.get_field("text1");
  10737. ASSERT_EQ("text1", text1);
  10738. const auto &text2 = req.form.get_field("text2");
  10739. ASSERT_EQ("text2", text2);
  10740. handled = true;
  10741. });
  10742. thread t = thread([&] { svr.listen(HOST, PORT); });
  10743. auto se = detail::scope_exit([&] {
  10744. svr.stop();
  10745. t.join();
  10746. ASSERT_FALSE(svr.is_running());
  10747. ASSERT_TRUE(handled);
  10748. });
  10749. svr.wait_until_ready();
  10750. auto req = "POST /test HTTP/1.1\r\n"
  10751. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10752. "Content-Length: 146\r\n"
  10753. "\r\n----------\r\n"
  10754. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10755. "\r\n"
  10756. "text1"
  10757. "\r\n----------\r\n"
  10758. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10759. "\r\n"
  10760. "text2"
  10761. "\r\n------------";
  10762. std::string response;
  10763. ASSERT_TRUE(send_request(1, req, &response));
  10764. ASSERT_EQ("200", response.substr(9, 3));
  10765. }
  10766. TEST(MultipartFormDataTest, ContentLength) {
  10767. auto handled = false;
  10768. Server svr;
  10769. svr.Post("/test", [&](const Request &req, Response &) {
  10770. ASSERT_EQ(2u, req.form.fields.size());
  10771. const auto &text1 = req.form.get_field("text1");
  10772. ASSERT_EQ("text1", text1);
  10773. const auto &text2 = req.form.get_field("text2");
  10774. ASSERT_EQ("text2", text2);
  10775. handled = true;
  10776. });
  10777. thread t = thread([&] { svr.listen(HOST, PORT); });
  10778. auto se = detail::scope_exit([&] {
  10779. svr.stop();
  10780. t.join();
  10781. ASSERT_FALSE(svr.is_running());
  10782. ASSERT_TRUE(handled);
  10783. });
  10784. svr.wait_until_ready();
  10785. auto req = "POST /test HTTP/1.1\r\n"
  10786. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10787. "Content-Length: 167\r\n"
  10788. "\r\n----------\r\n"
  10789. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10790. "Content-Length: 5\r\n"
  10791. "\r\n"
  10792. "text1"
  10793. "\r\n----------\r\n"
  10794. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10795. "\r\n"
  10796. "text2"
  10797. "\r\n------------\r\n";
  10798. std::string response;
  10799. ASSERT_TRUE(send_request(1, req, &response));
  10800. ASSERT_EQ("200", response.substr(9, 3));
  10801. }
  10802. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10803. auto handled = false;
  10804. Server svr;
  10805. svr.Post("/test", [&](const Request &req, Response &) {
  10806. ASSERT_EQ(2u, req.form.fields.size());
  10807. const auto &text1 = req.form.get_field("text1");
  10808. ASSERT_EQ("text1", text1);
  10809. // TODO: Add header access for text fields if needed
  10810. const auto &text2 = req.form.get_field("text2");
  10811. ASSERT_EQ("text2", text2);
  10812. // TODO: Header access for text fields needs to be implemented
  10813. // auto &headers = it->second.headers;
  10814. // ASSERT_EQ(3U, headers.size());
  10815. // auto custom_header = headers.find("x-whatever");
  10816. // ASSERT_TRUE(custom_header != headers.end());
  10817. // ASSERT_NE("customvalue", custom_header->second);
  10818. // ASSERT_EQ("CustomValue", custom_header->second);
  10819. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10820. handled = true;
  10821. });
  10822. thread t = thread([&] { svr.listen(HOST, PORT); });
  10823. auto se = detail::scope_exit([&] {
  10824. svr.stop();
  10825. t.join();
  10826. ASSERT_FALSE(svr.is_running());
  10827. ASSERT_TRUE(handled);
  10828. });
  10829. svr.wait_until_ready();
  10830. auto req = "POST /test HTTP/1.1\r\n"
  10831. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10832. "Content-Length: 232\r\n"
  10833. "\r\n----------\r\n"
  10834. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10835. "Content-Length: 5\r\n"
  10836. "X-Test: 1\r\n"
  10837. "\r\n"
  10838. "text1"
  10839. "\r\n----------\r\n"
  10840. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10841. "Content-Type: text/plain\r\n"
  10842. "X-Whatever: CustomValue\r\n"
  10843. "\r\n"
  10844. "text2"
  10845. "\r\n------------\r\n"
  10846. "That should be disregarded. Not even read";
  10847. std::string response;
  10848. ASSERT_TRUE(send_request(1, req, &response));
  10849. ASSERT_EQ("200", response.substr(9, 3));
  10850. }
  10851. TEST(MultipartFormDataTest, LargeHeader) {
  10852. auto handled = false;
  10853. Server svr;
  10854. svr.Post("/test", [&](const Request &req, Response &) {
  10855. ASSERT_EQ(1u, req.form.fields.size());
  10856. const auto &text = req.form.get_field("name1");
  10857. ASSERT_EQ("text1", text);
  10858. handled = true;
  10859. });
  10860. thread t = thread([&] { svr.listen(HOST, PORT); });
  10861. auto se = detail::scope_exit([&] {
  10862. svr.stop();
  10863. t.join();
  10864. ASSERT_FALSE(svr.is_running());
  10865. ASSERT_TRUE(handled);
  10866. });
  10867. svr.wait_until_ready();
  10868. auto boundary = std::string("cpp-httplib-multipart-data");
  10869. std::string content = "--" + boundary +
  10870. "\r\n"
  10871. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10872. "\r\n"
  10873. "text1\r\n"
  10874. "--" +
  10875. boundary + "--\r\n";
  10876. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10877. "Content-Type: multipart/form-data;boundary=" +
  10878. boundary +
  10879. "\r\n"
  10880. "Content-Length: " +
  10881. std::to_string(content.size()) +
  10882. "\r\n"
  10883. "Dummy-Header: ";
  10884. std::string header_suffix = "\r\n"
  10885. "\r\n";
  10886. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10887. size_t header_dummy_size =
  10888. read_buff_size -
  10889. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10890. auto header_dummy = std::string(header_dummy_size, '@');
  10891. auto req = header_prefix + header_dummy + header_suffix + content;
  10892. std::string response;
  10893. ASSERT_TRUE(send_request(1, req, &response));
  10894. ASSERT_EQ("200", response.substr(9, 3));
  10895. }
  10896. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10897. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10898. // (not chunked Transfer-Encoding) after the streaming refactor.
  10899. auto handled = false;
  10900. Server svr;
  10901. svr.Post("/upload", [&](const Request &req, Response &res) {
  10902. auto cl_it = req.headers.find("Content-Length");
  10903. EXPECT_TRUE(cl_it != req.headers.end());
  10904. auto te_it = req.headers.find("Transfer-Encoding");
  10905. EXPECT_TRUE(te_it == req.headers.end());
  10906. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10907. res.set_content("ok", "text/plain");
  10908. handled = true;
  10909. });
  10910. auto port = svr.bind_to_any_port(HOST);
  10911. auto t = thread([&] { svr.listen_after_bind(); });
  10912. auto se = detail::scope_exit([&] {
  10913. svr.stop();
  10914. t.join();
  10915. ASSERT_FALSE(svr.is_running());
  10916. ASSERT_TRUE(handled);
  10917. });
  10918. svr.wait_until_ready();
  10919. UploadFormDataItems items = {
  10920. {"field1", "hello", "", "text/plain"},
  10921. {"file1", "world", "test.txt", "application/octet-stream"},
  10922. };
  10923. Client cli(HOST, port);
  10924. auto res = cli.Post("/upload", {}, items);
  10925. ASSERT_TRUE(res);
  10926. EXPECT_EQ(StatusCode::OK_200, res->status);
  10927. }
  10928. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10929. // Verify that make_multipart_content_provider coalesces many small segments
  10930. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10931. constexpr size_t kItemCount = 1000;
  10932. UploadFormDataItems items;
  10933. items.reserve(kItemCount);
  10934. for (size_t i = 0; i < kItemCount; i++) {
  10935. items.push_back(
  10936. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10937. }
  10938. const std::string boundary = "----test-boundary";
  10939. auto content_length = detail::get_multipart_content_length(items, boundary);
  10940. auto provider = detail::make_multipart_content_provider(items, boundary);
  10941. // Drive the provider the same way write_content_with_progress does
  10942. size_t write_count = 0;
  10943. size_t total_bytes = 0;
  10944. DataSink sink;
  10945. size_t offset = 0;
  10946. sink.write = [&](const char *d, size_t l) -> bool {
  10947. (void)d;
  10948. write_count++;
  10949. total_bytes += l;
  10950. offset += l;
  10951. return true;
  10952. };
  10953. sink.is_writable = []() -> bool { return true; };
  10954. while (offset < content_length) {
  10955. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10956. }
  10957. EXPECT_EQ(content_length, total_bytes);
  10958. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10959. // With buffering into 64KB blocks, write_count should be much smaller.
  10960. auto segment_count = 3 * kItemCount + 1;
  10961. EXPECT_LT(write_count, segment_count / 10);
  10962. }
  10963. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10964. // Integration test: send many UploadFormDataItems and verify the server
  10965. // receives all of them correctly (#2410).
  10966. constexpr size_t kItemCount = 500;
  10967. auto handled = false;
  10968. Server svr;
  10969. svr.Post("/upload", [&](const Request &req, Response &res) {
  10970. EXPECT_EQ(kItemCount, req.form.fields.size());
  10971. for (size_t i = 0; i < kItemCount; i++) {
  10972. auto key = "field" + std::to_string(i);
  10973. auto val = "value" + std::to_string(i);
  10974. auto it = req.form.fields.find(key);
  10975. if (it != req.form.fields.end()) {
  10976. EXPECT_EQ(val, it->second.content);
  10977. } else {
  10978. ADD_FAILURE() << "Missing field: " << key;
  10979. }
  10980. }
  10981. res.set_content("ok", "text/plain");
  10982. handled = true;
  10983. });
  10984. auto port = svr.bind_to_any_port(HOST);
  10985. auto t = thread([&] { svr.listen_after_bind(); });
  10986. auto se = detail::scope_exit([&] {
  10987. svr.stop();
  10988. t.join();
  10989. ASSERT_FALSE(svr.is_running());
  10990. ASSERT_TRUE(handled);
  10991. });
  10992. svr.wait_until_ready();
  10993. UploadFormDataItems items;
  10994. items.reserve(kItemCount);
  10995. for (size_t i = 0; i < kItemCount; i++) {
  10996. items.push_back(
  10997. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10998. }
  10999. Client cli(HOST, port);
  11000. auto res = cli.Post("/upload", items);
  11001. ASSERT_TRUE(res);
  11002. EXPECT_EQ(StatusCode::OK_200, res->status);
  11003. }
  11004. TEST(MultipartFormDataTest, MakeFileProvider) {
  11005. // Verify make_file_provider sends a file's contents correctly.
  11006. const std::string file_content(4096, 'Z');
  11007. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11008. {
  11009. std::ofstream ofs(tmp_path, std::ios::binary);
  11010. ofs.write(file_content.data(),
  11011. static_cast<std::streamsize>(file_content.size()));
  11012. }
  11013. auto handled = false;
  11014. Server svr;
  11015. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11016. const ContentReader &content_reader) {
  11017. ASSERT_TRUE(req.is_multipart_form_data());
  11018. std::vector<FormData> items;
  11019. content_reader(
  11020. [&](const FormData &file) {
  11021. items.push_back(file);
  11022. return true;
  11023. },
  11024. [&](const char *data, size_t data_length) {
  11025. items.back().content.append(data, data_length);
  11026. return true;
  11027. });
  11028. ASSERT_EQ(1u, items.size());
  11029. EXPECT_EQ("myfile", items[0].name);
  11030. EXPECT_EQ("data.bin", items[0].filename);
  11031. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11032. EXPECT_EQ(file_content, items[0].content);
  11033. handled = true;
  11034. });
  11035. auto port = svr.bind_to_any_port(HOST);
  11036. auto t = thread([&] { svr.listen_after_bind(); });
  11037. auto se = detail::scope_exit([&] {
  11038. svr.stop();
  11039. t.join();
  11040. ASSERT_FALSE(svr.is_running());
  11041. ASSERT_TRUE(handled);
  11042. std::remove(tmp_path.c_str());
  11043. });
  11044. svr.wait_until_ready();
  11045. FormDataProviderItems providers;
  11046. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11047. "application/octet-stream"));
  11048. Client cli(HOST, port);
  11049. auto res = cli.Post("/upload", {}, {}, providers);
  11050. ASSERT_TRUE(res);
  11051. EXPECT_EQ(StatusCode::OK_200, res->status);
  11052. }
  11053. TEST(MakeFileBodyTest, Basic) {
  11054. const std::string file_content(4096, 'Z');
  11055. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11056. {
  11057. std::ofstream ofs(tmp_path, std::ios::binary);
  11058. ofs.write(file_content.data(),
  11059. static_cast<std::streamsize>(file_content.size()));
  11060. }
  11061. auto handled = false;
  11062. Server svr;
  11063. svr.Post("/upload", [&](const Request &req, Response &res) {
  11064. EXPECT_EQ(file_content, req.body);
  11065. handled = true;
  11066. res.status = StatusCode::OK_200;
  11067. });
  11068. auto port = svr.bind_to_any_port(HOST);
  11069. auto t = thread([&] { svr.listen_after_bind(); });
  11070. auto se = detail::scope_exit([&] {
  11071. svr.stop();
  11072. t.join();
  11073. ASSERT_FALSE(svr.is_running());
  11074. ASSERT_TRUE(handled);
  11075. std::remove(tmp_path.c_str());
  11076. });
  11077. svr.wait_until_ready();
  11078. auto fb = make_file_body(tmp_path);
  11079. ASSERT_GT(fb.first, 0u);
  11080. Client cli(HOST, port);
  11081. auto res =
  11082. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11083. ASSERT_TRUE(res);
  11084. EXPECT_EQ(StatusCode::OK_200, res->status);
  11085. }
  11086. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11087. static constexpr unsigned int number_of_tasks{1000000};
  11088. std::atomic_uint count{0};
  11089. std::unique_ptr<TaskQueue> task_queue{
  11090. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11091. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11092. auto queued = task_queue->enqueue(
  11093. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11094. EXPECT_TRUE(queued);
  11095. }
  11096. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11097. task_queue->shutdown();
  11098. #else
  11099. EXPECT_NO_THROW(task_queue->shutdown());
  11100. #endif
  11101. EXPECT_EQ(number_of_tasks, count.load());
  11102. }
  11103. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11104. static constexpr unsigned int number_of_tasks{1000000};
  11105. static constexpr unsigned int qlimit{2};
  11106. unsigned int queued_count{0};
  11107. std::atomic_uint count{0};
  11108. std::unique_ptr<TaskQueue> task_queue{
  11109. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11110. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11111. if (task_queue->enqueue(
  11112. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11113. queued_count++;
  11114. }
  11115. }
  11116. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11117. task_queue->shutdown();
  11118. #else
  11119. EXPECT_NO_THROW(task_queue->shutdown());
  11120. #endif
  11121. EXPECT_EQ(queued_count, count.load());
  11122. EXPECT_TRUE(queued_count <= number_of_tasks);
  11123. EXPECT_TRUE(queued_count >= qlimit);
  11124. }
  11125. TEST(TaskQueueTest, MaxQueuedRequests) {
  11126. static constexpr unsigned int qlimit{3};
  11127. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11128. std::condition_variable sem_cv;
  11129. std::mutex sem_mtx;
  11130. int credits = 0;
  11131. bool queued;
  11132. /* Fill up the queue with tasks that will block until we give them credits to
  11133. * complete. */
  11134. for (unsigned int n = 0; n <= qlimit;) {
  11135. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11136. std::unique_lock<std::mutex> lock(sem_mtx);
  11137. while (credits <= 0) {
  11138. sem_cv.wait(lock);
  11139. }
  11140. /* Consume the credit and signal the test code if they are all gone. */
  11141. if (--credits == 0) { sem_cv.notify_one(); }
  11142. });
  11143. if (n < qlimit) {
  11144. /* The first qlimit enqueues must succeed. */
  11145. EXPECT_TRUE(queued);
  11146. } else {
  11147. /* The last one will succeed only when the worker thread
  11148. * starts and dequeues the first blocking task. Although
  11149. * not necessary for the correctness of this test, we sleep for
  11150. * a short while to avoid busy waiting. */
  11151. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11152. }
  11153. if (queued) { n++; }
  11154. }
  11155. /* Further enqueues must fail since the queue is full. */
  11156. for (auto i = 0; i < 4; i++) {
  11157. queued = task_queue->enqueue([] {});
  11158. EXPECT_FALSE(queued);
  11159. }
  11160. /* Give the credits to allow the previous tasks to complete. */
  11161. {
  11162. std::unique_lock<std::mutex> lock(sem_mtx);
  11163. credits += qlimit + 1;
  11164. }
  11165. sem_cv.notify_all();
  11166. /* Wait for all the credits to be consumed. */
  11167. {
  11168. std::unique_lock<std::mutex> lock(sem_mtx);
  11169. while (credits > 0) {
  11170. sem_cv.wait(lock);
  11171. }
  11172. }
  11173. /* Check that we are able again to enqueue at least qlimit tasks. */
  11174. for (unsigned int i = 0; i < qlimit; i++) {
  11175. queued = task_queue->enqueue([] {});
  11176. EXPECT_TRUE(queued);
  11177. }
  11178. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11179. task_queue->shutdown();
  11180. #else
  11181. EXPECT_NO_THROW(task_queue->shutdown());
  11182. #endif
  11183. }
  11184. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11185. Server svr;
  11186. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11187. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11188. });
  11189. svr.Get("/hello", [](const Request &req, Response &res) {
  11190. res.set_content(req.get_param_value("key"), "text/plain");
  11191. });
  11192. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11193. auto se = detail::scope_exit([&] {
  11194. svr.stop();
  11195. thread.join();
  11196. ASSERT_FALSE(svr.is_running());
  11197. });
  11198. svr.wait_until_ready();
  11199. {
  11200. Client cli(HOST, PORT);
  11201. cli.set_follow_location(true);
  11202. auto res = cli.Get("/");
  11203. ASSERT_TRUE(res);
  11204. EXPECT_EQ(StatusCode::OK_200, res->status);
  11205. EXPECT_EQ("val&key2=val2", res->body);
  11206. }
  11207. }
  11208. #endif
  11209. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11210. Server svr;
  11211. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11212. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11213. });
  11214. svr.Get("/hello", [](const Request &req, Response &res) {
  11215. res.set_content(req.get_param_value("key"), "text/plain");
  11216. });
  11217. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11218. auto se = detail::scope_exit([&] {
  11219. svr.stop();
  11220. thread.join();
  11221. ASSERT_FALSE(svr.is_running());
  11222. });
  11223. svr.wait_until_ready();
  11224. {
  11225. Client cli(HOST, PORT);
  11226. cli.set_follow_location(true);
  11227. auto res = cli.Get("/");
  11228. ASSERT_TRUE(res);
  11229. EXPECT_EQ(StatusCode::OK_200, res->status);
  11230. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11231. }
  11232. }
  11233. TEST(RedirectTest, RedirectWithPlusInPath) {
  11234. Server svr;
  11235. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11236. res.set_redirect("/a+b");
  11237. });
  11238. // Route pattern uses regex; escape + as \\+
  11239. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11240. res.set_content(req.path, "text/plain");
  11241. });
  11242. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11243. auto se = detail::scope_exit([&] {
  11244. svr.stop();
  11245. thread.join();
  11246. ASSERT_FALSE(svr.is_running());
  11247. });
  11248. svr.wait_until_ready();
  11249. {
  11250. Client cli(HOST, PORT);
  11251. cli.set_follow_location(true);
  11252. auto res = cli.Get("/");
  11253. ASSERT_TRUE(res);
  11254. EXPECT_EQ(StatusCode::OK_200, res->status);
  11255. EXPECT_EQ("/a+b", res->body);
  11256. }
  11257. }
  11258. #ifdef CPPHTTPLIB_SSL_ENABLED
  11259. TEST(RedirectTest, Issue2185_Online) {
  11260. SSLClient client("github.com");
  11261. client.set_follow_location(true);
  11262. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11263. "Coollab-Windows.zip");
  11264. ASSERT_TRUE(res);
  11265. EXPECT_EQ(StatusCode::OK_200, res->status);
  11266. EXPECT_EQ(9920427U, res->body.size());
  11267. }
  11268. #endif
  11269. TEST(VulnerabilityTest, CRLFInjection) {
  11270. Server svr;
  11271. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11272. res.set_content("Hello 1", "text/plain");
  11273. });
  11274. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11275. res.set_content("Hello 2", "text/plain");
  11276. });
  11277. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11278. res.set_content("Hello 3", "text/plain");
  11279. });
  11280. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11281. res.set_content("Hello 4", "text/plain");
  11282. });
  11283. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11284. for (const auto &x : req.headers) {
  11285. auto key = x.first;
  11286. EXPECT_STRNE("evil", key.c_str());
  11287. }
  11288. });
  11289. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11290. auto se = detail::scope_exit([&] {
  11291. svr.stop();
  11292. thread.join();
  11293. ASSERT_FALSE(svr.is_running());
  11294. });
  11295. svr.wait_until_ready();
  11296. {
  11297. Client cli(HOST, PORT);
  11298. cli.Post("/test1", "A=B",
  11299. "application/x-www-form-urlencoded\r\nevil: hello1");
  11300. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11301. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11302. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11303. }
  11304. }
  11305. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11306. auto server_thread = std::thread([] {
  11307. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11308. default_socket_options(srv);
  11309. sockaddr_in addr{};
  11310. addr.sin_family = AF_INET;
  11311. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11312. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11313. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11314. ::listen(srv, 1);
  11315. sockaddr_in cli_addr{};
  11316. socklen_t cli_len = sizeof(cli_addr);
  11317. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11318. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11319. std::string buf_all;
  11320. char buf[2048];
  11321. ssize_t n;
  11322. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11323. buf_all.append(buf, static_cast<size_t>(n));
  11324. size_t pos;
  11325. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11326. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11327. auto e = request_block.find("\r\n");
  11328. if (e != std::string::npos) {
  11329. auto request_line = request_block.substr(0, e);
  11330. std::string msg =
  11331. "CRLF injection detected in request line: '" + request_line + "'";
  11332. EXPECT_FALSE(true) << msg;
  11333. }
  11334. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11335. ::send(cli,
  11336. #ifdef _WIN32
  11337. static_cast<const char *>(resp.c_str()),
  11338. static_cast<int>(resp.size()),
  11339. #else
  11340. resp.c_str(), resp.size(),
  11341. #endif
  11342. 0);
  11343. buf_all.erase(0, pos + 4);
  11344. }
  11345. }
  11346. detail::close_socket(cli);
  11347. detail::close_socket(srv);
  11348. });
  11349. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11350. auto cli = Client("127.0.0.1", PORT + 1);
  11351. auto headers = Headers{
  11352. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11353. {"Connection", "keep-alive"}};
  11354. auto res = cli.Get("/hi", headers);
  11355. EXPECT_FALSE(res);
  11356. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11357. server_thread.join();
  11358. }
  11359. TEST(PathParamsTest, StaticMatch) {
  11360. const auto pattern = "/users/all";
  11361. detail::PathParamsMatcher matcher(pattern);
  11362. Request request;
  11363. request.path = "/users/all";
  11364. ASSERT_TRUE(matcher.match(request));
  11365. std::unordered_map<std::string, std::string> expected_params = {};
  11366. EXPECT_EQ(request.path_params, expected_params);
  11367. }
  11368. TEST(PathParamsTest, StaticMismatch) {
  11369. const auto pattern = "/users/all";
  11370. detail::PathParamsMatcher matcher(pattern);
  11371. Request request;
  11372. request.path = "/users/1";
  11373. ASSERT_FALSE(matcher.match(request));
  11374. }
  11375. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11376. const auto pattern = "/users/:id/subscriptions";
  11377. detail::PathParamsMatcher matcher(pattern);
  11378. Request request;
  11379. request.path = "/users/42/subscriptions";
  11380. ASSERT_TRUE(matcher.match(request));
  11381. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11382. EXPECT_EQ(request.path_params, expected_params);
  11383. }
  11384. TEST(PathParamsTest, SingleParamInTheEnd) {
  11385. const auto pattern = "/users/:id";
  11386. detail::PathParamsMatcher matcher(pattern);
  11387. Request request;
  11388. request.path = "/users/24";
  11389. ASSERT_TRUE(matcher.match(request));
  11390. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11391. EXPECT_EQ(request.path_params, expected_params);
  11392. }
  11393. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11394. const auto pattern = "/users/:id/";
  11395. detail::PathParamsMatcher matcher(pattern);
  11396. Request request;
  11397. request.path = "/users/42/";
  11398. ASSERT_TRUE(matcher.match(request));
  11399. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11400. EXPECT_EQ(request.path_params, expected_params);
  11401. }
  11402. TEST(PathParamsTest, EmptyParam) {
  11403. const auto pattern = "/users/:id/";
  11404. detail::PathParamsMatcher matcher(pattern);
  11405. Request request;
  11406. request.path = "/users//";
  11407. ASSERT_TRUE(matcher.match(request));
  11408. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11409. EXPECT_EQ(request.path_params, expected_params);
  11410. }
  11411. TEST(PathParamsTest, FragmentMismatch) {
  11412. const auto pattern = "/users/:id/";
  11413. detail::PathParamsMatcher matcher(pattern);
  11414. Request request;
  11415. request.path = "/admins/24/";
  11416. ASSERT_FALSE(matcher.match(request));
  11417. }
  11418. TEST(PathParamsTest, ExtraFragments) {
  11419. const auto pattern = "/users/:id";
  11420. detail::PathParamsMatcher matcher(pattern);
  11421. Request request;
  11422. request.path = "/users/42/subscriptions";
  11423. ASSERT_FALSE(matcher.match(request));
  11424. }
  11425. TEST(PathParamsTest, MissingTrailingParam) {
  11426. const auto pattern = "/users/:id";
  11427. detail::PathParamsMatcher matcher(pattern);
  11428. Request request;
  11429. request.path = "/users";
  11430. ASSERT_FALSE(matcher.match(request));
  11431. }
  11432. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11433. const auto pattern = "/users/:id/subscriptions";
  11434. detail::PathParamsMatcher matcher(pattern);
  11435. Request request;
  11436. request.path = "/users/subscriptions";
  11437. ASSERT_FALSE(matcher.match(request));
  11438. }
  11439. TEST(PathParamsTest, MultipleParams) {
  11440. const auto pattern = "/users/:userid/subscriptions/:subid";
  11441. detail::PathParamsMatcher matcher(pattern);
  11442. Request request;
  11443. request.path = "/users/42/subscriptions/2";
  11444. ASSERT_TRUE(matcher.match(request));
  11445. std::unordered_map<std::string, std::string> expected_params = {
  11446. {"userid", "42"}, {"subid", "2"}};
  11447. EXPECT_EQ(request.path_params, expected_params);
  11448. }
  11449. TEST(PathParamsTest, SequenceOfParams) {
  11450. const auto pattern = "/values/:x/:y/:z";
  11451. detail::PathParamsMatcher matcher(pattern);
  11452. Request request;
  11453. request.path = "/values/1/2/3";
  11454. ASSERT_TRUE(matcher.match(request));
  11455. std::unordered_map<std::string, std::string> expected_params = {
  11456. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11457. EXPECT_EQ(request.path_params, expected_params);
  11458. }
  11459. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11460. const auto pattern = "/prefix:suffix";
  11461. detail::PathParamsMatcher matcher(pattern);
  11462. Request request;
  11463. request.path = "/prefix:suffix";
  11464. ASSERT_TRUE(matcher.match(request));
  11465. const std::unordered_map<std::string, std::string> expected_params = {};
  11466. EXPECT_EQ(request.path_params, expected_params);
  11467. }
  11468. TEST(ParseUrlTest, VariousPatterns) {
  11469. {
  11470. detail::UrlComponents uc;
  11471. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11472. EXPECT_EQ("http", uc.scheme);
  11473. EXPECT_EQ("example.com", uc.host);
  11474. EXPECT_EQ("8080", uc.port);
  11475. EXPECT_EQ("/path", uc.path);
  11476. EXPECT_EQ("?q=1", uc.query);
  11477. }
  11478. {
  11479. detail::UrlComponents uc;
  11480. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11481. EXPECT_EQ("https", uc.scheme);
  11482. EXPECT_EQ("example.com", uc.host);
  11483. EXPECT_TRUE(uc.port.empty());
  11484. EXPECT_EQ("/path", uc.path);
  11485. }
  11486. {
  11487. detail::UrlComponents uc;
  11488. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11489. EXPECT_EQ("::1", uc.host);
  11490. EXPECT_EQ("8080", uc.port);
  11491. EXPECT_EQ("/path", uc.path);
  11492. }
  11493. {
  11494. detail::UrlComponents uc;
  11495. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11496. }
  11497. {
  11498. detail::UrlComponents uc;
  11499. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11500. EXPECT_TRUE(uc.scheme.empty());
  11501. EXPECT_EQ("example.com", uc.host);
  11502. EXPECT_EQ("/path", uc.path);
  11503. EXPECT_EQ("?q=1", uc.query);
  11504. }
  11505. {
  11506. detail::UrlComponents uc;
  11507. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11508. EXPECT_TRUE(uc.host.empty());
  11509. EXPECT_EQ("/path", uc.path);
  11510. EXPECT_EQ("?q=1", uc.query);
  11511. }
  11512. {
  11513. detail::UrlComponents uc;
  11514. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11515. EXPECT_EQ("example.com", uc.host);
  11516. EXPECT_EQ("8080", uc.port);
  11517. }
  11518. {
  11519. // Unix socket path — must not be parsed as host
  11520. detail::UrlComponents uc;
  11521. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11522. EXPECT_TRUE(uc.host.empty());
  11523. }
  11524. {
  11525. detail::UrlComponents uc;
  11526. ASSERT_TRUE(detail::parse_url("", uc));
  11527. EXPECT_TRUE(uc.host.empty());
  11528. EXPECT_TRUE(uc.path.empty());
  11529. }
  11530. {
  11531. detail::UrlComponents uc;
  11532. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11533. }
  11534. {
  11535. detail::UrlComponents uc;
  11536. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11537. }
  11538. {
  11539. // Accepted by parse_url; callers restrict to http/https
  11540. detail::UrlComponents uc;
  11541. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11542. EXPECT_EQ("ftp", uc.scheme);
  11543. }
  11544. {
  11545. detail::UrlComponents uc;
  11546. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11547. }
  11548. {
  11549. detail::UrlComponents uc;
  11550. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11551. }
  11552. }
  11553. TEST(ParseUrlTest, FragmentHandling) {
  11554. {
  11555. detail::UrlComponents uc;
  11556. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11557. EXPECT_EQ("/path", uc.path);
  11558. EXPECT_TRUE(uc.query.empty());
  11559. }
  11560. {
  11561. detail::UrlComponents uc;
  11562. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11563. EXPECT_TRUE(uc.path.empty());
  11564. EXPECT_TRUE(uc.query.empty());
  11565. }
  11566. }
  11567. TEST(ParseUrlTest, UserinfoHandling) {
  11568. // Userinfo with @ but no colon — host includes @
  11569. detail::UrlComponents uc;
  11570. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11571. EXPECT_EQ("user@host.com", uc.host);
  11572. EXPECT_EQ("/path", uc.path);
  11573. }
  11574. TEST(ParseUrlTest, IPv6EdgeCases) {
  11575. {
  11576. detail::UrlComponents uc;
  11577. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11578. EXPECT_TRUE(uc.scheme.empty());
  11579. EXPECT_EQ("::1", uc.host);
  11580. EXPECT_EQ("8080", uc.port);
  11581. }
  11582. {
  11583. // Zone ID '%25' is not in [a-fA-F0-9:]
  11584. detail::UrlComponents uc;
  11585. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11586. }
  11587. }
  11588. TEST(ParseUrlTest, SchemeEdgeCases) {
  11589. {
  11590. detail::UrlComponents uc;
  11591. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11592. }
  11593. {
  11594. detail::UrlComponents uc;
  11595. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11596. }
  11597. {
  11598. detail::UrlComponents uc;
  11599. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11600. }
  11601. }
  11602. TEST(ParseUrlTest, PortEdgeCases) {
  11603. {
  11604. detail::UrlComponents uc;
  11605. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11606. EXPECT_TRUE(uc.port.empty());
  11607. EXPECT_EQ("/path", uc.path);
  11608. }
  11609. {
  11610. // parse_url accepts any port string; validation is done by parse_port
  11611. detail::UrlComponents uc;
  11612. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11613. EXPECT_EQ("abc", uc.port);
  11614. }
  11615. }
  11616. TEST(ParseUrlTest, WebSocketPatterns) {
  11617. {
  11618. detail::UrlComponents uc;
  11619. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11620. EXPECT_EQ("ws", uc.scheme);
  11621. EXPECT_EQ("echo.example.com", uc.host);
  11622. EXPECT_EQ("8080", uc.port);
  11623. EXPECT_EQ("/ws", uc.path);
  11624. }
  11625. {
  11626. detail::UrlComponents uc;
  11627. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11628. EXPECT_EQ("wss", uc.scheme);
  11629. EXPECT_EQ("echo.example.com", uc.host);
  11630. EXPECT_TRUE(uc.port.empty());
  11631. EXPECT_EQ("/ws", uc.path);
  11632. }
  11633. }
  11634. TEST(ParseUrlTest, QueryOnly) {
  11635. detail::UrlComponents uc;
  11636. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11637. EXPECT_TRUE(uc.host.empty());
  11638. EXPECT_TRUE(uc.path.empty());
  11639. EXPECT_EQ("?q=1&r=2", uc.query);
  11640. }
  11641. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11642. detail::UrlComponents uc;
  11643. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11644. EXPECT_TRUE(uc.scheme.empty());
  11645. EXPECT_EQ("example.com", uc.host);
  11646. EXPECT_EQ("443", uc.port);
  11647. EXPECT_EQ("/path", uc.path);
  11648. }
  11649. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11650. // If ipv6 regex working, regex match codepath is taken.
  11651. // else port will default to 80 in Client impl
  11652. int clientImplMagicPort = 80;
  11653. int port = 4321;
  11654. // above ports must be different to avoid false negative
  11655. EXPECT_NE(clientImplMagicPort, port);
  11656. std::string ipV6TestURL = "http://[ff06::c3]";
  11657. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11658. CLIENT_PRIVATE_KEY_FILE);
  11659. EXPECT_EQ(cli.port(), port);
  11660. }
  11661. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11662. auto file_path = "./www/dir/index.html";
  11663. auto dir_path = "./www/dir";
  11664. detail::FileStat stat_file(file_path);
  11665. EXPECT_TRUE(stat_file.is_file());
  11666. EXPECT_FALSE(stat_file.is_dir());
  11667. detail::FileStat stat_dir(dir_path);
  11668. EXPECT_FALSE(stat_dir.is_file());
  11669. EXPECT_TRUE(stat_dir.is_dir());
  11670. }
  11671. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11672. // IPv4 with default HTTP port (80)
  11673. EXPECT_EQ("example.com",
  11674. detail::make_host_and_port_string("example.com", 80, false));
  11675. // IPv4 with default HTTPS port (443)
  11676. EXPECT_EQ("example.com",
  11677. detail::make_host_and_port_string("example.com", 443, true));
  11678. // IPv4 with non-default HTTP port
  11679. EXPECT_EQ("example.com:8080",
  11680. detail::make_host_and_port_string("example.com", 8080, false));
  11681. // IPv4 with non-default HTTPS port
  11682. EXPECT_EQ("example.com:8443",
  11683. detail::make_host_and_port_string("example.com", 8443, true));
  11684. // IPv6 with default HTTP port (80)
  11685. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11686. // IPv6 with default HTTPS port (443)
  11687. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11688. // IPv6 with non-default HTTP port
  11689. EXPECT_EQ("[::1]:8080",
  11690. detail::make_host_and_port_string("::1", 8080, false));
  11691. // IPv6 with non-default HTTPS port
  11692. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11693. // IPv6 full address with default port
  11694. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11695. detail::make_host_and_port_string(
  11696. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11697. // IPv6 full address with non-default port
  11698. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11699. detail::make_host_and_port_string(
  11700. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11701. // IPv6 localhost with non-default port
  11702. EXPECT_EQ("[::1]:3000",
  11703. detail::make_host_and_port_string("::1", 3000, false));
  11704. // IPv6 with zone ID (link-local address) with default port
  11705. EXPECT_EQ("[fe80::1%eth0]",
  11706. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11707. // IPv6 with zone ID (link-local address) with non-default port
  11708. EXPECT_EQ("[fe80::1%eth0]:8080",
  11709. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11710. // Edge case: Port 443 with is_ssl=false (should add port)
  11711. EXPECT_EQ("example.com:443",
  11712. detail::make_host_and_port_string("example.com", 443, false));
  11713. // Edge case: Port 80 with is_ssl=true (should add port)
  11714. EXPECT_EQ("example.com:80",
  11715. detail::make_host_and_port_string("example.com", 80, true));
  11716. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11717. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11718. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11719. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11720. // Security fix: Already bracketed IPv6 should not get double brackets
  11721. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11722. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11723. EXPECT_EQ("[::1]:8080",
  11724. detail::make_host_and_port_string("[::1]", 8080, false));
  11725. EXPECT_EQ("[2001:db8::1]:8080",
  11726. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11727. EXPECT_EQ("[fe80::1%eth0]",
  11728. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11729. EXPECT_EQ("[fe80::1%eth0]:8080",
  11730. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11731. // Edge case: Empty host (should return as-is)
  11732. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11733. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11734. // This is a known limitation but shouldn't crash
  11735. EXPECT_EQ("[host:name]",
  11736. detail::make_host_and_port_string("host:name", 80, false));
  11737. // Port number edge cases (no validation, but should not crash)
  11738. EXPECT_EQ("example.com:0",
  11739. detail::make_host_and_port_string("example.com", 0, false));
  11740. EXPECT_EQ("example.com:-1",
  11741. detail::make_host_and_port_string("example.com", -1, false));
  11742. EXPECT_EQ("example.com:65535",
  11743. detail::make_host_and_port_string("example.com", 65535, false));
  11744. EXPECT_EQ("example.com:65536",
  11745. detail::make_host_and_port_string("example.com", 65536, false));
  11746. }
  11747. #ifdef CPPHTTPLIB_SSL_ENABLED
  11748. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11749. httplib::SSLClient cli("roblox.com", 443);
  11750. cli.set_follow_location(true);
  11751. auto res = cli.Get("/");
  11752. ASSERT_TRUE(res);
  11753. EXPECT_EQ(StatusCode::OK_200, res->status);
  11754. }
  11755. #endif
  11756. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11757. Server svr;
  11758. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11759. EXPECT_EQ(res.status, 400);
  11760. });
  11761. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11762. auto se = detail::scope_exit([&] {
  11763. svr.stop();
  11764. thread.join();
  11765. ASSERT_FALSE(svr.is_running());
  11766. });
  11767. svr.wait_until_ready();
  11768. Client cli(HOST, PORT);
  11769. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11770. }
  11771. TEST(InvalidHeaderCharsTest, is_field_name) {
  11772. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11773. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11774. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11775. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11776. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11777. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11778. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11779. EXPECT_FALSE(detail::fields::is_field_name(""));
  11780. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11781. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11782. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11783. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11784. }
  11785. TEST(InvalidHeaderCharsTest, is_field_value) {
  11786. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11787. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11788. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11789. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11790. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11791. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11792. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11793. EXPECT_TRUE(detail::fields::is_field_value(""));
  11794. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11795. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11796. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11797. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11798. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11799. }
  11800. TEST(InvalidHeaderCharsTest, OnServer) {
  11801. Server svr;
  11802. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11803. std::string header = "Not Set";
  11804. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11805. res.set_header(header, "value");
  11806. res.set_content("Page Content Page Content", "text/plain");
  11807. });
  11808. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11809. std::string header = "Not Set";
  11810. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11811. res.set_header("X-Test", header);
  11812. res.set_content("Page Content Page Content", "text/plain");
  11813. });
  11814. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11815. auto se = detail::scope_exit([&] {
  11816. svr.stop();
  11817. thread.join();
  11818. ASSERT_FALSE(svr.is_running());
  11819. });
  11820. svr.wait_until_ready();
  11821. Client cli(HOST, PORT);
  11822. {
  11823. auto res = cli.Get(
  11824. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11825. ASSERT_TRUE(res);
  11826. EXPECT_EQ("Page Content Page Content", res->body);
  11827. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11828. }
  11829. {
  11830. auto res = cli.Get(
  11831. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11832. ASSERT_TRUE(res);
  11833. EXPECT_EQ("Page Content Page Content", res->body);
  11834. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11835. }
  11836. }
  11837. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11838. auto handled = false;
  11839. Server svr;
  11840. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11841. thread t = thread([&] { svr.listen(HOST, PORT); });
  11842. auto se = detail::scope_exit([&] {
  11843. svr.stop();
  11844. t.join();
  11845. ASSERT_FALSE(svr.is_running());
  11846. ASSERT_FALSE(handled);
  11847. });
  11848. svr.wait_until_ready();
  11849. auto req = "POST /test HTTP/1.1\r\n"
  11850. "Content-Length: x\r\n"
  11851. "\r\n";
  11852. std::string response;
  11853. ASSERT_TRUE(send_request(1, req, &response));
  11854. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11855. response.substr(0, response.find("\r\n")));
  11856. }
  11857. #ifndef _WIN32
  11858. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11859. static constexpr char reject[] = "Unauthorized";
  11860. static constexpr char accept[] = "Upload accepted";
  11861. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11862. Server svr;
  11863. svr.set_expect_100_continue_handler(
  11864. [](const Request & /*req*/, Response &res) {
  11865. res.status = StatusCode::Unauthorized_401;
  11866. res.set_content(reject, "text/plain");
  11867. return res.status;
  11868. });
  11869. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11870. res.set_content(accept, "text/plain");
  11871. });
  11872. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11873. auto se = detail::scope_exit([&] {
  11874. svr.stop();
  11875. thread.join();
  11876. ASSERT_FALSE(svr.is_running());
  11877. });
  11878. svr.wait_until_ready();
  11879. {
  11880. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11881. curl_easy_init(), &curl_easy_cleanup};
  11882. ASSERT_NE(curl, nullptr);
  11883. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11884. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11885. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11886. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11887. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11888. &curl_slist_free_all};
  11889. ASSERT_NE(list, nullptr);
  11890. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11891. struct read_data {
  11892. size_t read_size;
  11893. size_t total_size;
  11894. } data = {0, total_size};
  11895. using read_callback_t =
  11896. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11897. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11898. void *userdata) -> size_t {
  11899. read_data *d = (read_data *)userdata;
  11900. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11901. std::fill_n(ptr, size * nmemb, 'A');
  11902. d->read_size += size * nmemb;
  11903. return size * nmemb;
  11904. };
  11905. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11906. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11907. std::vector<char> buffer;
  11908. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11909. using write_callback_t =
  11910. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11911. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11912. void *userdata) -> size_t {
  11913. std::vector<char> *buf = (std::vector<char> *)userdata;
  11914. buf->reserve(buf->size() + size * nmemb + 1);
  11915. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11916. return size * nmemb;
  11917. };
  11918. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11919. {
  11920. const auto res = curl_easy_perform(curl.get());
  11921. ASSERT_EQ(res, CURLE_OK);
  11922. }
  11923. {
  11924. auto response_code = long{};
  11925. const auto res =
  11926. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11927. ASSERT_EQ(res, CURLE_OK);
  11928. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11929. }
  11930. {
  11931. auto dl = curl_off_t{};
  11932. const auto res =
  11933. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11934. ASSERT_EQ(res, CURLE_OK);
  11935. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11936. }
  11937. {
  11938. buffer.push_back('\0');
  11939. ASSERT_STRCASEEQ(buffer.data(), reject);
  11940. }
  11941. }
  11942. }
  11943. #endif
  11944. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  11945. // Regression test for #2458.
  11946. //
  11947. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  11948. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  11949. // ticket can make the client socket spuriously readable during the
  11950. // 100-continue wait. If the readiness is mistaken for an incoming response,
  11951. // the client withholds the body and then blocks reading a response that never
  11952. // comes, failing with `Failed to read connection`.
  11953. //
  11954. // A correct client (like curl) sends the body once no `100 Continue` arrives
  11955. // within the timeout. This raw OpenSSL server deliberately never sends
  11956. // `100 Continue`; the client must still deliver the body and receive 200.
  11957. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  11958. signal(SIGPIPE, SIG_IGN);
  11959. const auto port = PORT + 4;
  11960. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11961. ASSERT_NE(srv, INVALID_SOCKET);
  11962. int opt = 1;
  11963. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  11964. sockaddr_in addr{};
  11965. addr.sin_family = AF_INET;
  11966. addr.sin_port = htons(static_cast<uint16_t>(port));
  11967. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11968. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11969. ASSERT_EQ(0, ::listen(srv, 1));
  11970. std::atomic<size_t> server_body_bytes{0};
  11971. auto server_thread = std::thread([&] {
  11972. sockaddr_in cli_addr{};
  11973. socklen_t cli_len = sizeof(cli_addr);
  11974. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11975. if (cli == INVALID_SOCKET) { return; }
  11976. // Bound the lifetime of the server side so a buggy client (which never
  11977. // sends the body) cannot make this thread block forever on join.
  11978. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  11979. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  11980. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  11981. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  11982. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  11983. SSL *ssl = SSL_new(ctx);
  11984. SSL_set_fd(ssl, static_cast<int>(cli));
  11985. if (SSL_accept(ssl) > 0) {
  11986. // Read the request headers. Reading here also flushes the TLS 1.3
  11987. // session tickets to the client. Deliberately do NOT send
  11988. // `100 Continue`.
  11989. std::string buf;
  11990. char tmp[1024];
  11991. while (buf.find("\r\n\r\n") == std::string::npos) {
  11992. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11993. if (n <= 0) { break; }
  11994. buf.append(tmp, static_cast<size_t>(n));
  11995. }
  11996. // A correct client sends the body now; count what arrives.
  11997. auto pos = buf.find("\r\n\r\n");
  11998. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  11999. while (body < 4096) {
  12000. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12001. if (n <= 0) { break; }
  12002. body += static_cast<size_t>(n);
  12003. }
  12004. server_body_bytes = body;
  12005. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12006. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12007. SSL_shutdown(ssl);
  12008. }
  12009. SSL_free(ssl);
  12010. detail::close_socket(cli);
  12011. SSL_CTX_free(ctx);
  12012. });
  12013. auto se = detail::scope_exit([&] {
  12014. server_thread.join();
  12015. detail::close_socket(srv);
  12016. });
  12017. SSLClient cli("127.0.0.1", port);
  12018. cli.enable_server_certificate_verification(false);
  12019. cli.set_connection_timeout(5, 0);
  12020. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12021. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12022. std::string body(4096, 'A');
  12023. auto res = cli.Put("/api/test", body, "application/json");
  12024. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12025. EXPECT_EQ(StatusCode::OK_200, res->status);
  12026. EXPECT_EQ(body.size(), server_body_bytes.load());
  12027. }
  12028. #endif
  12029. template <typename S, typename C>
  12030. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12031. svr.Get("/stream", [&](const Request &, Response &res) {
  12032. auto data = new std::string("01234567890123456789");
  12033. res.set_content_provider(
  12034. data->size(), "text/plain",
  12035. [&, data](size_t offset, size_t length, DataSink &sink) {
  12036. const size_t DATA_CHUNK_SIZE = 4;
  12037. const auto &d = *data;
  12038. std::this_thread::sleep_for(std::chrono::seconds(1));
  12039. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12040. return true;
  12041. },
  12042. [data](bool success) {
  12043. EXPECT_FALSE(success);
  12044. delete data;
  12045. });
  12046. });
  12047. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12048. auto i = new size_t(0);
  12049. res.set_content_provider(
  12050. "text/plain",
  12051. [i](size_t, DataSink &sink) {
  12052. if (*i < 5) {
  12053. std::this_thread::sleep_for(std::chrono::seconds(1));
  12054. sink.write("abcd", 4);
  12055. (*i)++;
  12056. } else {
  12057. sink.done();
  12058. }
  12059. return true;
  12060. },
  12061. [i](bool success) {
  12062. EXPECT_FALSE(success);
  12063. delete i;
  12064. });
  12065. });
  12066. svr.Get("/chunked", [&](const Request &, Response &res) {
  12067. auto i = new size_t(0);
  12068. res.set_chunked_content_provider(
  12069. "text/plain",
  12070. [i](size_t, DataSink &sink) {
  12071. if (*i < 5) {
  12072. std::this_thread::sleep_for(std::chrono::seconds(1));
  12073. sink.os << "abcd";
  12074. (*i)++;
  12075. } else {
  12076. sink.done();
  12077. }
  12078. return true;
  12079. },
  12080. [i](bool success) {
  12081. EXPECT_FALSE(success);
  12082. delete i;
  12083. });
  12084. });
  12085. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12086. auto se = detail::scope_exit([&] {
  12087. svr.stop();
  12088. listen_thread.join();
  12089. ASSERT_FALSE(svr.is_running());
  12090. });
  12091. svr.wait_until_ready();
  12092. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12093. {
  12094. auto start = std::chrono::steady_clock::now();
  12095. auto res = cli.Get("/stream");
  12096. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12097. std::chrono::steady_clock::now() - start)
  12098. .count();
  12099. ASSERT_FALSE(res);
  12100. EXPECT_EQ(Error::Read, res.error());
  12101. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12102. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12103. }
  12104. {
  12105. auto start = std::chrono::steady_clock::now();
  12106. auto res = cli.Get("/stream_without_length");
  12107. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12108. std::chrono::steady_clock::now() - start)
  12109. .count();
  12110. ASSERT_FALSE(res);
  12111. EXPECT_EQ(Error::Read, res.error());
  12112. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12113. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12114. }
  12115. {
  12116. auto start = std::chrono::steady_clock::now();
  12117. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12118. EXPECT_EQ("abcd", string(data, data_length));
  12119. return true;
  12120. });
  12121. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12122. std::chrono::steady_clock::now() - start)
  12123. .count();
  12124. ASSERT_FALSE(res);
  12125. EXPECT_EQ(Error::Read, res.error());
  12126. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12127. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12128. }
  12129. }
  12130. TEST(MaxTimeoutTest, ContentStream) {
  12131. time_t timeout = 2000;
  12132. time_t threshold = 200;
  12133. Server svr;
  12134. Client cli("localhost", PORT);
  12135. max_timeout_test(svr, cli, timeout, threshold);
  12136. }
  12137. #ifdef CPPHTTPLIB_SSL_ENABLED
  12138. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12139. time_t timeout = 2000;
  12140. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12141. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12142. SSLClient cli("localhost", PORT);
  12143. cli.enable_server_certificate_verification(false);
  12144. max_timeout_test(svr, cli, timeout, threshold);
  12145. }
  12146. #endif
  12147. class EventDispatcher {
  12148. public:
  12149. EventDispatcher() {}
  12150. bool wait_event(DataSink *sink) {
  12151. unique_lock<mutex> lk(m_);
  12152. int id = id_;
  12153. // Wait with timeout to prevent hanging if client disconnects
  12154. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12155. [&] { return cid_ == id; })) {
  12156. return false; // Timeout occurred
  12157. }
  12158. sink->write(message_.data(), message_.size());
  12159. return true;
  12160. }
  12161. void send_event(const string &message) {
  12162. lock_guard<mutex> lk(m_);
  12163. cid_ = id_++;
  12164. message_ = message;
  12165. cv_.notify_all();
  12166. }
  12167. private:
  12168. mutex m_;
  12169. condition_variable cv_;
  12170. atomic_int id_{0};
  12171. atomic_int cid_{-1};
  12172. string message_;
  12173. };
  12174. TEST(ClientInThreadTest, Issue2068) {
  12175. EventDispatcher ed;
  12176. Server svr;
  12177. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12178. res.set_chunked_content_provider("text/event-stream",
  12179. [&](size_t /*offset*/, DataSink &sink) {
  12180. return ed.wait_event(&sink);
  12181. });
  12182. });
  12183. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12184. svr.wait_until_ready();
  12185. thread event_thread([&] {
  12186. int id = 0;
  12187. while (svr.is_running()) {
  12188. this_thread::sleep_for(chrono::milliseconds(500));
  12189. std::stringstream ss;
  12190. ss << "data: " << id << "\n\n";
  12191. ed.send_event(ss.str());
  12192. id++;
  12193. }
  12194. });
  12195. auto se = detail::scope_exit([&] {
  12196. svr.stop();
  12197. listen_thread.join();
  12198. event_thread.join();
  12199. ASSERT_FALSE(svr.is_running());
  12200. });
  12201. {
  12202. auto client = detail::make_unique<Client>(HOST, PORT);
  12203. client->set_read_timeout(std::chrono::minutes(10));
  12204. std::atomic<bool> stop{false};
  12205. std::thread t([&] {
  12206. client->Get("/event1",
  12207. [&](const char *, size_t) -> bool { return !stop; });
  12208. });
  12209. std::this_thread::sleep_for(std::chrono::seconds(2));
  12210. stop = true;
  12211. client->stop();
  12212. t.join();
  12213. // Reset client after thread has finished
  12214. client.reset();
  12215. }
  12216. }
  12217. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12218. auto handled = false;
  12219. Server svr;
  12220. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12221. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12222. auto se = detail::scope_exit([&] {
  12223. svr.stop();
  12224. t.join();
  12225. ASSERT_FALSE(svr.is_running());
  12226. ASSERT_FALSE(handled);
  12227. });
  12228. svr.wait_until_ready();
  12229. // Two Content-Length headers with different values — must be rejected
  12230. auto req = "POST /test HTTP/1.1\r\n"
  12231. "Content-Length: 5\r\n"
  12232. "Content-Length: 10\r\n"
  12233. "\r\n"
  12234. "hello";
  12235. std::string response;
  12236. ASSERT_TRUE(send_request(1, req, &response));
  12237. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12238. response.substr(0, response.find("\r\n")));
  12239. }
  12240. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12241. auto handled = false;
  12242. Server svr;
  12243. svr.Post("/test", [&](const Request &, Response &res) {
  12244. handled = true;
  12245. res.set_content("ok", "text/plain");
  12246. });
  12247. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12248. auto se = detail::scope_exit([&] {
  12249. svr.stop();
  12250. t.join();
  12251. ASSERT_FALSE(svr.is_running());
  12252. ASSERT_TRUE(handled);
  12253. });
  12254. svr.wait_until_ready();
  12255. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12256. auto req = "POST /test HTTP/1.1\r\n"
  12257. "Content-Length: 5\r\n"
  12258. "Content-Length: 5\r\n"
  12259. "\r\n"
  12260. "hello";
  12261. std::string response;
  12262. ASSERT_TRUE(send_request(1, req, &response));
  12263. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12264. }
  12265. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12266. Server svr;
  12267. svr.Get("/", [](const Request &req, Response &res) {
  12268. EXPECT_EQ(2U, req.trailers.size());
  12269. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12270. // Denied
  12271. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12272. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12273. // Accepted
  12274. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12275. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12276. EXPECT_TRUE(req.has_trailer("X-World"));
  12277. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12278. res.set_content("ok", "text/plain");
  12279. });
  12280. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12281. auto se = detail::scope_exit([&] {
  12282. svr.stop();
  12283. t.join();
  12284. ASSERT_FALSE(svr.is_running());
  12285. });
  12286. svr.wait_until_ready();
  12287. const std::string req = "GET / HTTP/1.1\r\n"
  12288. "Transfer-Encoding: chunked\r\n"
  12289. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12290. "\r\n"
  12291. "0\r\n"
  12292. "Content-Length: 10\r\n"
  12293. "Host: internal.local\r\n"
  12294. "Content-Type: malicious/content\r\n"
  12295. "Cookie: any\r\n"
  12296. "Set-Cookie: any\r\n"
  12297. "X-Forwarded-For: attacker.com\r\n"
  12298. "X-Real-Ip: 1.1.1.1\r\n"
  12299. "X-Hello: hello\r\n"
  12300. "X-World: world\r\n"
  12301. "\r\n";
  12302. std::string res;
  12303. ASSERT_TRUE(send_request(1, req, &res));
  12304. }
  12305. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12306. Server svr;
  12307. std::string observed_remote_addr;
  12308. std::string observed_xff;
  12309. svr.Get("/ip", [&](const Request &req, Response &res) {
  12310. observed_remote_addr = req.remote_addr;
  12311. observed_xff = req.get_header_value("X-Forwarded-For");
  12312. res.set_content("ok", "text/plain");
  12313. });
  12314. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12315. auto se = detail::scope_exit([&] {
  12316. svr.stop();
  12317. t.join();
  12318. ASSERT_FALSE(svr.is_running());
  12319. });
  12320. svr.wait_until_ready();
  12321. Client cli(HOST, PORT);
  12322. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  12323. ASSERT_TRUE(res);
  12324. EXPECT_EQ(StatusCode::OK_200, res->status);
  12325. EXPECT_EQ(observed_xff, "203.0.113.66");
  12326. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12327. observed_remote_addr == "127.0.0.1");
  12328. }
  12329. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12330. Server svr;
  12331. svr.set_trusted_proxies({"203.0.113.66"});
  12332. std::string observed_remote_addr;
  12333. std::string observed_xff;
  12334. svr.Get("/ip", [&](const Request &req, Response &res) {
  12335. observed_remote_addr = req.remote_addr;
  12336. observed_xff = req.get_header_value("X-Forwarded-For");
  12337. res.set_content("ok", "text/plain");
  12338. });
  12339. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12340. auto se = detail::scope_exit([&] {
  12341. svr.stop();
  12342. t.join();
  12343. ASSERT_FALSE(svr.is_running());
  12344. });
  12345. svr.wait_until_ready();
  12346. Client cli(HOST, PORT);
  12347. auto res = cli.Get("/ip");
  12348. ASSERT_TRUE(res);
  12349. EXPECT_EQ(StatusCode::OK_200, res->status);
  12350. EXPECT_EQ(observed_xff, "");
  12351. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12352. observed_remote_addr == "127.0.0.1");
  12353. }
  12354. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12355. Server svr;
  12356. svr.set_trusted_proxies({"203.0.113.66"});
  12357. std::string observed_remote_addr;
  12358. std::string observed_xff;
  12359. svr.Get("/ip", [&](const Request &req, Response &res) {
  12360. observed_remote_addr = req.remote_addr;
  12361. observed_xff = req.get_header_value("X-Forwarded-For");
  12362. res.set_content("ok", "text/plain");
  12363. });
  12364. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12365. auto se = detail::scope_exit([&] {
  12366. svr.stop();
  12367. t.join();
  12368. ASSERT_FALSE(svr.is_running());
  12369. });
  12370. svr.wait_until_ready();
  12371. Client cli(HOST, PORT);
  12372. auto res =
  12373. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12374. ASSERT_TRUE(res);
  12375. EXPECT_EQ(StatusCode::OK_200, res->status);
  12376. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12377. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12378. }
  12379. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12380. Server svr;
  12381. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12382. std::string observed_remote_addr;
  12383. std::string observed_xff;
  12384. svr.Get("/ip", [&](const Request &req, Response &res) {
  12385. observed_remote_addr = req.remote_addr;
  12386. observed_xff = req.get_header_value("X-Forwarded-For");
  12387. res.set_content("ok", "text/plain");
  12388. });
  12389. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12390. auto se = detail::scope_exit([&] {
  12391. svr.stop();
  12392. t.join();
  12393. ASSERT_FALSE(svr.is_running());
  12394. });
  12395. svr.wait_until_ready();
  12396. Client cli(HOST, PORT);
  12397. auto res = cli.Get(
  12398. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12399. ASSERT_TRUE(res);
  12400. EXPECT_EQ(StatusCode::OK_200, res->status);
  12401. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12402. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12403. }
  12404. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12405. Server svr;
  12406. svr.set_trusted_proxies({"192.0.2.45"});
  12407. std::string observed_remote_addr;
  12408. std::string observed_xff;
  12409. svr.Get("/ip", [&](const Request &req, Response &res) {
  12410. observed_remote_addr = req.remote_addr;
  12411. observed_xff = req.get_header_value("X-Forwarded-For");
  12412. res.set_content("ok", "text/plain");
  12413. });
  12414. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12415. auto se = detail::scope_exit([&] {
  12416. svr.stop();
  12417. t.join();
  12418. ASSERT_FALSE(svr.is_running());
  12419. });
  12420. svr.wait_until_ready();
  12421. Client cli(HOST, PORT);
  12422. auto res =
  12423. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12424. ASSERT_TRUE(res);
  12425. EXPECT_EQ(StatusCode::OK_200, res->status);
  12426. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12427. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12428. }
  12429. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12430. Server svr;
  12431. svr.set_trusted_proxies({"192.0.2.45"});
  12432. std::string observed_remote_addr;
  12433. std::string observed_xff;
  12434. svr.Get("/ip", [&](const Request &req, Response &res) {
  12435. observed_remote_addr = req.remote_addr;
  12436. observed_xff = req.get_header_value("X-Forwarded-For");
  12437. res.set_content("ok", "text/plain");
  12438. });
  12439. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12440. auto se = detail::scope_exit([&] {
  12441. svr.stop();
  12442. t.join();
  12443. ASSERT_FALSE(svr.is_running());
  12444. });
  12445. svr.wait_until_ready();
  12446. Client cli(HOST, PORT);
  12447. auto res = cli.Get(
  12448. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12449. ASSERT_TRUE(res);
  12450. EXPECT_EQ(StatusCode::OK_200, res->status);
  12451. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12452. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12453. }
  12454. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12455. Server svr;
  12456. svr.set_trusted_proxies({"192.0.2.45"});
  12457. std::string observed_remote_addr;
  12458. std::string observed_xff;
  12459. svr.Get("/ip", [&](const Request &req, Response &res) {
  12460. observed_remote_addr = req.remote_addr;
  12461. observed_xff = req.get_header_value("X-Forwarded-For");
  12462. res.set_content("ok", "text/plain");
  12463. });
  12464. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12465. auto se = detail::scope_exit([&] {
  12466. svr.stop();
  12467. t.join();
  12468. ASSERT_FALSE(svr.is_running());
  12469. });
  12470. svr.wait_until_ready();
  12471. std::string raw_req =
  12472. "GET /ip HTTP/1.1\r\n"
  12473. "Host: localhost\r\n"
  12474. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12475. "Connection: close\r\n"
  12476. "\r\n";
  12477. std::string out;
  12478. ASSERT_TRUE(send_request(5, raw_req, &out));
  12479. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12480. // Header parser trims surrounding whitespace of the header value
  12481. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12482. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12483. }
  12484. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12485. // crash the server (it used to call front() on an empty vector inside
  12486. // get_client_ip). The connection-level remote address must be retained instead.
  12487. static void run_malformed_xff_test(const std::string &xff_value) {
  12488. Server svr;
  12489. svr.set_trusted_proxies({"192.0.2.45"});
  12490. std::string observed_remote_addr;
  12491. svr.Get("/ip", [&](const Request &req, Response &res) {
  12492. observed_remote_addr = req.remote_addr;
  12493. res.set_content("ok", "text/plain");
  12494. });
  12495. int port = 0;
  12496. thread t = thread([&]() {
  12497. port = svr.bind_to_any_port(HOST);
  12498. svr.listen_after_bind();
  12499. });
  12500. auto se = detail::scope_exit([&] {
  12501. svr.stop();
  12502. t.join();
  12503. ASSERT_FALSE(svr.is_running());
  12504. });
  12505. svr.wait_until_ready();
  12506. Client cli(HOST, port);
  12507. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  12508. ASSERT_TRUE(res);
  12509. EXPECT_EQ(StatusCode::OK_200, res->status);
  12510. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12511. observed_remote_addr == "127.0.0.1");
  12512. }
  12513. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12514. run_malformed_xff_test("");
  12515. }
  12516. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12517. run_malformed_xff_test(",");
  12518. }
  12519. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12520. run_malformed_xff_test(", , ,");
  12521. }
  12522. #ifndef _WIN32
  12523. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12524. Server svr;
  12525. svr.Post("/post", [&](const Request &req, Response &res) {
  12526. res.set_content(req.body, "text/plain");
  12527. });
  12528. svr.Put("/put", [&](const Request &req, Response &res) {
  12529. res.set_content(req.body, "text/plain");
  12530. });
  12531. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12532. res.set_content(req.body, "text/plain");
  12533. });
  12534. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12535. res.set_content(req.body, "text/plain");
  12536. });
  12537. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12538. auto se = detail::scope_exit([&] {
  12539. svr.stop();
  12540. t.join();
  12541. ASSERT_FALSE(svr.is_running());
  12542. });
  12543. svr.wait_until_ready();
  12544. std::string resp;
  12545. // POST without Content-Length
  12546. ASSERT_TRUE(send_request(5,
  12547. "POST /post HTTP/1.1\r\n"
  12548. "Host: localhost\r\n"
  12549. "Connection: close\r\n"
  12550. "\r\n",
  12551. &resp));
  12552. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12553. // PUT without Content-Length
  12554. resp.clear();
  12555. ASSERT_TRUE(send_request(5,
  12556. "PUT /put HTTP/1.1\r\n"
  12557. "Host: localhost\r\n"
  12558. "Connection: close\r\n"
  12559. "\r\n",
  12560. &resp));
  12561. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12562. // PATCH without Content-Length
  12563. resp.clear();
  12564. ASSERT_TRUE(send_request(5,
  12565. "PATCH /patch HTTP/1.1\r\n"
  12566. "Host: localhost\r\n"
  12567. "Connection: close\r\n"
  12568. "\r\n",
  12569. &resp));
  12570. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12571. // DELETE without Content-Length
  12572. resp.clear();
  12573. ASSERT_TRUE(send_request(5,
  12574. "DELETE /delete HTTP/1.1\r\n"
  12575. "Host: localhost\r\n"
  12576. "Connection: close\r\n"
  12577. "\r\n",
  12578. &resp));
  12579. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12580. }
  12581. #endif
  12582. //==============================================================================
  12583. // open_stream() Tests
  12584. //==============================================================================
  12585. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12586. std::string result;
  12587. char buf[8192];
  12588. ssize_t n;
  12589. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12590. result.append(buf, static_cast<size_t>(n));
  12591. }
  12592. return result;
  12593. }
  12594. // Mock stream for unit tests
  12595. class MockStream : public Stream {
  12596. public:
  12597. std::string data;
  12598. size_t pos = 0;
  12599. ssize_t error_after = -1; // -1 = no error
  12600. explicit MockStream(const std::string &d, ssize_t err = -1)
  12601. : data(d), error_after(err) {}
  12602. bool is_readable() const override { return true; }
  12603. bool wait_readable() const override { return true; }
  12604. bool wait_writable() const override { return true; }
  12605. ssize_t read(char *ptr, size_t size) override {
  12606. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12607. if (pos >= data.size()) return 0;
  12608. size_t limit =
  12609. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12610. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12611. std::memcpy(ptr, data.data() + pos, to_read);
  12612. pos += to_read;
  12613. return static_cast<ssize_t>(to_read);
  12614. }
  12615. ssize_t write(const char *, size_t) override { return -1; }
  12616. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12617. ip = "127.0.0.1";
  12618. port = 0;
  12619. }
  12620. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12621. ip = "127.0.0.1";
  12622. port = 0;
  12623. }
  12624. socket_t socket() const override { return INVALID_SOCKET; }
  12625. time_t duration() const override { return 0; }
  12626. };
  12627. TEST(StreamHandleTest, Basic) {
  12628. ClientImpl::StreamHandle handle;
  12629. EXPECT_FALSE(handle.is_valid());
  12630. handle.response = detail::make_unique<Response>();
  12631. handle.error = Error::Connection;
  12632. EXPECT_FALSE(handle.is_valid());
  12633. handle.error = Error::Success;
  12634. EXPECT_TRUE(handle.is_valid());
  12635. }
  12636. TEST(BodyReaderTest, Basic) {
  12637. MockStream stream("Hello, World!");
  12638. detail::BodyReader reader;
  12639. reader.stream = &stream;
  12640. reader.content_length = 13;
  12641. char buf[32];
  12642. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12643. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12644. EXPECT_TRUE(reader.eof);
  12645. }
  12646. TEST(BodyReaderTest, NoStream) {
  12647. detail::BodyReader reader;
  12648. char buf[32];
  12649. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12650. EXPECT_EQ(Error::Connection, reader.last_error);
  12651. }
  12652. TEST(BodyReaderTest, Error) {
  12653. MockStream stream("Hello, World!", 5);
  12654. detail::BodyReader reader;
  12655. reader.stream = &stream;
  12656. reader.content_length = 13;
  12657. char buf[32];
  12658. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12659. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12660. EXPECT_EQ(Error::Read, reader.last_error);
  12661. }
  12662. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12663. // Mock-based StreamHandle tests relying on private internals are removed.
  12664. class OpenStreamTest : public ::testing::Test {
  12665. protected:
  12666. void SetUp() override {
  12667. svr_.Get("/hello", [](const Request &, Response &res) {
  12668. res.set_content("Hello World!", "text/plain");
  12669. });
  12670. svr_.Get("/large", [](const Request &, Response &res) {
  12671. res.set_content(std::string(10000, 'X'), "text/plain");
  12672. });
  12673. svr_.Get("/chunked", [](const Request &, Response &res) {
  12674. res.set_chunked_content_provider("text/plain",
  12675. [](size_t offset, DataSink &sink) {
  12676. if (offset < 15) {
  12677. sink.write("chunk", 5);
  12678. return true;
  12679. }
  12680. sink.done();
  12681. return true;
  12682. });
  12683. });
  12684. svr_.Get("/compressible", [](const Request &, Response &res) {
  12685. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12686. DataSink &sink) {
  12687. if (offset < 100 * 1024) {
  12688. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12689. sink.write(chunk.data(), chunk.size());
  12690. return true;
  12691. }
  12692. sink.done();
  12693. return true;
  12694. });
  12695. });
  12696. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12697. [](const Request & /*req*/, Response &res) {
  12698. auto i = new int(0);
  12699. res.set_header("Trailer", "Content-Length, X-Allowed");
  12700. res.set_chunked_content_provider(
  12701. "text/plain",
  12702. [i](size_t /*offset*/, DataSink &sink) {
  12703. switch (*i) {
  12704. case 0: sink.os << "123"; break;
  12705. case 1: sink.os << "456"; break;
  12706. case 2: sink.os << "789"; break;
  12707. case 3: {
  12708. sink.done_with_trailer(
  12709. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12710. } break;
  12711. }
  12712. (*i)++;
  12713. return true;
  12714. },
  12715. [i](bool success) {
  12716. EXPECT_TRUE(success);
  12717. delete i;
  12718. });
  12719. });
  12720. // Echo headers endpoint for header-related tests
  12721. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12722. std::string body;
  12723. for (const auto &h : req.headers) {
  12724. body.append(h.first);
  12725. body.push_back(':');
  12726. body.append(h.second);
  12727. body.push_back('\n');
  12728. }
  12729. res.set_content(body, "text/plain");
  12730. });
  12731. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12732. std::string body;
  12733. for (const auto &h : req.headers) {
  12734. body.append(h.first);
  12735. body.push_back(':');
  12736. body.append(h.second);
  12737. body.push_back('\n');
  12738. }
  12739. res.set_content(body, "text/plain");
  12740. });
  12741. port_ = svr_.bind_to_any_port("127.0.0.1");
  12742. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12743. svr_.wait_until_ready();
  12744. }
  12745. void TearDown() override {
  12746. svr_.stop();
  12747. if (thread_.joinable()) thread_.join();
  12748. }
  12749. Server svr_;
  12750. std::thread thread_;
  12751. int port_ = 0;
  12752. };
  12753. TEST_F(OpenStreamTest, Basic) {
  12754. Client cli("127.0.0.1", port_);
  12755. auto handle = cli.open_stream("GET", "/hello");
  12756. EXPECT_TRUE(handle.is_valid());
  12757. EXPECT_EQ("Hello World!", read_all(handle));
  12758. }
  12759. TEST_F(OpenStreamTest, SmallBuffer) {
  12760. Client cli("127.0.0.1", port_);
  12761. auto handle = cli.open_stream("GET", "/hello");
  12762. std::string result;
  12763. char buf[4];
  12764. ssize_t n;
  12765. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12766. result.append(buf, static_cast<size_t>(n));
  12767. EXPECT_EQ("Hello World!", result);
  12768. }
  12769. TEST_F(OpenStreamTest, DefaultHeaders) {
  12770. Client cli("127.0.0.1", port_);
  12771. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12772. {
  12773. auto handle = cli.open_stream("GET", "/echo-headers");
  12774. ASSERT_TRUE(handle.is_valid());
  12775. auto body = read_all(handle);
  12776. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12777. std::string::npos);
  12778. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12779. std::string::npos);
  12780. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12781. }
  12782. // open_stream POST with body and no explicit content_type should NOT add
  12783. // text/plain Content-Type (behavior differs from non-streaming path), but
  12784. // should include Content-Length
  12785. {
  12786. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12787. ASSERT_TRUE(handle.is_valid());
  12788. auto body = read_all(handle);
  12789. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12790. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12791. }
  12792. // open_stream POST with explicit Content-Type should preserve it
  12793. {
  12794. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12795. {{"Content-Type", "application/custom"}},
  12796. "{}", "application/custom");
  12797. ASSERT_TRUE(handle.is_valid());
  12798. auto body = read_all(handle);
  12799. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12800. }
  12801. // User-specified User-Agent must not be overwritten for stream API
  12802. {
  12803. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12804. {{"User-Agent", "MyAgent/1.2"}});
  12805. ASSERT_TRUE(handle.is_valid());
  12806. auto body = read_all(handle);
  12807. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12808. }
  12809. }
  12810. TEST_F(OpenStreamTest, Large) {
  12811. Client cli("127.0.0.1", port_);
  12812. auto handle = cli.open_stream("GET", "/large");
  12813. EXPECT_EQ(10000u, read_all(handle).size());
  12814. }
  12815. TEST_F(OpenStreamTest, ConnectionError) {
  12816. Client cli("127.0.0.1", 9999);
  12817. auto handle = cli.open_stream("GET", "/hello");
  12818. EXPECT_FALSE(handle.is_valid());
  12819. }
  12820. TEST_F(OpenStreamTest, Chunked) {
  12821. Client cli("127.0.0.1", port_);
  12822. auto handle = cli.open_stream("GET", "/chunked");
  12823. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12824. "Transfer-Encoding") == "chunked");
  12825. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12826. }
  12827. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12828. Client cli("127.0.0.1", port_);
  12829. auto handle =
  12830. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12831. ASSERT_TRUE(handle.is_valid());
  12832. // Consume body to allow trailers to be received/parsed
  12833. auto body = read_all(handle);
  12834. // Explicitly parse trailers (ensure trailers are available for assertion)
  12835. handle.parse_trailers_if_needed();
  12836. EXPECT_EQ(std::string("123456789"), body);
  12837. // The response should include a Trailer header declaring both names
  12838. ASSERT_TRUE(handle.response);
  12839. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12840. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12841. handle.response->get_header_value("Trailer"));
  12842. // Prohibited trailer must not be present
  12843. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12844. // Allowed trailer should be present
  12845. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12846. EXPECT_EQ(std::string("yes"),
  12847. handle.response->get_trailer_value("X-Allowed"));
  12848. // Verify trailers are NOT present as regular headers
  12849. EXPECT_EQ(std::string(""),
  12850. handle.response->get_header_value("Content-Length"));
  12851. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12852. }
  12853. static std::thread serve_single_response(std::promise<int> &port_promise,
  12854. const std::string &response) {
  12855. return std::thread([&port_promise, response] {
  12856. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12857. default_socket_options(srv);
  12858. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12859. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12860. sockaddr_in addr{};
  12861. addr.sin_family = AF_INET;
  12862. addr.sin_port = htons(0); // Let OS assign a free port
  12863. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12864. int opt = 1;
  12865. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12866. #ifdef _WIN32
  12867. reinterpret_cast<const char *>(&opt),
  12868. #else
  12869. &opt,
  12870. #endif
  12871. sizeof(opt));
  12872. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12873. ::listen(srv, 1) != 0) {
  12874. port_promise.set_value(-1);
  12875. detail::close_socket(srv);
  12876. return;
  12877. }
  12878. socklen_t addr_len = sizeof(addr);
  12879. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12880. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12881. sockaddr_in cli_addr{};
  12882. socklen_t cli_len = sizeof(cli_addr);
  12883. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12884. if (cli != INVALID_SOCKET) {
  12885. // Read the complete HTTP request (until the blank line that terminates
  12886. // headers) before sending the response. If the server closes the socket
  12887. // while the client's request data is still unread in the kernel receive
  12888. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12889. // connection on both sides: it discards the client's receive buffer
  12890. // (which already holds our response) and causes any in-progress write on
  12891. // the client to fail with ECONNRESET. Reading all request data first
  12892. // ensures close() emits a graceful FIN.
  12893. {
  12894. char rbuf[256];
  12895. std::string req;
  12896. while (req.find("\r\n\r\n") == std::string::npos) {
  12897. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12898. if (n <= 0) { break; }
  12899. req.append(rbuf, static_cast<size_t>(n));
  12900. }
  12901. }
  12902. ::send(cli,
  12903. #ifdef _WIN32
  12904. static_cast<const char *>(response.c_str()),
  12905. static_cast<int>(response.size()),
  12906. #else
  12907. response.c_str(), response.size(),
  12908. #endif
  12909. 0);
  12910. detail::close_socket(cli);
  12911. }
  12912. detail::close_socket(srv);
  12913. });
  12914. }
  12915. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12916. #ifndef _WIN32
  12917. signal(SIGPIPE, SIG_IGN);
  12918. #endif
  12919. std::promise<int> port_promise;
  12920. auto port_future = port_promise.get_future();
  12921. auto server_thread =
  12922. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12923. "Content-Type: text/plain\r\n"
  12924. "Content-Length: not-a-number\r\n"
  12925. "Connection: close\r\n"
  12926. "\r\n"
  12927. "hello");
  12928. auto port = port_future.get();
  12929. ASSERT_GT(port, 0);
  12930. Client cli("127.0.0.1", port);
  12931. auto handle = cli.open_stream("GET", "/");
  12932. EXPECT_FALSE(handle.is_valid());
  12933. server_thread.join();
  12934. }
  12935. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12936. #ifndef _WIN32
  12937. signal(SIGPIPE, SIG_IGN);
  12938. #endif
  12939. std::promise<int> port_promise;
  12940. auto port_future = port_promise.get_future();
  12941. auto server_thread = serve_single_response(
  12942. port_promise, "HTTP/1.1 200 OK\r\n"
  12943. "Content-Type: text/plain\r\n"
  12944. "Content-Length: 99999999999999999999999999\r\n"
  12945. "Connection: close\r\n"
  12946. "\r\n"
  12947. "hello");
  12948. auto port = port_future.get();
  12949. ASSERT_GT(port, 0);
  12950. // Before the fix, std::stoull would throw std::out_of_range here and
  12951. // crash the process. After the fix, strtoull silently clamps to
  12952. // ULLONG_MAX so the stream opens without crashing. The important thing
  12953. // is that the process does NOT terminate.
  12954. Client cli("127.0.0.1", port);
  12955. auto handle = cli.open_stream("GET", "/");
  12956. EXPECT_TRUE(handle.is_valid());
  12957. server_thread.join();
  12958. }
  12959. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12960. TEST_F(OpenStreamTest, Gzip) {
  12961. Client cli("127.0.0.1", port_);
  12962. auto handle = cli.open_stream("GET", "/compressible", {},
  12963. {{"Accept-Encoding", "gzip"}});
  12964. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12965. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12966. }
  12967. #endif
  12968. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12969. TEST_F(OpenStreamTest, Brotli) {
  12970. Client cli("127.0.0.1", port_);
  12971. auto handle =
  12972. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12973. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12974. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12975. }
  12976. #endif
  12977. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12978. TEST_F(OpenStreamTest, Zstd) {
  12979. Client cli("127.0.0.1", port_);
  12980. auto handle = cli.open_stream("GET", "/compressible", {},
  12981. {{"Accept-Encoding", "zstd"}});
  12982. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12983. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12984. }
  12985. #endif
  12986. #ifdef CPPHTTPLIB_SSL_ENABLED
  12987. class SSLOpenStreamTest : public ::testing::Test {
  12988. protected:
  12989. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12990. void SetUp() override {
  12991. svr_.Get("/hello", [](const Request &, Response &res) {
  12992. res.set_content("Hello SSL World!", "text/plain");
  12993. });
  12994. svr_.Get("/chunked", [](const Request &, Response &res) {
  12995. res.set_chunked_content_provider("text/plain",
  12996. [](size_t offset, DataSink &sink) {
  12997. if (offset < 15) {
  12998. sink.write("chunk", 5);
  12999. return true;
  13000. }
  13001. sink.done();
  13002. return true;
  13003. });
  13004. });
  13005. svr_.Post("/echo", [](const Request &req, Response &res) {
  13006. res.set_content(req.body, req.get_header_value("Content-Type"));
  13007. });
  13008. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13009. std::string body = req.body;
  13010. res.set_chunked_content_provider(
  13011. "text/plain", [body](size_t offset, DataSink &sink) {
  13012. if (offset < body.size()) {
  13013. sink.write(body.data() + offset, body.size() - offset);
  13014. }
  13015. sink.done();
  13016. return true;
  13017. });
  13018. });
  13019. port_ = svr_.bind_to_any_port("127.0.0.1");
  13020. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13021. svr_.wait_until_ready();
  13022. }
  13023. void TearDown() override {
  13024. svr_.stop();
  13025. if (thread_.joinable()) thread_.join();
  13026. }
  13027. SSLServer svr_;
  13028. std::thread thread_;
  13029. int port_ = 0;
  13030. };
  13031. TEST_F(SSLOpenStreamTest, Basic) {
  13032. SSLClient cli("127.0.0.1", port_);
  13033. cli.enable_server_certificate_verification(false);
  13034. auto handle = cli.open_stream("GET", "/hello");
  13035. ASSERT_TRUE(handle.is_valid());
  13036. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13037. }
  13038. TEST_F(SSLOpenStreamTest, Chunked) {
  13039. SSLClient cli("127.0.0.1", port_);
  13040. cli.enable_server_certificate_verification(false);
  13041. auto handle = cli.open_stream("GET", "/chunked");
  13042. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13043. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13044. "Transfer-Encoding") == "chunked");
  13045. auto body = read_all(handle);
  13046. EXPECT_EQ("chunkchunkchunk", body);
  13047. }
  13048. TEST_F(SSLOpenStreamTest, Post) {
  13049. SSLClient cli("127.0.0.1", port_);
  13050. cli.enable_server_certificate_verification(false);
  13051. auto handle =
  13052. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13053. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13054. EXPECT_EQ(200, handle.response->status);
  13055. auto body = read_all(handle);
  13056. EXPECT_EQ("Hello SSL POST", body);
  13057. }
  13058. TEST_F(SSLOpenStreamTest, PostChunked) {
  13059. SSLClient cli("127.0.0.1", port_);
  13060. cli.enable_server_certificate_verification(false);
  13061. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13062. "Chunked SSL Data", "text/plain");
  13063. ASSERT_TRUE(handle.is_valid());
  13064. EXPECT_EQ(200, handle.response->status);
  13065. auto body = read_all(handle);
  13066. EXPECT_EQ("Chunked SSL Data", body);
  13067. }
  13068. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13069. // Content-Length is terminated by the server closing the connection. When the
  13070. // SSL peer sends a close_notify after the body, the client must treat it as a
  13071. // clean EOF and return a successful response rather than an error.
  13072. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13074. ASSERT_TRUE(svr.is_valid());
  13075. svr.set_keep_alive_max_count(1);
  13076. const std::string expected_body = "Hello from connection-close response!";
  13077. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13078. res.set_content_provider("text/plain",
  13079. [&](size_t offset, DataSink &sink) -> bool {
  13080. if (offset < expected_body.size()) {
  13081. sink.write(expected_body.data() + offset,
  13082. expected_body.size() - offset);
  13083. }
  13084. sink.done();
  13085. return true;
  13086. });
  13087. });
  13088. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13089. auto se = detail::scope_exit([&] {
  13090. svr.stop();
  13091. listen_thread.join();
  13092. ASSERT_FALSE(svr.is_running());
  13093. });
  13094. svr.wait_until_ready();
  13095. SSLClient cli(HOST, PORT);
  13096. cli.enable_server_certificate_verification(false);
  13097. auto res = cli.Get("/no-content-length");
  13098. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13099. EXPECT_EQ(StatusCode::OK_200, res->status);
  13100. EXPECT_EQ(expected_body, res->body);
  13101. }
  13102. #endif // CPPHTTPLIB_SSL_ENABLED
  13103. //==============================================================================
  13104. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13105. // results for various scenarios.
  13106. //==============================================================================
  13107. TEST(ParityTest, GetVsOpenStream) {
  13108. Server svr;
  13109. const std::string path = "/parity";
  13110. const std::string content = "Parity test content: hello world";
  13111. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13112. res.set_content(content, "text/plain");
  13113. });
  13114. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13115. auto se = detail::scope_exit([&] {
  13116. svr.stop();
  13117. t.join();
  13118. ASSERT_FALSE(svr.is_running());
  13119. });
  13120. svr.wait_until_ready();
  13121. Client cli(HOST, PORT);
  13122. // Non-stream path
  13123. auto r1 = cli.Get(path);
  13124. ASSERT_TRUE(r1);
  13125. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13126. // Stream path
  13127. auto h = cli.open_stream("GET", path);
  13128. ASSERT_TRUE(h.is_valid());
  13129. EXPECT_EQ(r1->body, read_all(h));
  13130. }
  13131. // Helper to compress data with provided compressor type T
  13132. template <typename Compressor>
  13133. static std::string compress_payload_for_parity(const std::string &in) {
  13134. std::string out;
  13135. Compressor compressor;
  13136. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13137. [&](const char *data, size_t n) {
  13138. out.append(data, n);
  13139. return true;
  13140. });
  13141. EXPECT_TRUE(ok);
  13142. return out;
  13143. }
  13144. // Helper function for compression parity tests
  13145. template <typename Compressor>
  13146. static void test_compression_parity(const std::string &original,
  13147. const std::string &path,
  13148. const std::string &encoding) {
  13149. const std::string compressed =
  13150. compress_payload_for_parity<Compressor>(original);
  13151. Server svr;
  13152. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13153. res.set_content(compressed, "application/octet-stream");
  13154. res.set_header("Content-Encoding", encoding);
  13155. });
  13156. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13157. auto se = detail::scope_exit([&] {
  13158. svr.stop();
  13159. t.join();
  13160. ASSERT_FALSE(svr.is_running());
  13161. });
  13162. svr.wait_until_ready();
  13163. Client cli(HOST, PORT);
  13164. // Non-streaming
  13165. {
  13166. auto res = cli.Get(path);
  13167. ASSERT_TRUE(res);
  13168. EXPECT_EQ(StatusCode::OK_200, res->status);
  13169. EXPECT_EQ(original, res->body);
  13170. }
  13171. // Streaming
  13172. {
  13173. auto h = cli.open_stream("GET", path);
  13174. ASSERT_TRUE(h.is_valid());
  13175. EXPECT_EQ(original, read_all(h));
  13176. }
  13177. }
  13178. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13179. TEST(ParityTest, Gzip) {
  13180. test_compression_parity<detail::gzip_compressor>(
  13181. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13182. }
  13183. #endif
  13184. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13185. TEST(ParityTest, Brotli) {
  13186. test_compression_parity<detail::brotli_compressor>(
  13187. "Hello, brotli parity test payload", "/parity-br", "br");
  13188. }
  13189. #endif
  13190. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13191. TEST(ParityTest, Zstd) {
  13192. test_compression_parity<detail::zstd_compressor>(
  13193. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13194. }
  13195. #endif
  13196. //==============================================================================
  13197. // New Stream API Tests
  13198. //==============================================================================
  13199. inline std::string read_body(httplib::stream::Result &result) {
  13200. std::string body;
  13201. while (result.next()) {
  13202. body.append(result.data(), result.size());
  13203. }
  13204. return body;
  13205. }
  13206. TEST(ClientConnectionTest, Basic) {
  13207. httplib::ClientConnection conn;
  13208. EXPECT_FALSE(conn.is_open());
  13209. conn.sock = 1;
  13210. EXPECT_TRUE(conn.is_open());
  13211. httplib::ClientConnection conn2(std::move(conn));
  13212. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13213. conn2.sock = INVALID_SOCKET;
  13214. }
  13215. // Unified test server for all stream::* tests
  13216. class StreamApiTest : public ::testing::Test {
  13217. protected:
  13218. void SetUp() override {
  13219. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13220. res.set_content("Hello World!", "text/plain");
  13221. });
  13222. svr_.Get("/echo-params",
  13223. [](const httplib::Request &req, httplib::Response &res) {
  13224. std::string r;
  13225. for (const auto &p : req.params) {
  13226. if (!r.empty()) r += "&";
  13227. r += p.first + "=" + p.second;
  13228. }
  13229. res.set_content(r, "text/plain");
  13230. });
  13231. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13232. res.set_content(req.body, req.get_header_value("Content-Type"));
  13233. });
  13234. svr_.Post("/echo-headers",
  13235. [](const httplib::Request &req, httplib::Response &res) {
  13236. std::string r;
  13237. for (const auto &h : req.headers)
  13238. r += h.first + ": " + h.second + "\n";
  13239. res.set_content(r, "text/plain");
  13240. });
  13241. svr_.Post("/echo-params",
  13242. [](const httplib::Request &req, httplib::Response &res) {
  13243. std::string r = "params:";
  13244. for (const auto &p : req.params)
  13245. r += p.first + "=" + p.second + ";";
  13246. res.set_content(r + " body:" + req.body, "text/plain");
  13247. });
  13248. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13249. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13250. });
  13251. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13252. res.set_content("PUT:" + req.body, "text/plain");
  13253. });
  13254. svr_.Patch("/echo",
  13255. [](const httplib::Request &req, httplib::Response &res) {
  13256. res.set_content("PATCH:" + req.body, "text/plain");
  13257. });
  13258. svr_.Delete(
  13259. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13260. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13261. "text/plain");
  13262. });
  13263. svr_.Get("/head-test",
  13264. [](const httplib::Request &, httplib::Response &res) {
  13265. res.set_content("body for HEAD", "text/plain");
  13266. });
  13267. svr_.Options("/options",
  13268. [](const httplib::Request &, httplib::Response &res) {
  13269. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13270. });
  13271. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13272. svr_.wait_until_ready();
  13273. }
  13274. void TearDown() override {
  13275. svr_.stop();
  13276. if (thread_.joinable()) thread_.join();
  13277. }
  13278. httplib::Server svr_;
  13279. std::thread thread_;
  13280. };
  13281. // stream::Get tests
  13282. TEST_F(StreamApiTest, GetBasic) {
  13283. httplib::Client cli(HOST, PORT);
  13284. auto result = httplib::stream::Get(cli, "/hello");
  13285. ASSERT_TRUE(result.is_valid());
  13286. EXPECT_EQ(200, result.status());
  13287. EXPECT_EQ("Hello World!", read_body(result));
  13288. }
  13289. TEST_F(StreamApiTest, GetWithParams) {
  13290. httplib::Client cli(HOST, PORT);
  13291. httplib::Params params{{"foo", "bar"}};
  13292. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13293. ASSERT_TRUE(result.is_valid());
  13294. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13295. }
  13296. TEST_F(StreamApiTest, GetConnectionError) {
  13297. httplib::Client cli(HOST, 9999);
  13298. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13299. }
  13300. TEST_F(StreamApiTest, Get404) {
  13301. httplib::Client cli(HOST, PORT);
  13302. auto result = httplib::stream::Get(cli, "/nonexistent");
  13303. EXPECT_TRUE(result.is_valid());
  13304. EXPECT_EQ(404, result.status());
  13305. }
  13306. // stream::Post tests
  13307. TEST_F(StreamApiTest, PostBasic) {
  13308. httplib::Client cli(HOST, PORT);
  13309. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13310. "application/json");
  13311. ASSERT_TRUE(result.is_valid());
  13312. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13313. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13314. }
  13315. TEST_F(StreamApiTest, PostWithHeaders) {
  13316. httplib::Client cli(HOST, PORT);
  13317. httplib::Headers headers{{"X-Custom", "value"}};
  13318. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13319. "text/plain");
  13320. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13321. }
  13322. TEST_F(StreamApiTest, PostWithParams) {
  13323. httplib::Client cli(HOST, PORT);
  13324. httplib::Params params{{"k", "v"}};
  13325. auto result =
  13326. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13327. auto body = read_body(result);
  13328. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13329. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13330. }
  13331. TEST_F(StreamApiTest, PostLarge) {
  13332. httplib::Client cli(HOST, PORT);
  13333. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13334. size_t total = 0;
  13335. while (result.next()) {
  13336. total += result.size();
  13337. }
  13338. EXPECT_EQ(100u * 1024u, total);
  13339. }
  13340. // stream::Put/Patch tests
  13341. TEST_F(StreamApiTest, PutAndPatch) {
  13342. httplib::Client cli(HOST, PORT);
  13343. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13344. EXPECT_EQ("PUT:test", read_body(put));
  13345. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13346. EXPECT_EQ("PATCH:test", read_body(patch));
  13347. }
  13348. // stream::Delete tests
  13349. TEST_F(StreamApiTest, Delete) {
  13350. httplib::Client cli(HOST, PORT);
  13351. auto del1 = httplib::stream::Delete(cli, "/resource");
  13352. EXPECT_EQ("Deleted", read_body(del1));
  13353. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13354. EXPECT_EQ("Deleted:data", read_body(del2));
  13355. }
  13356. // stream::Head/Options tests
  13357. TEST_F(StreamApiTest, HeadAndOptions) {
  13358. httplib::Client cli(HOST, PORT);
  13359. auto head = httplib::stream::Head(cli, "/head-test");
  13360. EXPECT_TRUE(head.is_valid());
  13361. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13362. auto opts = httplib::stream::Options(cli, "/options");
  13363. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13364. }
  13365. // SSL stream::* tests
  13366. #ifdef CPPHTTPLIB_SSL_ENABLED
  13367. class SSLStreamApiTest : public ::testing::Test {
  13368. protected:
  13369. void SetUp() override {
  13370. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13371. res.set_content("Hello SSL!", "text/plain");
  13372. });
  13373. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13374. res.set_content(req.body, "text/plain");
  13375. });
  13376. port_ = svr_.bind_to_any_port("127.0.0.1");
  13377. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13378. svr_.wait_until_ready();
  13379. }
  13380. void TearDown() override {
  13381. svr_.stop();
  13382. if (thread_.joinable()) thread_.join();
  13383. }
  13384. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13385. std::thread thread_;
  13386. int port_ = 0;
  13387. };
  13388. TEST_F(SSLStreamApiTest, GetAndPost) {
  13389. httplib::SSLClient cli("127.0.0.1", port_);
  13390. cli.enable_server_certificate_verification(false);
  13391. auto get = httplib::stream::Get(cli, "/hello");
  13392. EXPECT_EQ("Hello SSL!", read_body(get));
  13393. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13394. EXPECT_EQ("test", read_body(post));
  13395. }
  13396. #endif
  13397. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13398. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13399. // BodyReader
  13400. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13401. // Test that read timeout during streaming is detected
  13402. // Use a large content-length response where server delays mid-stream
  13403. Server svr;
  13404. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13405. // Send a large response with delay in the middle
  13406. res.set_content_provider(
  13407. 1000, // content_length
  13408. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13409. if (offset < 100) {
  13410. // Send first 100 bytes immediately
  13411. std::string data(100, 'A');
  13412. sink.write(data.c_str(), data.size());
  13413. return true;
  13414. }
  13415. // Then delay longer than client timeout
  13416. std::this_thread::sleep_for(std::chrono::seconds(3));
  13417. std::string data(900, 'B');
  13418. sink.write(data.c_str(), data.size());
  13419. return true;
  13420. });
  13421. });
  13422. auto port = 8091;
  13423. std::thread t([&]() { svr.listen("localhost", port); });
  13424. svr.wait_until_ready();
  13425. Client cli("localhost", port);
  13426. cli.set_read_timeout(1, 0); // 1 second timeout
  13427. auto handle = cli.open_stream("GET", "/slow-stream");
  13428. ASSERT_TRUE(handle.is_valid());
  13429. char buf[256];
  13430. ssize_t total = 0;
  13431. ssize_t n;
  13432. bool got_error = false;
  13433. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13434. total += n;
  13435. }
  13436. if (n < 0) {
  13437. got_error = true;
  13438. // Should be timeout or read error
  13439. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13440. handle.get_read_error() == Error::Read)
  13441. << "Actual error: " << to_string(handle.get_read_error());
  13442. }
  13443. // Either we got an error, or we got less data than expected
  13444. EXPECT_TRUE(got_error || total < 1000)
  13445. << "Expected timeout but got all " << total << " bytes";
  13446. svr.stop();
  13447. t.join();
  13448. }
  13449. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13450. // Test connection closed detection via BodyReader
  13451. Server svr;
  13452. std::atomic<bool> close_now{false};
  13453. svr.Get("/will-close", [&](const Request &, Response &res) {
  13454. res.set_content_provider(
  13455. 10000, // Large content_length that we won't fully send
  13456. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13457. if (offset < 100) {
  13458. std::string data(100, 'X');
  13459. sink.write(data.c_str(), data.size());
  13460. return true;
  13461. }
  13462. // Wait for signal then abort
  13463. while (!close_now) {
  13464. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13465. }
  13466. return false; // Abort - server will close connection
  13467. });
  13468. });
  13469. auto port = 8092;
  13470. std::thread t([&]() { svr.listen("localhost", port); });
  13471. svr.wait_until_ready();
  13472. Client cli("localhost", port);
  13473. auto handle = cli.open_stream("GET", "/will-close");
  13474. ASSERT_TRUE(handle.is_valid());
  13475. char buf[256];
  13476. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13477. EXPECT_GT(n, 0) << "First read should succeed";
  13478. // Signal server to close
  13479. close_now = true;
  13480. // Keep reading until error or EOF
  13481. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13482. // Keep reading
  13483. }
  13484. // Should get an error since content_length wasn't satisfied
  13485. if (n < 0) {
  13486. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13487. handle.get_read_error() == Error::Read)
  13488. << "Actual error: " << to_string(handle.get_read_error());
  13489. }
  13490. svr.stop();
  13491. t.join();
  13492. }
  13493. #ifdef CPPHTTPLIB_SSL_ENABLED
  13494. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13495. // Test that read timeout during SSL streaming is detected
  13496. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13497. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13498. res.set_content_provider(
  13499. 1000, "text/plain",
  13500. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13501. if (offset < 100) {
  13502. std::string data(100, 'A');
  13503. sink.write(data.c_str(), data.size());
  13504. return true;
  13505. }
  13506. std::this_thread::sleep_for(std::chrono::seconds(3));
  13507. std::string data(900, 'B');
  13508. sink.write(data.c_str(), data.size());
  13509. return true;
  13510. });
  13511. });
  13512. auto port = 8093;
  13513. std::thread t([&]() { svr.listen("localhost", port); });
  13514. svr.wait_until_ready();
  13515. SSLClient cli("localhost", port);
  13516. cli.enable_server_certificate_verification(false);
  13517. cli.set_read_timeout(1, 0); // 1 second timeout
  13518. auto handle = cli.open_stream("GET", "/slow-stream");
  13519. ASSERT_TRUE(handle.is_valid());
  13520. char buf[256];
  13521. ssize_t total = 0;
  13522. ssize_t n;
  13523. bool got_error = false;
  13524. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13525. total += n;
  13526. }
  13527. if (n < 0) {
  13528. got_error = true;
  13529. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13530. handle.get_read_error() == Error::Read)
  13531. << "Actual error: " << to_string(handle.get_read_error());
  13532. }
  13533. EXPECT_TRUE(got_error || total < 1000)
  13534. << "Expected timeout but got all " << total << " bytes";
  13535. svr.stop();
  13536. t.join();
  13537. }
  13538. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13539. // Test SSL connection closed detection
  13540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13541. std::atomic<bool> close_now{false};
  13542. svr.Get("/will-close", [&](const Request &, Response &res) {
  13543. res.set_content_provider(
  13544. 10000, "text/plain",
  13545. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13546. if (offset < 100) {
  13547. std::string data(100, 'X');
  13548. sink.write(data.c_str(), data.size());
  13549. return true;
  13550. }
  13551. while (!close_now) {
  13552. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13553. }
  13554. return false;
  13555. });
  13556. });
  13557. auto port = 8094;
  13558. std::thread t([&]() { svr.listen("localhost", port); });
  13559. svr.wait_until_ready();
  13560. SSLClient cli("localhost", port);
  13561. cli.enable_server_certificate_verification(false);
  13562. auto handle = cli.open_stream("GET", "/will-close");
  13563. ASSERT_TRUE(handle.is_valid());
  13564. char buf[256];
  13565. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13566. EXPECT_GT(n, 0);
  13567. // Signal server to close
  13568. close_now = true;
  13569. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13570. // Keep reading
  13571. }
  13572. if (n < 0) {
  13573. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13574. handle.get_read_error() == Error::Read)
  13575. << "Actual error: " << to_string(handle.get_read_error());
  13576. }
  13577. svr.stop();
  13578. t.join();
  13579. }
  13580. #endif
  13581. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13582. using namespace httplib;
  13583. // Create a test file
  13584. const char *fname = "etag_testfile.txt";
  13585. const char *content = "etag-content";
  13586. {
  13587. std::ofstream ofs(fname);
  13588. ofs << content;
  13589. ASSERT_TRUE(ofs.good());
  13590. }
  13591. Server svr;
  13592. svr.set_mount_point("/static", ".");
  13593. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13594. svr.wait_until_ready();
  13595. Client cli(HOST, PORT);
  13596. // First request: should get 200 with ETag header
  13597. auto res1 = cli.Get("/static/etag_testfile.txt");
  13598. ASSERT_TRUE(res1);
  13599. ASSERT_EQ(200, res1->status);
  13600. ASSERT_TRUE(res1->has_header("ETag"));
  13601. std::string etag = res1->get_header_value("ETag");
  13602. EXPECT_FALSE(etag.empty());
  13603. // Verify ETag format: W/"hex-hex"
  13604. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13605. EXPECT_EQ('W', etag[0]);
  13606. EXPECT_EQ('/', etag[1]);
  13607. EXPECT_EQ('"', etag[2]);
  13608. EXPECT_EQ('"', etag.back());
  13609. // Exact match: expect 304 Not Modified
  13610. Headers h2 = {{"If-None-Match", etag}};
  13611. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13612. ASSERT_TRUE(res2);
  13613. EXPECT_EQ(304, res2->status);
  13614. // Wildcard match: expect 304 Not Modified
  13615. Headers h3 = {{"If-None-Match", "*"}};
  13616. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13617. ASSERT_TRUE(res3);
  13618. EXPECT_EQ(304, res3->status);
  13619. // Non-matching ETag: expect 200
  13620. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13621. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13622. ASSERT_TRUE(res4);
  13623. EXPECT_EQ(200, res4->status);
  13624. // Multiple ETags with one matching: expect 304
  13625. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13626. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13627. ASSERT_TRUE(res5);
  13628. EXPECT_EQ(304, res5->status);
  13629. svr.stop();
  13630. t.join();
  13631. std::remove(fname);
  13632. }
  13633. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13634. using namespace httplib;
  13635. Server svr;
  13636. svr.set_mount_point("/static", ".");
  13637. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13638. svr.wait_until_ready();
  13639. Client cli(HOST, PORT);
  13640. // Send If-None-Match: * to a non-existent file
  13641. Headers h = {{"If-None-Match", "*"}};
  13642. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13643. ASSERT_TRUE(res);
  13644. EXPECT_EQ(404, res->status);
  13645. svr.stop();
  13646. t.join();
  13647. }
  13648. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13649. using namespace httplib;
  13650. // Create a test file
  13651. const char *fname = "etag_boundary_testfile.txt";
  13652. const char *content = "boundary-test";
  13653. {
  13654. std::ofstream ofs(fname);
  13655. ofs << content;
  13656. ASSERT_TRUE(ofs.good());
  13657. }
  13658. Server svr;
  13659. svr.set_mount_point("/static", ".");
  13660. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13661. svr.wait_until_ready();
  13662. Client cli(HOST, PORT);
  13663. // Get the actual ETag
  13664. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13665. ASSERT_TRUE(res1);
  13666. ASSERT_EQ(200, res1->status);
  13667. ASSERT_TRUE(res1->has_header("ETag"));
  13668. std::string etag = res1->get_header_value("ETag");
  13669. // Test 1: Very long ETag value (longer than actual ETag)
  13670. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13671. Headers h1 = {{"If-None-Match", "W/"
  13672. "\"very-long-etag-value-that-is-much-longer-"
  13673. "than-the-actual-etag-value\""}};
  13674. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13675. ASSERT_TRUE(res2);
  13676. EXPECT_EQ(200, res2->status); // Should not match
  13677. // Test 2: Long string followed by wildcard
  13678. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13679. // string)
  13680. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13681. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13682. ASSERT_TRUE(res3);
  13683. EXPECT_EQ(304, res3->status); // Should match on "*"
  13684. // Test 3: Wildcard followed by long string
  13685. // Should match on "*" immediately and return 304
  13686. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13687. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13688. ASSERT_TRUE(res4);
  13689. EXPECT_EQ(304, res4->status); // Should match on "*"
  13690. // Test 4: Multiple long non-matching values
  13691. // Should NOT match and return 200 (test that all comparisons are safe)
  13692. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13693. "W/\"second-long-non-matching-value\", "
  13694. "W/\"third-long-non-matching-value\""}};
  13695. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13696. ASSERT_TRUE(res5);
  13697. EXPECT_EQ(200, res5->status); // Should not match
  13698. // Test 5: Single character that is not "*" (edge case)
  13699. Headers h5 = {{"If-None-Match", "X"}};
  13700. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13701. ASSERT_TRUE(res6);
  13702. EXPECT_EQ(200, res6->status); // Should not match
  13703. svr.stop();
  13704. t.join();
  13705. std::remove(fname);
  13706. }
  13707. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13708. using namespace httplib;
  13709. // Create a test file
  13710. const char *fname = "ims_testfile.txt";
  13711. const char *content = "if-modified-since-test";
  13712. {
  13713. std::ofstream ofs(fname);
  13714. ofs << content;
  13715. ASSERT_TRUE(ofs.good());
  13716. }
  13717. Server svr;
  13718. svr.set_mount_point("/static", ".");
  13719. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13720. svr.wait_until_ready();
  13721. Client cli(HOST, PORT);
  13722. // First request: should get 200 with Last-Modified header
  13723. auto res1 = cli.Get("/static/ims_testfile.txt");
  13724. ASSERT_TRUE(res1);
  13725. ASSERT_EQ(200, res1->status);
  13726. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13727. std::string last_modified = res1->get_header_value("Last-Modified");
  13728. EXPECT_FALSE(last_modified.empty());
  13729. // If-Modified-Since with same time: expect 304
  13730. Headers h2 = {{"If-Modified-Since", last_modified}};
  13731. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13732. ASSERT_TRUE(res2);
  13733. EXPECT_EQ(304, res2->status);
  13734. // If-Modified-Since with future time: expect 304
  13735. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13736. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13737. ASSERT_TRUE(res3);
  13738. EXPECT_EQ(304, res3->status);
  13739. // If-Modified-Since with past time: expect 200
  13740. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13741. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13742. ASSERT_TRUE(res4);
  13743. EXPECT_EQ(200, res4->status);
  13744. // If-None-Match takes precedence over If-Modified-Since
  13745. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13746. ASSERT_TRUE(res1->has_header("ETag"));
  13747. std::string etag = res1->get_header_value("ETag");
  13748. Headers h5 = {{"If-None-Match", etag},
  13749. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13750. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13751. ASSERT_TRUE(res5);
  13752. EXPECT_EQ(304, res5->status);
  13753. svr.stop();
  13754. t.join();
  13755. std::remove(fname);
  13756. }
  13757. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13758. using namespace httplib;
  13759. Server svr;
  13760. // Endpoint that returns compressible content
  13761. svr.Get("/compressible", [](const Request &, Response &res) {
  13762. // Return a large enough body to trigger compression
  13763. std::string body(1000, 'a');
  13764. res.set_content(body, "text/plain");
  13765. });
  13766. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13767. svr.wait_until_ready();
  13768. Client cli(HOST, PORT);
  13769. // Request with gzip support: should get Vary header when compressed
  13770. cli.set_compress(true);
  13771. auto res1 = cli.Get("/compressible");
  13772. ASSERT_TRUE(res1);
  13773. EXPECT_EQ(200, res1->status);
  13774. // If Content-Encoding is set, Vary should also be set
  13775. if (res1->has_header("Content-Encoding")) {
  13776. EXPECT_TRUE(res1->has_header("Vary"));
  13777. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13778. }
  13779. // Request without Accept-Encoding header: should not have compression
  13780. Headers h_no_compress;
  13781. auto res2 = cli.Get("/compressible", h_no_compress);
  13782. ASSERT_TRUE(res2);
  13783. EXPECT_EQ(200, res2->status);
  13784. // Verify Vary header is present when compression is applied
  13785. // (the exact behavior depends on server configuration)
  13786. svr.stop();
  13787. t.join();
  13788. }
  13789. TEST(ETagTest, IfRangeWithETag) {
  13790. using namespace httplib;
  13791. // Create a test file with known content
  13792. const char *fname = "if_range_testfile.txt";
  13793. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13794. {
  13795. std::ofstream ofs(fname);
  13796. ofs << content;
  13797. ASSERT_TRUE(ofs.good());
  13798. }
  13799. Server svr;
  13800. svr.set_mount_point("/static", ".");
  13801. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13802. svr.wait_until_ready();
  13803. Client cli(HOST, PORT);
  13804. // First request: get ETag
  13805. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13806. ASSERT_TRUE(res1);
  13807. ASSERT_EQ(200, res1->status);
  13808. ASSERT_TRUE(res1->has_header("ETag"));
  13809. std::string etag = res1->get_header_value("ETag");
  13810. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13811. // Since our server generates weak ETags (W/"..."), If-Range with our
  13812. // ETag should NOT result in partial content - it should return full content.
  13813. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13814. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13815. ASSERT_TRUE(res2);
  13816. // Weak ETag in If-Range -> full content (200), not partial (206)
  13817. EXPECT_EQ(200, res2->status);
  13818. EXPECT_EQ(content, res2->body);
  13819. EXPECT_FALSE(res2->has_header("Content-Range"));
  13820. // Range request with non-matching If-Range (ETag): should get 200 (full
  13821. // content)
  13822. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13823. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13824. ASSERT_TRUE(res3);
  13825. EXPECT_EQ(200, res3->status);
  13826. EXPECT_EQ(content, res3->body);
  13827. EXPECT_FALSE(res3->has_header("Content-Range"));
  13828. // Range request with strong ETag (hypothetical - our server doesn't generate
  13829. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13830. // should return full content)
  13831. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13832. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13833. ASSERT_TRUE(res4);
  13834. EXPECT_EQ(200, res4->status);
  13835. EXPECT_EQ(content, res4->body);
  13836. EXPECT_FALSE(res4->has_header("Content-Range"));
  13837. svr.stop();
  13838. t.join();
  13839. std::remove(fname);
  13840. }
  13841. TEST(ETagTest, IfRangeWithDate) {
  13842. using namespace httplib;
  13843. // Create a test file
  13844. const char *fname = "if_range_date_testfile.txt";
  13845. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13846. {
  13847. std::ofstream ofs(fname);
  13848. ofs << content;
  13849. ASSERT_TRUE(ofs.good());
  13850. }
  13851. Server svr;
  13852. svr.set_mount_point("/static", ".");
  13853. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13854. svr.wait_until_ready();
  13855. Client cli(HOST, PORT);
  13856. // First request: get Last-Modified
  13857. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13858. ASSERT_TRUE(res1);
  13859. ASSERT_EQ(200, res1->status);
  13860. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13861. std::string last_modified = res1->get_header_value("Last-Modified");
  13862. // Range request with matching If-Range (date): should get 206
  13863. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13864. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13865. ASSERT_TRUE(res2);
  13866. EXPECT_EQ(206, res2->status);
  13867. EXPECT_EQ("FGHIJ", res2->body);
  13868. // Range request with old If-Range date: should get 200 (full content)
  13869. Headers h3 = {{"Range", "bytes=5-9"},
  13870. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13871. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13872. ASSERT_TRUE(res3);
  13873. EXPECT_EQ(200, res3->status);
  13874. EXPECT_EQ(content, res3->body);
  13875. // Range request with future If-Range date: should get 206
  13876. Headers h4 = {{"Range", "bytes=0-4"},
  13877. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13878. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13879. ASSERT_TRUE(res4);
  13880. EXPECT_EQ(206, res4->status);
  13881. EXPECT_EQ("ABCDE", res4->body);
  13882. svr.stop();
  13883. t.join();
  13884. std::remove(fname);
  13885. }
  13886. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13887. using namespace httplib;
  13888. const char *fname = "etag_malformed.txt";
  13889. const char *content = "malformed-etag";
  13890. {
  13891. std::ofstream ofs(fname);
  13892. ofs << content;
  13893. ASSERT_TRUE(ofs.good());
  13894. }
  13895. Server svr;
  13896. svr.set_mount_point("/static", ".");
  13897. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13898. svr.wait_until_ready();
  13899. Client cli(HOST, PORT);
  13900. // baseline: should get 200 and an ETag
  13901. auto res1 = cli.Get("/static/etag_malformed.txt");
  13902. ASSERT_TRUE(res1);
  13903. ASSERT_EQ(200, res1->status);
  13904. ASSERT_TRUE(res1->has_header("ETag"));
  13905. // Malformed ETag value (missing quotes) should be treated as non-matching
  13906. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13907. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13908. ASSERT_TRUE(res_bad);
  13909. EXPECT_EQ(200, res_bad->status);
  13910. // Whitespace-only header value should be considered invalid / non-matching
  13911. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13912. "Host: localhost\r\n"
  13913. "If-None-Match: \r\n"
  13914. "Connection: close\r\n"
  13915. "\r\n";
  13916. std::string out;
  13917. ASSERT_TRUE(send_request(5, raw_req, &out));
  13918. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13919. svr.stop();
  13920. t.join();
  13921. std::remove(fname);
  13922. }
  13923. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13924. using namespace httplib;
  13925. const char *fname = "ims_invalid_format.txt";
  13926. const char *content = "ims-bad-format";
  13927. {
  13928. std::ofstream ofs(fname);
  13929. ofs << content;
  13930. ASSERT_TRUE(ofs.good());
  13931. }
  13932. Server svr;
  13933. svr.set_mount_point("/static", ".");
  13934. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13935. svr.wait_until_ready();
  13936. Client cli(HOST, PORT);
  13937. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13938. ASSERT_TRUE(res1);
  13939. ASSERT_EQ(200, res1->status);
  13940. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13941. // If-Modified-Since with invalid format should not result in 304
  13942. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13943. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13944. ASSERT_TRUE(res_bad);
  13945. EXPECT_EQ(200, res_bad->status);
  13946. // If-Range with invalid date format should be treated as mismatch -> full
  13947. // content (200)
  13948. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13949. {"If-Range", "invalid-date"}};
  13950. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13951. ASSERT_TRUE(res_ifrange);
  13952. EXPECT_EQ(200, res_ifrange->status);
  13953. svr.stop();
  13954. t.join();
  13955. std::remove(fname);
  13956. }
  13957. TEST(ETagTest, IfRangeWithMalformedETag) {
  13958. using namespace httplib;
  13959. const char *fname = "ifrange_malformed.txt";
  13960. const std::string content = "0123456789";
  13961. {
  13962. std::ofstream ofs(fname);
  13963. ofs << content;
  13964. ASSERT_TRUE(ofs.good());
  13965. }
  13966. Server svr;
  13967. svr.set_mount_point("/static", ".");
  13968. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13969. svr.wait_until_ready();
  13970. Client cli(HOST, PORT);
  13971. // First request: get ETag
  13972. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13973. ASSERT_TRUE(res1);
  13974. ASSERT_EQ(200, res1->status);
  13975. ASSERT_TRUE(res1->has_header("ETag"));
  13976. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13977. // full content (200)
  13978. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13979. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13980. ASSERT_TRUE(res2);
  13981. EXPECT_EQ(200, res2->status);
  13982. EXPECT_EQ(content, res2->body);
  13983. svr.stop();
  13984. t.join();
  13985. std::remove(fname);
  13986. }
  13987. TEST(ETagTest, ExtremeLargeDateValues) {
  13988. using namespace httplib;
  13989. const char *fname = "ims_extreme_date.txt";
  13990. const char *content = "ims-extreme-date";
  13991. {
  13992. std::ofstream ofs(fname);
  13993. ofs << content;
  13994. ASSERT_TRUE(ofs.good());
  13995. }
  13996. Server svr;
  13997. svr.set_mount_point("/static", ".");
  13998. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13999. svr.wait_until_ready();
  14000. Client cli(HOST, PORT);
  14001. auto res1 = cli.Get(std::string("/static/") + fname);
  14002. ASSERT_TRUE(res1);
  14003. ASSERT_EQ(200, res1->status);
  14004. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14005. // Extremely large year that may overflow date parsing routines.
  14006. Headers h_large_date = {
  14007. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14008. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14009. ASSERT_TRUE(res_bad);
  14010. // Expect server to treat this as invalid/mismatch and return full content
  14011. EXPECT_EQ(200, res_bad->status);
  14012. // If-Range with extremely large date should be treated as mismatch -> full
  14013. // content (200)
  14014. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14015. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14016. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14017. ASSERT_TRUE(res_ifrange);
  14018. EXPECT_EQ(200, res_ifrange->status);
  14019. svr.stop();
  14020. t.join();
  14021. std::remove(fname);
  14022. }
  14023. TEST(ETagTest, NegativeFileModificationTime) {
  14024. using namespace httplib;
  14025. const char *fname = "ims_negative_mtime.txt";
  14026. const std::string content = "negative-mtime";
  14027. {
  14028. std::ofstream ofs(fname);
  14029. ofs << content;
  14030. ASSERT_TRUE(ofs.good());
  14031. }
  14032. // Try to set file mtime to a negative value. This may fail on some
  14033. // platforms/filesystems; if it fails, the test will still verify server
  14034. // behaves safely by performing a regular conditional request.
  14035. #if defined(__APPLE__) || defined(__linux__)
  14036. bool set_negative = false;
  14037. do {
  14038. struct timeval times[2];
  14039. // access time: now
  14040. times[0].tv_sec = time(nullptr);
  14041. times[0].tv_usec = 0;
  14042. // modification time: negative (e.g., -1)
  14043. times[1].tv_sec = -1;
  14044. times[1].tv_usec = 0;
  14045. if (utimes(fname, times) == 0) { set_negative = true; }
  14046. } while (0);
  14047. #else
  14048. bool set_negative = false;
  14049. #endif
  14050. Server svr;
  14051. svr.set_mount_point("/static", ".");
  14052. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14053. svr.wait_until_ready();
  14054. Client cli(HOST, PORT);
  14055. auto res1 = cli.Get(std::string("/static/") + fname);
  14056. ASSERT_TRUE(res1);
  14057. ASSERT_EQ(200, res1->status);
  14058. bool has_last_modified = res1->has_header("Last-Modified");
  14059. std::string last_modified;
  14060. if (has_last_modified) {
  14061. last_modified = res1->get_header_value("Last-Modified");
  14062. }
  14063. if (set_negative) {
  14064. // If we successfully set a negative mtime, ensure server returns a
  14065. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14066. // with an old date and ensure server handles it without crash.
  14067. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14068. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14069. ASSERT_TRUE(res2);
  14070. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14071. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14072. } else {
  14073. // Could not set negative mtime on this platform; fall back to verifying
  14074. // that normal invalid/malformed dates are treated safely (non-304).
  14075. Headers h_bad_date = {
  14076. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14077. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14078. ASSERT_TRUE(res_bad);
  14079. EXPECT_EQ(200, res_bad->status);
  14080. }
  14081. svr.stop();
  14082. t.join();
  14083. std::remove(fname);
  14084. }
  14085. //==============================================================================
  14086. // SSE Parsing Tests
  14087. //==============================================================================
  14088. class SSEParsingTest : public ::testing::Test {
  14089. protected:
  14090. // Test helper that mimics SSE parsing behavior
  14091. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14092. int &retry_ms) {
  14093. // Blank line signals end of event
  14094. if (line.empty() || line == "\r") { return true; }
  14095. // Lines starting with ':' are comments (ignored)
  14096. if (!line.empty() && line[0] == ':') { return false; }
  14097. // Find the colon separator
  14098. auto colon_pos = line.find(':');
  14099. if (colon_pos == std::string::npos) {
  14100. // Line with no colon is treated as field name with empty value
  14101. return false;
  14102. }
  14103. std::string field = line.substr(0, colon_pos);
  14104. std::string value;
  14105. // Value starts after colon, skip optional single space
  14106. if (colon_pos + 1 < line.size()) {
  14107. size_t value_start = colon_pos + 1;
  14108. if (line[value_start] == ' ') { value_start++; }
  14109. value = line.substr(value_start);
  14110. // Remove trailing \r if present
  14111. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14112. }
  14113. // Handle known fields
  14114. if (field == "event") {
  14115. msg.event = value;
  14116. } else if (field == "data") {
  14117. // Multiple data lines are concatenated with newlines
  14118. if (!msg.data.empty()) { msg.data += "\n"; }
  14119. msg.data += value;
  14120. } else if (field == "id") {
  14121. // Empty id is valid (clears the last event ID)
  14122. msg.id = value;
  14123. } else if (field == "retry") {
  14124. // Parse retry interval in milliseconds
  14125. {
  14126. int v = 0;
  14127. auto res =
  14128. detail::from_chars(value.data(), value.data() + value.size(), v);
  14129. if (res.ec == std::errc{}) { retry_ms = v; }
  14130. }
  14131. }
  14132. // Unknown fields are ignored per SSE spec
  14133. return false;
  14134. }
  14135. };
  14136. // Test: Single-line data
  14137. TEST_F(SSEParsingTest, SingleLineData) {
  14138. sse::SSEMessage msg;
  14139. int retry_ms = 3000;
  14140. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14141. EXPECT_EQ(msg.data, "hello");
  14142. EXPECT_EQ(msg.event, "message");
  14143. // Blank line ends event
  14144. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14145. }
  14146. // Test: Multi-line data
  14147. TEST_F(SSEParsingTest, MultiLineData) {
  14148. sse::SSEMessage msg;
  14149. int retry_ms = 3000;
  14150. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14151. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14152. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14153. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14154. }
  14155. // Test: Custom event types
  14156. TEST_F(SSEParsingTest, CustomEventType) {
  14157. sse::SSEMessage msg;
  14158. int retry_ms = 3000;
  14159. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14160. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14161. EXPECT_EQ(msg.event, "update");
  14162. EXPECT_EQ(msg.data, "payload");
  14163. }
  14164. // Test: Event ID handling
  14165. TEST_F(SSEParsingTest, EventIdHandling) {
  14166. sse::SSEMessage msg;
  14167. int retry_ms = 3000;
  14168. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14169. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14170. EXPECT_EQ(msg.id, "12345");
  14171. }
  14172. // Test: Empty event ID (clears last event ID)
  14173. TEST_F(SSEParsingTest, EmptyEventId) {
  14174. sse::SSEMessage msg;
  14175. msg.id = "previous";
  14176. int retry_ms = 3000;
  14177. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14178. EXPECT_EQ(msg.id, "");
  14179. }
  14180. // Test: Retry field parsing
  14181. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14182. sse::SSEMessage msg;
  14183. int retry_ms = 3000;
  14184. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14185. EXPECT_EQ(retry_ms, 5000);
  14186. }
  14187. // Test: Invalid retry value
  14188. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14189. sse::SSEMessage msg;
  14190. int retry_ms = 3000;
  14191. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14192. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14193. }
  14194. // Test: Comments (lines starting with :)
  14195. TEST_F(SSEParsingTest, CommentsIgnored) {
  14196. sse::SSEMessage msg;
  14197. int retry_ms = 3000;
  14198. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14199. EXPECT_EQ(msg.data, "");
  14200. EXPECT_EQ(msg.event, "message");
  14201. }
  14202. // Test: Colon in value
  14203. TEST_F(SSEParsingTest, ColonInValue) {
  14204. sse::SSEMessage msg;
  14205. int retry_ms = 3000;
  14206. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14207. EXPECT_EQ(msg.data, "hello:world:test");
  14208. }
  14209. // Test: Line with no colon (field name only)
  14210. TEST_F(SSEParsingTest, FieldNameOnly) {
  14211. sse::SSEMessage msg;
  14212. int retry_ms = 3000;
  14213. // According to SSE spec, this is treated as field name with empty value
  14214. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14215. // Since we don't recognize "data" without colon, data should be empty
  14216. EXPECT_EQ(msg.data, "");
  14217. }
  14218. // Test: Trailing \r handling
  14219. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14220. sse::SSEMessage msg;
  14221. int retry_ms = 3000;
  14222. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14223. EXPECT_EQ(msg.data, "hello");
  14224. }
  14225. // Test: Unknown fields ignored
  14226. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14227. sse::SSEMessage msg;
  14228. int retry_ms = 3000;
  14229. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14230. EXPECT_EQ(msg.data, "");
  14231. EXPECT_EQ(msg.event, "message");
  14232. }
  14233. // Test: Space after colon is optional
  14234. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14235. sse::SSEMessage msg1, msg2;
  14236. int retry_ms = 3000;
  14237. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14238. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14239. EXPECT_EQ(msg1.data, "hello");
  14240. EXPECT_EQ(msg2.data, "hello");
  14241. }
  14242. // Test: SSEMessage clear
  14243. TEST_F(SSEParsingTest, MessageClear) {
  14244. sse::SSEMessage msg;
  14245. msg.event = "custom";
  14246. msg.data = "some data";
  14247. msg.id = "123";
  14248. msg.clear();
  14249. EXPECT_EQ(msg.event, "message");
  14250. EXPECT_EQ(msg.data, "");
  14251. EXPECT_EQ(msg.id, "");
  14252. }
  14253. // Test: Complete event parsing
  14254. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14255. sse::SSEMessage msg;
  14256. int retry_ms = 3000;
  14257. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14258. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14259. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14260. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14261. // Blank line ends event
  14262. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14263. EXPECT_EQ(msg.event, "notification");
  14264. EXPECT_EQ(msg.id, "evt-42");
  14265. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14266. EXPECT_EQ(retry_ms, 1000);
  14267. }
  14268. //==============================================================================
  14269. // Integration Tests with Server
  14270. //==============================================================================
  14271. class SSEIntegrationTest : public ::testing::Test {
  14272. protected:
  14273. void SetUp() override {
  14274. stop_server_.store(false);
  14275. events_.clear();
  14276. server_ = httplib::detail::make_unique<Server>();
  14277. setup_server();
  14278. start_server();
  14279. }
  14280. void TearDown() override {
  14281. stop_server_.store(true);
  14282. event_cv_.notify_all();
  14283. server_->stop();
  14284. if (server_thread_.joinable()) { server_thread_.join(); }
  14285. }
  14286. void setup_server() {
  14287. // Simple SSE endpoint
  14288. server_->Get("/events", [this](const Request &req, Response &res) {
  14289. auto last_id = req.get_header_value("Last-Event-ID");
  14290. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14291. res.set_chunked_content_provider(
  14292. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14293. std::unique_lock<std::mutex> lock(event_mutex_);
  14294. if (event_cv_.wait_for(
  14295. lock, std::chrono::milliseconds(200), [this] {
  14296. return !events_.empty() || stop_server_.load();
  14297. })) {
  14298. if (stop_server_.load()) { return false; }
  14299. if (!events_.empty()) {
  14300. std::string event = events_.front();
  14301. events_.erase(events_.begin());
  14302. sink.write(event.data(), event.size());
  14303. return true;
  14304. }
  14305. }
  14306. return !stop_server_.load();
  14307. });
  14308. });
  14309. // Endpoint that returns error
  14310. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14311. res.status = 500;
  14312. res.set_content("Internal Server Error", "text/plain");
  14313. });
  14314. // Endpoint for custom event types
  14315. server_->Get("/custom-events", [](const Request &, Response &res) {
  14316. res.set_chunked_content_provider(
  14317. "text/event-stream", [](size_t offset, DataSink &sink) {
  14318. if (offset == 0) {
  14319. std::string event = "event: update\ndata: updated\n\n"
  14320. "event: delete\ndata: deleted\n\n";
  14321. sink.write(event.data(), event.size());
  14322. }
  14323. return false; // End stream after sending
  14324. });
  14325. });
  14326. }
  14327. void start_server() {
  14328. port_ = server_->bind_to_any_port(HOST);
  14329. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14330. // Wait for server to start
  14331. while (!server_->is_running()) {
  14332. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14333. }
  14334. }
  14335. int get_port() const { return port_; }
  14336. void send_event(const std::string &event) {
  14337. std::lock_guard<std::mutex> lock(event_mutex_);
  14338. events_.push_back(event);
  14339. event_cv_.notify_all();
  14340. }
  14341. std::unique_ptr<Server> server_;
  14342. std::thread server_thread_;
  14343. std::mutex event_mutex_;
  14344. std::condition_variable event_cv_;
  14345. std::vector<std::string> events_;
  14346. std::atomic<bool> stop_server_{false};
  14347. std::string last_received_event_id_;
  14348. int port_ = 0;
  14349. };
  14350. // Test: Successful connection and on_open callback
  14351. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14352. // Add a simple endpoint that sends one event and closes
  14353. server_->Get("/simple-event", [](const Request &, Response &res) {
  14354. res.set_chunked_content_provider(
  14355. "text/event-stream", [](size_t offset, DataSink &sink) {
  14356. if (offset == 0) {
  14357. std::string event = "data: hello\n\n";
  14358. sink.write(event.data(), event.size());
  14359. }
  14360. return false; // Close stream after sending
  14361. });
  14362. });
  14363. Client client("localhost", get_port());
  14364. sse::SSEClient sse(client, "/simple-event");
  14365. std::atomic<bool> open_called{false};
  14366. std::atomic<bool> message_received{false};
  14367. sse.on_open([&open_called]() { open_called.store(true); });
  14368. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14369. if (msg.data == "hello") { message_received.store(true); }
  14370. });
  14371. sse.set_reconnect_interval(100);
  14372. sse.set_max_reconnect_attempts(1);
  14373. // Start async
  14374. sse.start_async();
  14375. // Wait for message to be processed
  14376. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14377. sse.stop();
  14378. EXPECT_TRUE(open_called.load());
  14379. EXPECT_TRUE(message_received.load());
  14380. }
  14381. // Test: on_message callback
  14382. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14383. // Endpoint that sends multiple events then closes
  14384. server_->Get("/multi-event", [](const Request &, Response &res) {
  14385. res.set_chunked_content_provider(
  14386. "text/event-stream", [](size_t offset, DataSink &sink) {
  14387. if (offset == 0) {
  14388. std::string events = "data: message1\n\ndata: message2\n\n";
  14389. sink.write(events.data(), events.size());
  14390. }
  14391. return false;
  14392. });
  14393. });
  14394. Client client("localhost", get_port());
  14395. sse::SSEClient sse(client, "/multi-event");
  14396. std::vector<std::string> received_messages;
  14397. std::mutex messages_mutex;
  14398. sse.on_message([&](const sse::SSEMessage &msg) {
  14399. std::lock_guard<std::mutex> lock(messages_mutex);
  14400. received_messages.push_back(msg.data);
  14401. });
  14402. sse.set_reconnect_interval(100);
  14403. sse.set_max_reconnect_attempts(1);
  14404. sse.start_async();
  14405. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14406. sse.stop();
  14407. std::lock_guard<std::mutex> lock(messages_mutex);
  14408. EXPECT_GE(received_messages.size(), 2u);
  14409. if (received_messages.size() >= 2) {
  14410. EXPECT_EQ(received_messages[0], "message1");
  14411. EXPECT_EQ(received_messages[1], "message2");
  14412. }
  14413. }
  14414. // Test: on_event for specific types
  14415. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14416. Client client("localhost", get_port());
  14417. sse::SSEClient sse(client, "/custom-events");
  14418. std::atomic<bool> update_received{false};
  14419. std::atomic<bool> delete_received{false};
  14420. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14421. if (msg.data == "updated") { update_received.store(true); }
  14422. });
  14423. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14424. if (msg.data == "deleted") { delete_received.store(true); }
  14425. });
  14426. sse.set_max_reconnect_attempts(1);
  14427. sse.start_async();
  14428. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14429. sse.stop();
  14430. EXPECT_TRUE(update_received.load());
  14431. EXPECT_TRUE(delete_received.load());
  14432. }
  14433. // Test: on_error callback on connection failure
  14434. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14435. // Connect to a non-existent port
  14436. Client client("localhost", 59999);
  14437. sse::SSEClient sse(client, "/events");
  14438. std::atomic<bool> error_called{false};
  14439. Error received_error = Error::Success;
  14440. sse.on_error([&](Error err) {
  14441. error_called.store(true);
  14442. received_error = err;
  14443. });
  14444. sse.set_reconnect_interval(50);
  14445. sse.set_max_reconnect_attempts(1);
  14446. sse.start_async();
  14447. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14448. sse.stop();
  14449. EXPECT_TRUE(error_called.load());
  14450. EXPECT_NE(received_error, Error::Success);
  14451. }
  14452. // Test: Last-Event-ID header sent on reconnect
  14453. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14454. // Endpoint that sends event with ID
  14455. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14456. res.set_chunked_content_provider(
  14457. "text/event-stream", [](size_t offset, DataSink &sink) {
  14458. if (offset == 0) {
  14459. std::string event = "id: evt-123\ndata: test\n\n";
  14460. sink.write(event.data(), event.size());
  14461. }
  14462. return false;
  14463. });
  14464. });
  14465. Client client("localhost", get_port());
  14466. sse::SSEClient sse(client, "/event-with-id");
  14467. std::atomic<bool> id_received{false};
  14468. sse.on_message([&](const sse::SSEMessage &msg) {
  14469. if (!msg.id.empty()) { id_received.store(true); }
  14470. });
  14471. sse.set_reconnect_interval(100);
  14472. sse.set_max_reconnect_attempts(1);
  14473. sse.start_async();
  14474. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14475. sse.stop();
  14476. EXPECT_TRUE(id_received.load());
  14477. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14478. }
  14479. // Test: Manual stop
  14480. TEST_F(SSEIntegrationTest, ManualStop) {
  14481. // Endpoint that sends one event and stays open briefly
  14482. std::atomic<bool> handler_running{true};
  14483. server_->Get("/stay-open", [&handler_running](const Request &,
  14484. Response &res) {
  14485. res.set_chunked_content_provider(
  14486. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14487. if (offset == 0) {
  14488. std::string event = "data: connected\n\n";
  14489. sink.write(event.data(), event.size());
  14490. }
  14491. // Keep connection open while handler_running is true
  14492. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14493. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14494. }
  14495. return false;
  14496. });
  14497. });
  14498. Client client("localhost", get_port());
  14499. sse::SSEClient sse(client, "/stay-open");
  14500. std::atomic<bool> connected{false};
  14501. sse.on_open([&connected]() { connected.store(true); });
  14502. sse.set_reconnect_interval(100);
  14503. sse.set_max_reconnect_attempts(1);
  14504. sse.start_async();
  14505. // Wait for connection to establish
  14506. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14507. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14508. }
  14509. EXPECT_TRUE(connected.load());
  14510. EXPECT_TRUE(sse.is_connected());
  14511. // Signal handler to stop
  14512. handler_running.store(false);
  14513. // Stop SSE client
  14514. sse.stop();
  14515. EXPECT_FALSE(sse.is_connected());
  14516. }
  14517. // Test: SSEClient with custom headers
  14518. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14519. // Setup a server endpoint that checks for custom header
  14520. std::atomic<bool> header_received{false};
  14521. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14522. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14523. header_received.store(true);
  14524. }
  14525. res.set_chunked_content_provider("text/event-stream",
  14526. [](size_t, DataSink &) { return false; });
  14527. });
  14528. Client client("localhost", get_port());
  14529. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14530. sse::SSEClient sse(client, "/header-check", headers);
  14531. sse.set_max_reconnect_attempts(1);
  14532. sse.start_async();
  14533. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14534. sse.stop();
  14535. EXPECT_TRUE(header_received.load());
  14536. }
  14537. // Test: Reconnect interval configuration
  14538. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14539. Client client("localhost", get_port());
  14540. sse::SSEClient sse(client, "/events");
  14541. auto &result = sse.set_reconnect_interval(500);
  14542. // Builder pattern should return reference to self
  14543. EXPECT_EQ(&result, &sse);
  14544. }
  14545. // Test: Max reconnect attempts
  14546. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14547. // Connect to non-existent port to force reconnects
  14548. Client client("localhost", 59998);
  14549. sse::SSEClient sse(client, "/events");
  14550. std::atomic<int> error_count{0};
  14551. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14552. sse.set_reconnect_interval(50);
  14553. sse.set_max_reconnect_attempts(2);
  14554. auto start = std::chrono::steady_clock::now();
  14555. sse.start(); // Blocking call
  14556. auto end = std::chrono::steady_clock::now();
  14557. // Should have stopped after 2 failed attempts
  14558. EXPECT_GE(error_count.load(), 2);
  14559. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14560. auto duration =
  14561. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14562. #ifdef _WIN32
  14563. // Windows is much slower for socket connection failures
  14564. EXPECT_LT(duration.count(), 7000);
  14565. #else
  14566. EXPECT_LT(duration.count(), 1000);
  14567. #endif
  14568. }
  14569. // Test: Multi-line data in integration
  14570. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14571. // Endpoint with multi-line data
  14572. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14573. res.set_chunked_content_provider(
  14574. "text/event-stream", [](size_t offset, DataSink &sink) {
  14575. if (offset == 0) {
  14576. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14577. sink.write(event.data(), event.size());
  14578. }
  14579. return false;
  14580. });
  14581. });
  14582. Client client("localhost", get_port());
  14583. sse::SSEClient sse(client, "/multiline-data");
  14584. std::string received_data;
  14585. std::mutex data_mutex;
  14586. sse.on_message([&](const sse::SSEMessage &msg) {
  14587. std::lock_guard<std::mutex> lock(data_mutex);
  14588. received_data = msg.data;
  14589. });
  14590. sse.set_reconnect_interval(100);
  14591. sse.set_max_reconnect_attempts(1);
  14592. sse.start_async();
  14593. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14594. sse.stop();
  14595. std::lock_guard<std::mutex> lock(data_mutex);
  14596. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14597. }
  14598. // Test: Auto-reconnect after server disconnection
  14599. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14600. std::atomic<int> connection_count{0};
  14601. std::atomic<int> message_count{0};
  14602. // Endpoint that sends one event and closes, forcing reconnect
  14603. server_->Get("/reconnect-test",
  14604. [&connection_count](const Request &, Response &res) {
  14605. connection_count.fetch_add(1);
  14606. res.set_chunked_content_provider(
  14607. "text/event-stream", [](size_t offset, DataSink &sink) {
  14608. if (offset == 0) {
  14609. std::string event = "data: hello\n\n";
  14610. sink.write(event.data(), event.size());
  14611. }
  14612. return false; // Close connection after sending
  14613. });
  14614. });
  14615. Client client("localhost", get_port());
  14616. sse::SSEClient sse(client, "/reconnect-test");
  14617. sse.on_message([&message_count](const sse::SSEMessage &) {
  14618. message_count.fetch_add(1);
  14619. });
  14620. sse.set_reconnect_interval(100);
  14621. sse.set_max_reconnect_attempts(3);
  14622. sse.start_async();
  14623. // Wait long enough for multiple reconnects
  14624. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14625. sse.stop();
  14626. // Should have connected multiple times (initial + reconnects)
  14627. EXPECT_GE(connection_count.load(), 2);
  14628. // Should have received messages from multiple connections
  14629. EXPECT_GE(message_count.load(), 2);
  14630. }
  14631. // Test: Last-Event-ID sent on reconnect
  14632. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14633. std::atomic<int> connection_count{0};
  14634. std::vector<std::string> received_last_event_ids;
  14635. std::mutex id_mutex;
  14636. // Endpoint that checks Last-Event-ID header and sends event with ID
  14637. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14638. int conn = connection_count.fetch_add(1);
  14639. // Capture the Last-Event-ID header from each connection
  14640. {
  14641. std::lock_guard<std::mutex> lock(id_mutex);
  14642. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14643. }
  14644. res.set_chunked_content_provider(
  14645. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14646. if (offset == 0) {
  14647. std::string event =
  14648. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14649. sink.write(event.data(), event.size());
  14650. }
  14651. return false;
  14652. });
  14653. });
  14654. Client client("localhost", get_port());
  14655. sse::SSEClient sse(client, "/reconnect-with-id");
  14656. sse.set_reconnect_interval(100);
  14657. sse.set_max_reconnect_attempts(3);
  14658. sse.start_async();
  14659. // Wait for at least 2 connections
  14660. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14661. sse.stop();
  14662. // Verify behavior
  14663. std::lock_guard<std::mutex> lock(id_mutex);
  14664. EXPECT_GE(received_last_event_ids.size(), 2u);
  14665. // First connection should have no Last-Event-ID
  14666. if (!received_last_event_ids.empty()) {
  14667. EXPECT_EQ(received_last_event_ids[0], "");
  14668. }
  14669. // Second connection should have Last-Event-ID from first connection
  14670. if (received_last_event_ids.size() >= 2) {
  14671. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14672. }
  14673. }
  14674. // Test: set_headers updates headers used on reconnect
  14675. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14676. std::vector<std::string> received_tokens;
  14677. std::mutex token_mutex;
  14678. // Endpoint that captures Authorization header
  14679. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14680. {
  14681. std::lock_guard<std::mutex> lock(token_mutex);
  14682. received_tokens.push_back(req.get_header_value("Authorization"));
  14683. }
  14684. res.set_chunked_content_provider(
  14685. "text/event-stream", [](size_t offset, DataSink &sink) {
  14686. if (offset == 0) {
  14687. std::string event = "data: hello\n\n";
  14688. sink.write(event.data(), event.size());
  14689. }
  14690. return false; // Close connection to trigger reconnect
  14691. });
  14692. });
  14693. Client client("localhost", get_port());
  14694. Headers headers = {{"Authorization", "Bearer old-token"}};
  14695. sse::SSEClient sse(client, "/auth-check", headers);
  14696. // Update headers on each successful connection
  14697. sse.on_open(
  14698. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14699. sse.set_reconnect_interval(100);
  14700. sse.set_max_reconnect_attempts(3);
  14701. sse.start_async();
  14702. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14703. sse.stop();
  14704. std::lock_guard<std::mutex> lock(token_mutex);
  14705. ASSERT_GE(received_tokens.size(), 2u);
  14706. // First connection uses original header
  14707. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14708. // Second connection uses updated header from set_headers
  14709. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14710. }
  14711. // Test: 401 allows reconnection (so on_error can refresh headers)
  14712. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14713. std::atomic<int> connection_count{0};
  14714. // Endpoint: returns 401 on first attempt, 200 on second
  14715. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14716. int conn = connection_count.fetch_add(1);
  14717. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14718. res.status = StatusCode::Unauthorized_401;
  14719. res.set_content("Unauthorized", "text/plain");
  14720. return;
  14721. }
  14722. res.set_chunked_content_provider(
  14723. "text/event-stream", [](size_t offset, DataSink &sink) {
  14724. if (offset == 0) {
  14725. std::string event = "data: authenticated\n\n";
  14726. sink.write(event.data(), event.size());
  14727. }
  14728. return false;
  14729. });
  14730. });
  14731. Client client("localhost", get_port());
  14732. Headers headers = {{"Authorization", "Bearer expired"}};
  14733. sse::SSEClient sse(client, "/auth-retry", headers);
  14734. std::atomic<bool> message_received{false};
  14735. // Refresh token on error
  14736. sse.on_error(
  14737. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14738. sse.on_message([&](const sse::SSEMessage &msg) {
  14739. if (msg.data == "authenticated") { message_received.store(true); }
  14740. });
  14741. sse.set_reconnect_interval(100);
  14742. sse.set_max_reconnect_attempts(3);
  14743. sse.start_async();
  14744. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14745. sse.stop();
  14746. // Should have reconnected after 401 and succeeded with new token
  14747. EXPECT_GE(connection_count.load(), 2);
  14748. EXPECT_TRUE(message_received.load());
  14749. }
  14750. TEST(Issue2318Test, EmptyHostString) {
  14751. {
  14752. httplib::Client cli_empty("", PORT);
  14753. auto res = cli_empty.Get("/");
  14754. ASSERT_FALSE(res);
  14755. EXPECT_EQ(httplib::Error::Connection, res.error());
  14756. }
  14757. {
  14758. httplib::Client cli(" ", PORT);
  14759. auto res = cli.Get("/");
  14760. ASSERT_FALSE(res);
  14761. EXPECT_EQ(httplib::Error::Connection, res.error());
  14762. }
  14763. }
  14764. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14765. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14766. Server svr;
  14767. // Set a small payload limit (1KB)
  14768. svr.set_payload_max_length(1024);
  14769. svr.Post("/test", [&](const Request &req, Response &res) {
  14770. res.set_content("Body size: " + std::to_string(req.body.size()),
  14771. "text/plain");
  14772. });
  14773. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14774. auto se = detail::scope_exit([&] {
  14775. svr.stop();
  14776. listen_thread.join();
  14777. });
  14778. svr.wait_until_ready();
  14779. // Create data that compresses well but exceeds limit when decompressed
  14780. // 8KB of repeated null bytes compresses to a very small size
  14781. std::string original_data(8 * 1024, '\0');
  14782. // Compress the data using gzip
  14783. std::string compressed_data;
  14784. detail::gzip_compressor compressor;
  14785. compressor.compress(original_data.data(), original_data.size(), true,
  14786. [&](const char *data, size_t size) {
  14787. compressed_data.append(data, size);
  14788. return true;
  14789. });
  14790. // Verify compression worked (compressed should be much smaller)
  14791. ASSERT_LT(compressed_data.size(), original_data.size());
  14792. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14793. // Send compressed data with Content-Encoding: gzip
  14794. Client cli(HOST, PORT);
  14795. Headers headers = {{"Content-Encoding", "gzip"}};
  14796. auto res =
  14797. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14798. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14799. ASSERT_TRUE(res);
  14800. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14801. }
  14802. #endif
  14803. // ============================================================================
  14804. // OpenSSL-Specific Tests
  14805. // ============================================================================
  14806. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14807. X509 *readCertificate(const std::string &strFileName) {
  14808. std::ifstream inStream(strFileName);
  14809. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14810. std::istreambuf_iterator<char>());
  14811. if (strCertPEM.empty()) return (nullptr);
  14812. BIO *pbCert = BIO_new(BIO_s_mem());
  14813. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14814. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14815. BIO_free(pbCert);
  14816. return (pCert);
  14817. }
  14818. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14819. std::ifstream inStream(strFileName);
  14820. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14821. std::istreambuf_iterator<char>());
  14822. if (strPrivateKeyPEM.empty()) return (nullptr);
  14823. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14824. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14825. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14826. BIO_free(pbPrivKey);
  14827. return (pPrivateKey);
  14828. }
  14829. TEST(BindServerTest, UpdateCerts) {
  14830. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14831. int port = svr.bind_to_any_port("0.0.0.0");
  14832. ASSERT_TRUE(svr.is_valid());
  14833. ASSERT_TRUE(port > 0);
  14834. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14835. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14836. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14837. ASSERT_TRUE(cert != nullptr);
  14838. ASSERT_TRUE(ca_cert != nullptr);
  14839. ASSERT_TRUE(key != nullptr);
  14840. X509_STORE *cert_store = X509_STORE_new();
  14841. X509_STORE_add_cert(cert_store, ca_cert);
  14842. // svr.update_certs(cert, key, cert_store); // deprecated
  14843. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14844. CLIENT_CA_CERT_FILE);
  14845. ASSERT_TRUE(svr.is_valid());
  14846. svr.stop();
  14847. X509_STORE_free(cert_store);
  14848. X509_free(cert);
  14849. X509_free(ca_cert);
  14850. EVP_PKEY_free(key);
  14851. }
  14852. // Test that update_certs() updates client CA list correctly
  14853. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14854. // Start with file-based constructor
  14855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14856. ASSERT_TRUE(svr.is_valid());
  14857. // Initially no client CA list should be set
  14858. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14859. ASSERT_TRUE(ssl_ctx != nullptr);
  14860. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14861. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14862. EXPECT_EQ(0, count_before);
  14863. // Now update with client CA (PEM string)
  14864. std::string cert_pem, key_pem, ca_pem;
  14865. read_file(SERVER_CERT_FILE, cert_pem);
  14866. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14867. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14868. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14869. ASSERT_TRUE(svr.is_valid());
  14870. // Now client CA list should be set
  14871. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14872. ASSERT_TRUE(ca_list_after != nullptr);
  14873. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14874. }
  14875. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14876. // Test that the file-path SSLServer constructor properly sets the client CA
  14877. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14878. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14879. ASSERT_TRUE(svr.is_valid());
  14880. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14881. ASSERT_TRUE(ssl_ctx != nullptr);
  14882. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14883. ASSERT_TRUE(ca_list != nullptr);
  14884. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14885. }
  14886. #endif
  14887. // ============================================================================
  14888. // MbedTLS-Specific Tests
  14889. // ============================================================================
  14890. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14891. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14892. using namespace httplib::tls;
  14893. // Track if callback was invoked
  14894. bool callback_invoked = false;
  14895. // The callback receives void* ctx which is actually MbedTlsContext*
  14896. // We can access the mbedtls_ssl_config via the context
  14897. auto setup_callback = [&callback_invoked](void *ctx) {
  14898. callback_invoked = true;
  14899. // Cast to MbedTlsContext* to access the ssl config
  14900. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14901. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14902. // Use static variables to hold certificate data (simplified for test)
  14903. static mbedtls_x509_crt own_cert;
  14904. static mbedtls_pk_context own_key;
  14905. static mbedtls_x509_crt ca_chain;
  14906. static bool initialized = false;
  14907. if (!initialized) {
  14908. mbedtls_x509_crt_init(&own_cert);
  14909. mbedtls_pk_init(&own_key);
  14910. mbedtls_x509_crt_init(&ca_chain);
  14911. // Load server certificate
  14912. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14913. return false;
  14914. }
  14915. // Load server private key
  14916. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14917. #if MBEDTLS_VERSION_MAJOR >= 3
  14918. ,
  14919. mbedtls_ctr_drbg_random, nullptr
  14920. #endif
  14921. ) != 0) {
  14922. return false;
  14923. }
  14924. // Load CA chain for client verification
  14925. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14926. return false;
  14927. }
  14928. initialized = true;
  14929. }
  14930. // Configure the SSL config
  14931. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14932. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14933. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14934. // Set minimum TLS version using mbedTLS native API
  14935. #if MBEDTLS_VERSION_MAJOR >= 3
  14936. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14937. #else
  14938. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14939. MBEDTLS_SSL_MINOR_VERSION_3);
  14940. #endif
  14941. return true;
  14942. };
  14943. SSLServer svr(setup_callback);
  14944. ASSERT_TRUE(svr.is_valid());
  14945. ASSERT_TRUE(callback_invoked);
  14946. svr.Get("/test", [&](const Request &req, Response &res) {
  14947. res.set_content("test", "text/plain");
  14948. auto cert = req.peer_cert();
  14949. ASSERT_TRUE(static_cast<bool>(cert));
  14950. auto common_name = cert.subject_cn();
  14951. EXPECT_EQ("Common Name", common_name);
  14952. });
  14953. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14954. auto se = detail::scope_exit([&] {
  14955. svr.stop();
  14956. t.join();
  14957. ASSERT_FALSE(svr.is_running());
  14958. });
  14959. svr.wait_until_ready();
  14960. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14961. cli.enable_server_certificate_verification(false);
  14962. cli.set_connection_timeout(30);
  14963. auto res = cli.Get("/test");
  14964. ASSERT_TRUE(res);
  14965. ASSERT_EQ(StatusCode::OK_200, res->status);
  14966. }
  14967. #endif
  14968. // WebSocket Tests
  14969. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14970. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14971. // defining the meaning of these bits has been negotiated.
  14972. auto make_frame = [](uint8_t first_byte) {
  14973. std::string frame;
  14974. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14975. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14976. frame += "Hello";
  14977. return frame;
  14978. };
  14979. // RSV1 set (0x40)
  14980. {
  14981. detail::BufferStream strm;
  14982. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14983. ws::Opcode opcode;
  14984. std::string payload;
  14985. bool fin;
  14986. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14987. false, 1024));
  14988. }
  14989. // RSV2 set (0x20)
  14990. {
  14991. detail::BufferStream strm;
  14992. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14993. ws::Opcode opcode;
  14994. std::string payload;
  14995. bool fin;
  14996. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14997. false, 1024));
  14998. }
  14999. // RSV3 set (0x10)
  15000. {
  15001. detail::BufferStream strm;
  15002. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15003. ws::Opcode opcode;
  15004. std::string payload;
  15005. bool fin;
  15006. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15007. false, 1024));
  15008. }
  15009. // No RSV bits set - should succeed
  15010. {
  15011. detail::BufferStream strm;
  15012. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15013. ws::Opcode opcode;
  15014. std::string payload;
  15015. bool fin;
  15016. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15017. false, 1024));
  15018. EXPECT_EQ(ws::Opcode::Text, opcode);
  15019. EXPECT_EQ("Hello", payload);
  15020. EXPECT_TRUE(fin);
  15021. }
  15022. }
  15023. TEST(WebSocketTest, ControlFrameValidation) {
  15024. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15025. // payload length <= 125.
  15026. // Ping with FIN=0 - must be rejected
  15027. {
  15028. detail::BufferStream strm;
  15029. std::string frame;
  15030. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15031. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15032. strm.write(frame.data(), frame.size());
  15033. ws::Opcode opcode;
  15034. std::string payload;
  15035. bool fin;
  15036. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15037. false, 1024));
  15038. }
  15039. // Close with FIN=0 - must be rejected
  15040. {
  15041. detail::BufferStream strm;
  15042. std::string frame;
  15043. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15044. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15045. strm.write(frame.data(), frame.size());
  15046. ws::Opcode opcode;
  15047. std::string payload;
  15048. bool fin;
  15049. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15050. false, 1024));
  15051. }
  15052. // Ping with payload_len=126 (extended length) - must be rejected
  15053. {
  15054. detail::BufferStream strm;
  15055. std::string frame;
  15056. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15057. frame += static_cast<char>(126); // payload_len=126 (>125)
  15058. frame += static_cast<char>(0x00); // extended length high byte
  15059. frame += static_cast<char>(126); // extended length low byte
  15060. frame += std::string(126, 'x');
  15061. strm.write(frame.data(), frame.size());
  15062. ws::Opcode opcode;
  15063. std::string payload;
  15064. bool fin;
  15065. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15066. false, 1024));
  15067. }
  15068. // Ping with FIN=1 and payload_len=125 - should succeed
  15069. {
  15070. detail::BufferStream strm;
  15071. std::string frame;
  15072. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15073. frame += static_cast<char>(125); // payload_len=125
  15074. frame += std::string(125, 'x');
  15075. strm.write(frame.data(), frame.size());
  15076. ws::Opcode opcode;
  15077. std::string payload;
  15078. bool fin;
  15079. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15080. false, 1024));
  15081. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15082. EXPECT_EQ(125u, payload.size());
  15083. EXPECT_TRUE(fin);
  15084. }
  15085. }
  15086. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15087. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15088. // length MUST be 0.
  15089. // MSB set - must be rejected
  15090. {
  15091. detail::BufferStream strm;
  15092. std::string frame;
  15093. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15094. frame += static_cast<char>(127); // 64-bit extended length
  15095. frame += static_cast<char>(0x80); // MSB set (invalid)
  15096. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15097. strm.write(frame.data(), frame.size());
  15098. ws::Opcode opcode;
  15099. std::string payload;
  15100. bool fin;
  15101. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15102. false, 1024));
  15103. }
  15104. // MSB clear - should pass length parsing (will be rejected by max_len,
  15105. // but that's a different check; use a small length to verify)
  15106. {
  15107. detail::BufferStream strm;
  15108. std::string frame;
  15109. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15110. frame += static_cast<char>(127); // 64-bit extended length
  15111. frame += std::string(7, '\0'); // high bytes = 0
  15112. frame += static_cast<char>(0x03); // length = 3
  15113. frame += "abc";
  15114. strm.write(frame.data(), frame.size());
  15115. ws::Opcode opcode;
  15116. std::string payload;
  15117. bool fin;
  15118. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15119. false, 1024));
  15120. EXPECT_EQ(ws::Opcode::Text, opcode);
  15121. EXPECT_EQ("abc", payload);
  15122. }
  15123. }
  15124. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15125. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15126. // Valid UTF-8
  15127. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15128. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15129. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15130. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15131. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15132. // Invalid UTF-8
  15133. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15134. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15135. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15136. EXPECT_FALSE(
  15137. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15138. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15139. }
  15140. TEST(WebSocketTest, ConnectAndDisconnect) {
  15141. Server svr;
  15142. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15143. std::string msg;
  15144. while (ws.read(msg)) {}
  15145. });
  15146. auto port = svr.bind_to_any_port(HOST);
  15147. std::thread t([&]() { svr.listen_after_bind(); });
  15148. svr.wait_until_ready();
  15149. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15150. ASSERT_TRUE(client.connect());
  15151. EXPECT_TRUE(client.is_open());
  15152. client.close();
  15153. EXPECT_FALSE(client.is_open());
  15154. svr.stop();
  15155. t.join();
  15156. }
  15157. TEST(WebSocketTest, ValidURL) {
  15158. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15159. EXPECT_TRUE(ws1.is_valid());
  15160. ws::WebSocketClient ws2("ws://example.com/path");
  15161. EXPECT_TRUE(ws2.is_valid());
  15162. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15163. EXPECT_TRUE(ws3.is_valid());
  15164. #ifdef CPPHTTPLIB_SSL_ENABLED
  15165. ws::WebSocketClient wss1("wss://example.com/path");
  15166. EXPECT_TRUE(wss1.is_valid());
  15167. ws::WebSocketClient wss2("wss://example.com:443/path");
  15168. EXPECT_TRUE(wss2.is_valid());
  15169. #endif
  15170. }
  15171. TEST(WebSocketTest, InvalidURL) {
  15172. // No scheme
  15173. ws::WebSocketClient ws1("localhost:8080/path");
  15174. EXPECT_FALSE(ws1.is_valid());
  15175. // No path
  15176. ws::WebSocketClient ws2("ws://localhost:8080");
  15177. EXPECT_FALSE(ws2.is_valid());
  15178. // Empty string
  15179. ws::WebSocketClient ws3("");
  15180. EXPECT_FALSE(ws3.is_valid());
  15181. // Missing host
  15182. ws::WebSocketClient ws4("ws://:8080/path");
  15183. EXPECT_FALSE(ws4.is_valid());
  15184. // Port number overflow — should not crash
  15185. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15186. EXPECT_FALSE(ws5.is_valid());
  15187. // Port out of range
  15188. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15189. EXPECT_FALSE(ws6.is_valid());
  15190. }
  15191. TEST(WebSocketTest, UnsupportedScheme) {
  15192. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15193. ws::WebSocketClient ws1("http://localhost:8080/path");
  15194. EXPECT_FALSE(ws1.is_valid());
  15195. ws::WebSocketClient ws2("https://localhost:8080/path");
  15196. EXPECT_FALSE(ws2.is_valid());
  15197. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15198. EXPECT_FALSE(ws3.is_valid());
  15199. #else
  15200. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15201. std::invalid_argument);
  15202. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15203. std::invalid_argument);
  15204. #endif
  15205. }
  15206. TEST(WebSocketTest, ConnectWhenInvalid) {
  15207. ws::WebSocketClient ws("not a valid url");
  15208. EXPECT_FALSE(ws.is_valid());
  15209. EXPECT_FALSE(ws.connect());
  15210. }
  15211. TEST(WebSocketTest, DefaultPort) {
  15212. ws::WebSocketClient ws1("ws://example.com/path");
  15213. EXPECT_TRUE(ws1.is_valid());
  15214. // ws:// defaults to port 80 (verified by successful parse)
  15215. #ifdef CPPHTTPLIB_SSL_ENABLED
  15216. ws::WebSocketClient ws2("wss://example.com/path");
  15217. EXPECT_TRUE(ws2.is_valid());
  15218. // wss:// defaults to port 443 (verified by successful parse)
  15219. #endif
  15220. }
  15221. TEST(WebSocketTest, IPv6LiteralAddress) {
  15222. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15223. EXPECT_TRUE(ws1.is_valid());
  15224. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15225. EXPECT_TRUE(ws2.is_valid());
  15226. }
  15227. TEST(WebSocketTest, ComplexPath) {
  15228. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15229. EXPECT_TRUE(ws1.is_valid());
  15230. ws::WebSocketClient ws2("ws://localhost:8080/");
  15231. EXPECT_TRUE(ws2.is_valid());
  15232. }
  15233. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15234. Server svr;
  15235. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15236. std::string msg;
  15237. while (ws.read(msg)) {}
  15238. });
  15239. auto port = svr.bind_to_any_port(HOST);
  15240. std::thread t([&]() { svr.listen_after_bind(); });
  15241. svr.wait_until_ready();
  15242. auto another_host = "example.com";
  15243. auto wrong_ip = "192.0.2.1";
  15244. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15245. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15246. ASSERT_TRUE(client.connect());
  15247. EXPECT_TRUE(client.is_open());
  15248. client.close();
  15249. svr.stop();
  15250. t.join();
  15251. }
  15252. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15253. Server svr;
  15254. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15255. std::string msg;
  15256. while (ws.read(msg)) {}
  15257. });
  15258. auto port = svr.bind_to_any_port(HOST);
  15259. std::thread t([&]() { svr.listen_after_bind(); });
  15260. svr.wait_until_ready();
  15261. auto wrong_ip = "192.0.2.1";
  15262. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15263. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15264. client.set_connection_timeout(1);
  15265. client.set_read_timeout(1);
  15266. client.set_write_timeout(1);
  15267. EXPECT_FALSE(client.connect());
  15268. EXPECT_FALSE(client.is_open());
  15269. svr.stop();
  15270. t.join();
  15271. }
  15272. class WebSocketIntegrationTest : public ::testing::Test {
  15273. protected:
  15274. void SetUp() override {
  15275. server_ = httplib::detail::make_unique<Server>();
  15276. setup_server();
  15277. start_server();
  15278. }
  15279. void TearDown() override {
  15280. server_->stop();
  15281. if (server_thread_.joinable()) { server_thread_.join(); }
  15282. }
  15283. void setup_server() {
  15284. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15285. std::string msg;
  15286. ws::ReadResult ret;
  15287. while ((ret = ws.read(msg))) {
  15288. if (ret == ws::Binary) {
  15289. ws.send(msg.data(), msg.size());
  15290. } else {
  15291. ws.send(msg);
  15292. }
  15293. }
  15294. });
  15295. server_->WebSocket("/ws-echo-string",
  15296. [](const Request &, ws::WebSocket &ws) {
  15297. std::string msg;
  15298. while (ws.read(msg)) {
  15299. ws.send("echo: " + msg);
  15300. }
  15301. });
  15302. server_->WebSocket(
  15303. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15304. // Echo back request metadata
  15305. ws.send("path:" + req.path);
  15306. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15307. std::string msg;
  15308. while (ws.read(msg)) {}
  15309. });
  15310. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15311. std::string msg;
  15312. ws.read(msg); // wait for a message
  15313. ws.close();
  15314. });
  15315. server_->WebSocket("/ws-close-status",
  15316. [](const Request &, ws::WebSocket &ws) {
  15317. std::string msg;
  15318. ws.read(msg); // wait for a message
  15319. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15320. });
  15321. server_->WebSocket(
  15322. "/ws-subprotocol",
  15323. [](const Request &, ws::WebSocket &ws) {
  15324. std::string msg;
  15325. while (ws.read(msg)) {
  15326. ws.send(msg);
  15327. }
  15328. },
  15329. [](const std::vector<std::string> &protocols) -> std::string {
  15330. for (const auto &p : protocols) {
  15331. if (p == "graphql-ws") { return p; }
  15332. }
  15333. return "";
  15334. });
  15335. }
  15336. void start_server() {
  15337. port_ = server_->bind_to_any_port(HOST);
  15338. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15339. server_->wait_until_ready();
  15340. }
  15341. std::unique_ptr<Server> server_;
  15342. std::thread server_thread_;
  15343. int port_ = 0;
  15344. };
  15345. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15346. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15347. "/ws-echo");
  15348. ASSERT_TRUE(client.connect());
  15349. ASSERT_TRUE(client.is_open());
  15350. ASSERT_TRUE(client.send("Hello WebSocket"));
  15351. std::string msg;
  15352. EXPECT_EQ(ws::Text, client.read(msg));
  15353. EXPECT_EQ("Hello WebSocket", msg);
  15354. client.close();
  15355. }
  15356. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15357. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15358. "/ws-echo");
  15359. ASSERT_TRUE(client.connect());
  15360. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15361. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15362. std::string msg;
  15363. EXPECT_EQ(ws::Binary, client.read(msg));
  15364. EXPECT_EQ(binary_data, msg);
  15365. client.close();
  15366. }
  15367. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15368. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15369. "/ws-echo");
  15370. ASSERT_TRUE(client.connect());
  15371. for (int i = 0; i < 10; i++) {
  15372. auto text = "message " + std::to_string(i);
  15373. ASSERT_TRUE(client.send(text));
  15374. std::string msg;
  15375. ASSERT_TRUE(client.read(msg));
  15376. EXPECT_EQ(text, msg);
  15377. }
  15378. client.close();
  15379. }
  15380. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15381. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15382. "/ws-close");
  15383. ASSERT_TRUE(client.connect());
  15384. // Send a message to trigger the server to close
  15385. ASSERT_TRUE(client.send("trigger close"));
  15386. // The server will close, so read should return false
  15387. std::string msg;
  15388. EXPECT_FALSE(client.read(msg));
  15389. EXPECT_FALSE(client.is_open());
  15390. }
  15391. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15392. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15393. "/ws-echo");
  15394. ASSERT_TRUE(client.connect());
  15395. // 128KB message
  15396. std::string large_data(128 * 1024, 'X');
  15397. ASSERT_TRUE(client.send(large_data));
  15398. std::string msg;
  15399. ASSERT_TRUE(client.read(msg));
  15400. EXPECT_EQ(large_data, msg);
  15401. client.close();
  15402. }
  15403. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15404. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15405. "/ws-echo");
  15406. ASSERT_TRUE(client.connect());
  15407. const int num_threads = 4;
  15408. std::vector<std::thread> threads;
  15409. std::atomic<int> send_count{0};
  15410. for (int t = 0; t < num_threads; t++) {
  15411. threads.emplace_back([&client, &send_count, t]() {
  15412. for (int i = 0; i < 5; i++) {
  15413. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15414. if (client.send(text)) { send_count++; }
  15415. }
  15416. });
  15417. }
  15418. for (auto &th : threads) {
  15419. th.join();
  15420. }
  15421. int received = 0;
  15422. std::string msg;
  15423. while (received < send_count.load()) {
  15424. if (!client.read(msg)) { break; }
  15425. received++;
  15426. }
  15427. EXPECT_EQ(send_count.load(), received);
  15428. client.close();
  15429. }
  15430. TEST_F(WebSocketIntegrationTest, ReadString) {
  15431. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15432. "/ws-echo-string");
  15433. ASSERT_TRUE(client.connect());
  15434. ASSERT_TRUE(client.send("hello"));
  15435. std::string msg;
  15436. ASSERT_TRUE(client.read(msg));
  15437. EXPECT_EQ("echo: hello", msg);
  15438. ASSERT_TRUE(client.send("world"));
  15439. ASSERT_TRUE(client.read(msg));
  15440. EXPECT_EQ("echo: world", msg);
  15441. client.close();
  15442. }
  15443. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15444. Headers headers = {{"X-Test-Header", "test-value"}};
  15445. ws::WebSocketClient client(
  15446. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15447. ASSERT_TRUE(client.connect());
  15448. std::string msg;
  15449. ASSERT_TRUE(client.read(msg));
  15450. EXPECT_EQ("path:/ws-request-info", msg);
  15451. ASSERT_TRUE(client.read(msg));
  15452. EXPECT_EQ("header:test-value", msg);
  15453. client.close();
  15454. }
  15455. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15457. "/ws-echo");
  15458. client.set_read_timeout(1, 0); // 1 second
  15459. ASSERT_TRUE(client.connect());
  15460. // Don't send anything — server echo handler waits for a message,
  15461. // so read() should time out and return false.
  15462. std::string msg;
  15463. EXPECT_FALSE(client.read(msg));
  15464. }
  15465. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15466. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15467. "/ws-echo");
  15468. client.set_read_timeout(5, 0);
  15469. ASSERT_TRUE(client.connect());
  15470. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15471. // The server should reject it and close the connection.
  15472. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15473. client.send(oversized);
  15474. // The server's read() should have failed due to payload limit,
  15475. // so our read() should return false (connection closed).
  15476. std::string msg;
  15477. EXPECT_FALSE(client.read(msg));
  15478. }
  15479. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15480. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15481. "/ws-echo");
  15482. client.set_read_timeout(10, 0);
  15483. ASSERT_TRUE(client.connect());
  15484. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15485. // This should succeed.
  15486. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15487. ASSERT_TRUE(client.send(at_limit));
  15488. std::string msg;
  15489. ASSERT_TRUE(client.read(msg));
  15490. EXPECT_EQ(at_limit.size(), msg.size());
  15491. client.close();
  15492. }
  15493. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15494. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15495. "/nonexistent");
  15496. EXPECT_FALSE(client.connect());
  15497. EXPECT_FALSE(client.is_open());
  15498. }
  15499. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15500. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15501. "/ws-echo");
  15502. ASSERT_TRUE(client.connect());
  15503. ASSERT_TRUE(client.send(""));
  15504. std::string msg;
  15505. EXPECT_EQ(ws::Text, client.read(msg));
  15506. EXPECT_EQ("", msg);
  15507. client.close();
  15508. }
  15509. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15510. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15511. "/ws-echo");
  15512. // First connection
  15513. ASSERT_TRUE(client.connect());
  15514. ASSERT_TRUE(client.send("first"));
  15515. std::string msg;
  15516. ASSERT_TRUE(client.read(msg));
  15517. EXPECT_EQ("first", msg);
  15518. client.close();
  15519. EXPECT_FALSE(client.is_open());
  15520. // Reconnect using the same client object
  15521. ASSERT_TRUE(client.connect());
  15522. ASSERT_TRUE(client.is_open());
  15523. ASSERT_TRUE(client.send("second"));
  15524. ASSERT_TRUE(client.read(msg));
  15525. EXPECT_EQ("second", msg);
  15526. client.close();
  15527. }
  15528. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15529. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15530. "/ws-close-status");
  15531. ASSERT_TRUE(client.connect());
  15532. // Trigger the server to close with GoingAway status
  15533. ASSERT_TRUE(client.send("trigger"));
  15534. // read() should return false after receiving the close frame
  15535. std::string msg;
  15536. EXPECT_FALSE(client.read(msg));
  15537. EXPECT_FALSE(client.is_open());
  15538. }
  15539. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15540. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15541. "/ws-echo");
  15542. ASSERT_TRUE(client.connect());
  15543. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15544. EXPECT_FALSE(client.is_open());
  15545. }
  15546. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15547. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15548. ws::WebSocketClient client(
  15549. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15550. ASSERT_TRUE(client.connect());
  15551. // Server should have selected graphql-ws
  15552. EXPECT_EQ("graphql-ws", client.subprotocol());
  15553. client.close();
  15554. }
  15555. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15556. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15557. ws::WebSocketClient client(
  15558. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15559. ASSERT_TRUE(client.connect());
  15560. // Server should not have selected any subprotocol
  15561. EXPECT_TRUE(client.subprotocol().empty());
  15562. client.close();
  15563. }
  15564. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15565. // Connect without requesting any subprotocol
  15566. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15567. "/ws-subprotocol");
  15568. ASSERT_TRUE(client.connect());
  15569. EXPECT_TRUE(client.subprotocol().empty());
  15570. client.close();
  15571. }
  15572. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15573. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15574. "/ws-echo");
  15575. client.set_tcp_nodelay(true);
  15576. client.set_connection_timeout(3, 0);
  15577. bool socket_options_called = false;
  15578. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15579. ASSERT_TRUE(client.connect());
  15580. ASSERT_TRUE(client.is_open());
  15581. EXPECT_TRUE(socket_options_called);
  15582. ASSERT_TRUE(client.send("hello"));
  15583. std::string msg;
  15584. auto result = client.read(msg);
  15585. EXPECT_EQ(result, ws::ReadResult::Text);
  15586. EXPECT_EQ(msg, "hello");
  15587. client.close();
  15588. }
  15589. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15590. Server svr;
  15591. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15592. if (!req.has_header("Authorization")) {
  15593. res.status = StatusCode::Unauthorized_401;
  15594. res.set_content("Unauthorized", "text/plain");
  15595. return Server::HandlerResponse::Handled;
  15596. }
  15597. return Server::HandlerResponse::Unhandled;
  15598. });
  15599. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15600. std::string msg;
  15601. while (ws.read(msg)) {
  15602. ws.send(msg);
  15603. }
  15604. });
  15605. auto port = svr.bind_to_any_port("localhost");
  15606. std::thread t([&]() { svr.listen_after_bind(); });
  15607. svr.wait_until_ready();
  15608. // Without Authorization header - should be rejected before upgrade
  15609. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15610. EXPECT_FALSE(client1.connect());
  15611. // With Authorization header - should succeed
  15612. Headers headers = {{"Authorization", "Bearer token123"}};
  15613. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15614. headers);
  15615. ASSERT_TRUE(client2.connect());
  15616. ASSERT_TRUE(client2.send("hello"));
  15617. std::string msg;
  15618. ASSERT_TRUE(client2.read(msg));
  15619. EXPECT_EQ("hello", msg);
  15620. client2.close();
  15621. svr.stop();
  15622. t.join();
  15623. }
  15624. TEST(WebSocketTest, QueryStringInHandshake) {
  15625. Server svr;
  15626. std::mutex mtx;
  15627. std::string received_target;
  15628. std::string received_token;
  15629. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15630. {
  15631. std::lock_guard<std::mutex> lock(mtx);
  15632. received_target = req.target;
  15633. if (req.has_param("token")) {
  15634. received_token = req.get_param_value("token");
  15635. }
  15636. }
  15637. std::string msg;
  15638. while (ws.read(msg)) {
  15639. ws.send(msg);
  15640. }
  15641. });
  15642. auto port = svr.bind_to_any_port("localhost");
  15643. std::thread t([&]() { svr.listen_after_bind(); });
  15644. svr.wait_until_ready();
  15645. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15646. "/ws?token=ABC&session=123");
  15647. ASSERT_TRUE(client.connect());
  15648. // Round-trip ensures the handler has run and captured the request.
  15649. ASSERT_TRUE(client.send("hello"));
  15650. std::string msg;
  15651. ASSERT_TRUE(client.read(msg));
  15652. EXPECT_EQ("hello", msg);
  15653. client.close();
  15654. {
  15655. std::lock_guard<std::mutex> lock(mtx);
  15656. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15657. EXPECT_EQ("ABC", received_token);
  15658. }
  15659. svr.stop();
  15660. t.join();
  15661. }
  15662. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15663. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15664. protected:
  15665. void SetUp() override {
  15666. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15667. SERVER_PRIVATE_KEY_FILE);
  15668. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15669. std::string msg;
  15670. ws::ReadResult ret;
  15671. while ((ret = ws.read(msg))) {
  15672. if (ret == ws::Binary) {
  15673. ws.send(msg.data(), msg.size());
  15674. } else {
  15675. ws.send(msg);
  15676. }
  15677. }
  15678. });
  15679. port_ = server_->bind_to_any_port(HOST);
  15680. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15681. server_->wait_until_ready();
  15682. }
  15683. void TearDown() override {
  15684. server_->stop();
  15685. if (server_thread_.joinable()) { server_thread_.join(); }
  15686. }
  15687. std::unique_ptr<SSLServer> server_;
  15688. std::thread server_thread_;
  15689. int port_ = 0;
  15690. };
  15691. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15692. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15693. "/ws-echo");
  15694. client.enable_server_certificate_verification(false);
  15695. ASSERT_TRUE(client.connect());
  15696. ASSERT_TRUE(client.is_open());
  15697. ASSERT_TRUE(client.send("Hello WSS"));
  15698. std::string msg;
  15699. EXPECT_EQ(ws::Text, client.read(msg));
  15700. EXPECT_EQ("Hello WSS", msg);
  15701. client.close();
  15702. }
  15703. #endif
  15704. #ifdef CPPHTTPLIB_SSL_ENABLED
  15705. class WebSocketSSLCATest : public ::testing::Test {
  15706. protected:
  15707. void SetUp() override {
  15708. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  15709. SERVER_PRIVATE_KEY_FILE);
  15710. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15711. std::string msg;
  15712. while (ws.read(msg)) {
  15713. ws.send(msg);
  15714. }
  15715. });
  15716. port_ = server_->bind_to_any_port("127.0.0.1");
  15717. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15718. server_->wait_until_ready();
  15719. }
  15720. void TearDown() override {
  15721. server_->stop();
  15722. if (server_thread_.joinable()) { server_thread_.join(); }
  15723. }
  15724. std::string url() const {
  15725. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  15726. }
  15727. std::unique_ptr<SSLServer> server_;
  15728. std::thread server_thread_;
  15729. int port_ = 0;
  15730. };
  15731. // A custom CA loaded as PEM verifies the server with full certificate
  15732. // verification enabled
  15733. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  15734. ws::WebSocketClient client(url());
  15735. std::string cert;
  15736. read_file(SERVER_CERT2_FILE, cert);
  15737. client.load_ca_cert_store(cert.c_str(), cert.size());
  15738. ASSERT_TRUE(client.connect());
  15739. ASSERT_TRUE(client.send("hello"));
  15740. std::string msg;
  15741. EXPECT_EQ(ws::Text, client.read(msg));
  15742. EXPECT_EQ("hello", msg);
  15743. client.close();
  15744. }
  15745. // A custom CA that does not cover the server must fail verification (the
  15746. // custom CA is exclusive; system certs are not loaded alongside it)
  15747. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  15748. ws::WebSocketClient client(url());
  15749. std::string cert;
  15750. read_file(CLIENT_CA_CERT_FILE, cert);
  15751. client.load_ca_cert_store(cert.c_str(), cert.size());
  15752. ASSERT_FALSE(client.connect());
  15753. }
  15754. // Regression test: reconnecting with a native custom CA store used to reuse
  15755. // a store handle the previous TLS context had already freed (use-after-free
  15756. // under the OpenSSL backend). The context now lives as long as the client.
  15757. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  15758. ws::WebSocketClient client(url());
  15759. std::string cert;
  15760. read_file(SERVER_CERT2_FILE, cert);
  15761. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15762. ASSERT_TRUE(client.connect());
  15763. client.close();
  15764. ASSERT_TRUE(client.connect());
  15765. ASSERT_TRUE(client.send("again"));
  15766. std::string msg;
  15767. EXPECT_EQ(ws::Text, client.read(msg));
  15768. EXPECT_EQ("again", msg);
  15769. client.close();
  15770. }
  15771. // Regression test: a certificate with a trusted chain but no identity match
  15772. // for the server IP must be rejected. The Mbed TLS backend used to skip
  15773. // verification entirely for IP hosts, so this connection succeeded there.
  15774. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  15775. // chain verification while the identity check must still fail.
  15776. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  15777. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15778. ASSERT_TRUE(svr.is_valid());
  15779. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15780. std::string msg;
  15781. while (ws.read(msg)) {
  15782. ws.send(msg);
  15783. }
  15784. });
  15785. auto port = svr.bind_to_any_port("127.0.0.1");
  15786. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15787. auto se = detail::scope_exit([&] {
  15788. svr.stop();
  15789. t.join();
  15790. });
  15791. svr.wait_until_ready();
  15792. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  15793. "/echo");
  15794. std::string cert;
  15795. read_file(SERVER_CERT_FILE, cert);
  15796. client.load_ca_cert_store(cert.c_str(), cert.size());
  15797. ASSERT_FALSE(client.connect());
  15798. }
  15799. #endif
  15800. #if !defined(_WIN32)
  15801. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  15802. auto secret_dir = std::string("./symlink_test_secret");
  15803. auto served_dir = std::string("./symlink_test_served");
  15804. auto secret_file = secret_dir + "/secret.txt";
  15805. auto symlink_path = served_dir + "/escape";
  15806. // Setup: create directories and files
  15807. mkdir(secret_dir.c_str(), 0755);
  15808. mkdir(served_dir.c_str(), 0755);
  15809. {
  15810. std::ofstream ofs(secret_file);
  15811. ofs << "SECRET_DATA";
  15812. }
  15813. // Create symlink using absolute path so it resolves correctly
  15814. #ifdef PATH_MAX
  15815. char abs_secret[PATH_MAX];
  15816. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  15817. #else
  15818. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  15819. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  15820. ASSERT_NE(nullptr, abs_secret);
  15821. #endif
  15822. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  15823. auto se = detail::scope_exit([&] {
  15824. unlink(symlink_path.c_str());
  15825. unlink(secret_file.c_str());
  15826. rmdir(served_dir.c_str());
  15827. rmdir(secret_dir.c_str());
  15828. });
  15829. Server svr;
  15830. svr.set_mount_point("/", served_dir);
  15831. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15832. auto se2 = detail::scope_exit([&] {
  15833. svr.stop();
  15834. listen_thread.join();
  15835. });
  15836. svr.wait_until_ready();
  15837. Client cli("localhost", PORT);
  15838. // Symlink pointing outside base dir should be blocked
  15839. auto res = cli.Get("/escape/secret.txt");
  15840. ASSERT_TRUE(res);
  15841. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15842. }
  15843. #endif
  15844. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15845. // A GET request with Content-Length to a static file handler must have its
  15846. // body drained before the keep-alive connection is reused. Otherwise the
  15847. // unread body bytes are interpreted as the next HTTP request.
  15848. //
  15849. // The body is sent AFTER receiving the first response (as in the original
  15850. // PoC) so that the stream_line_reader cannot buffer it together with the
  15851. // headers of the first request.
  15852. Server svr;
  15853. svr.set_mount_point("/", "./www");
  15854. std::atomic<int> smuggled_count(0);
  15855. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15856. smuggled_count++;
  15857. res.set_content("oops", "text/plain");
  15858. });
  15859. auto port = svr.bind_to_any_port("localhost");
  15860. thread t = thread([&] { svr.listen_after_bind(); });
  15861. auto se = detail::scope_exit([&] {
  15862. svr.stop();
  15863. t.join();
  15864. });
  15865. svr.wait_until_ready();
  15866. auto error = Error::Success;
  15867. auto sock = detail::create_client_socket(
  15868. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15869. /*connection_timeout_sec=*/2, 0,
  15870. /*read_timeout_sec=*/2, 0,
  15871. /*write_timeout_sec=*/2, 0, std::string(), error);
  15872. ASSERT_NE(INVALID_SOCKET, sock);
  15873. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15874. // The "smuggled" request will be sent as the body of the outer GET
  15875. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15876. "Host: localhost\r\n"
  15877. "Connection: close\r\n"
  15878. "\r\n";
  15879. // Step 1: Send only the outer request headers (no body yet)
  15880. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15881. "Host: localhost\r\n"
  15882. "Content-Length: " +
  15883. std::to_string(smuggled.size()) +
  15884. "\r\n"
  15885. "\r\n";
  15886. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15887. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15888. // Step 2: Read the first response (server serves file without reading body)
  15889. std::string first_response;
  15890. char buf[4096];
  15891. for (;;) {
  15892. auto n = recv(sock, buf, sizeof(buf), 0);
  15893. if (n <= 0) break;
  15894. first_response.append(buf, static_cast<size_t>(n));
  15895. // Stop once we have a complete response (headers + body)
  15896. auto hdr_end = first_response.find("\r\n\r\n");
  15897. if (hdr_end != std::string::npos) {
  15898. // Check for Content-Length to know when the body is complete
  15899. auto cl_pos = first_response.find("Content-Length:");
  15900. if (cl_pos != std::string::npos) {
  15901. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15902. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15903. auto cl = std::stoul(
  15904. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15905. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15906. } else {
  15907. break; // No Content-Length, assume headers-only response
  15908. }
  15909. }
  15910. }
  15911. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15912. // Step 3: Now send the body, which looks like a new HTTP request.
  15913. // On a vulnerable server the keep-alive loop reads this as a second request.
  15914. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15915. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15916. // Step 4: Try to read a second response (should NOT exist after fix)
  15917. std::string second_response;
  15918. for (;;) {
  15919. auto n = recv(sock, buf, sizeof(buf), 0);
  15920. if (n <= 0) break;
  15921. second_response.append(buf, static_cast<size_t>(n));
  15922. }
  15923. // The smuggled request must NOT have been processed
  15924. EXPECT_EQ(0, smuggled_count.load());
  15925. }
  15926. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15927. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15928. // must be rejected with 400 Bad Request.
  15929. Server svr;
  15930. svr.Post("/test", [&](const Request &, Response &res) {
  15931. res.set_content("ok", "text/plain");
  15932. });
  15933. thread t = thread([&] { svr.listen(HOST, PORT); });
  15934. auto se = detail::scope_exit([&] {
  15935. svr.stop();
  15936. t.join();
  15937. ASSERT_FALSE(svr.is_running());
  15938. });
  15939. svr.wait_until_ready();
  15940. // Exact "chunked"
  15941. {
  15942. auto req = "POST /test HTTP/1.1\r\n"
  15943. "Host: localhost\r\n"
  15944. "Content-Length: 5\r\n"
  15945. "Transfer-Encoding: chunked\r\n"
  15946. "Connection: close\r\n"
  15947. "\r\n"
  15948. "hello";
  15949. std::string response;
  15950. ASSERT_TRUE(send_request(1, req, &response));
  15951. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15952. response.substr(0, response.find("\r\n")));
  15953. }
  15954. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15955. {
  15956. auto req = "POST /test HTTP/1.1\r\n"
  15957. "Host: localhost\r\n"
  15958. "Content-Length: 5\r\n"
  15959. "Transfer-Encoding: gzip, chunked\r\n"
  15960. "Connection: close\r\n"
  15961. "\r\n"
  15962. "hello";
  15963. std::string response;
  15964. ASSERT_TRUE(send_request(1, req, &response));
  15965. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15966. response.substr(0, response.find("\r\n")));
  15967. }
  15968. }
  15969. // Regression for issue #2450: a DELETE without Content-Length on a
  15970. // keep-alive connection must not let the post-response drain consume the
  15971. // next request's bytes.
  15972. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  15973. Server svr;
  15974. std::atomic<int> delete_count(0);
  15975. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  15976. delete_count++;
  15977. res.status = StatusCode::NoContent_204;
  15978. });
  15979. auto port = svr.bind_to_any_port(HOST);
  15980. thread t = thread([&] { svr.listen_after_bind(); });
  15981. auto se = detail::scope_exit([&] {
  15982. svr.stop();
  15983. t.join();
  15984. });
  15985. svr.wait_until_ready();
  15986. auto error = Error::Success;
  15987. auto sock = detail::create_client_socket(
  15988. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15989. /*connection_timeout_sec=*/2, 0,
  15990. /*read_timeout_sec=*/2, 0,
  15991. /*write_timeout_sec=*/2, 0, std::string(), error);
  15992. ASSERT_NE(INVALID_SOCKET, sock);
  15993. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15994. auto send_request_and_read_response = [&](const std::string &req,
  15995. std::string &out) -> bool {
  15996. auto sent = send(sock, req.data(), req.size(), 0);
  15997. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  15998. char buf[4096];
  15999. for (;;) {
  16000. auto n = recv(sock, buf, sizeof(buf), 0);
  16001. if (n <= 0) { return !out.empty(); }
  16002. out.append(buf, static_cast<size_t>(n));
  16003. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16004. }
  16005. };
  16006. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16007. "Host: localhost\r\n"
  16008. "\r\n";
  16009. std::string resp1;
  16010. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16011. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16012. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16013. "Host: localhost\r\n"
  16014. "Connection: close\r\n"
  16015. "\r\n";
  16016. std::string resp2;
  16017. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16018. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16019. EXPECT_EQ(2, delete_count.load());
  16020. }
  16021. namespace no_proxy_test {
  16022. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16023. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16024. // calling listen().
  16025. class ScopedServer {
  16026. public:
  16027. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16028. ~ScopedServer() {
  16029. svr_.stop();
  16030. if (th_.joinable()) { th_.join(); }
  16031. }
  16032. Server &svr() { return svr_; }
  16033. int port() const { return port_; }
  16034. void listen() {
  16035. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16036. svr_.wait_until_ready();
  16037. }
  16038. private:
  16039. Server svr_;
  16040. std::thread th_;
  16041. int port_ = 0;
  16042. };
  16043. class ProxyAndTargetServers {
  16044. public:
  16045. ProxyAndTargetServers() {
  16046. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16047. proxy_hits_++;
  16048. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16049. res.set_content("via-proxy", "text/plain");
  16050. });
  16051. target_.Get(".*", [this](const Request &req, Response &res) {
  16052. target_hits_++;
  16053. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16054. res.set_content("direct", "text/plain");
  16055. });
  16056. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16057. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16058. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16059. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16060. proxy_mock_.wait_until_ready();
  16061. target_.wait_until_ready();
  16062. }
  16063. ~ProxyAndTargetServers() {
  16064. proxy_mock_.stop();
  16065. target_.stop();
  16066. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16067. if (target_thread_.joinable()) { target_thread_.join(); }
  16068. }
  16069. Server &proxy_mock() { return proxy_mock_; }
  16070. Server &target() { return target_; }
  16071. int proxy_port() const { return proxy_port_; }
  16072. int target_port() const { return target_port_; }
  16073. int proxy_hits() const { return proxy_hits_.load(); }
  16074. int target_hits() const { return target_hits_.load(); }
  16075. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16076. void reset_counters() {
  16077. proxy_hits_ = 0;
  16078. target_hits_ = 0;
  16079. last_had_proxy_authz_ = false;
  16080. }
  16081. private:
  16082. Server proxy_mock_;
  16083. Server target_;
  16084. std::thread proxy_thread_;
  16085. std::thread target_thread_;
  16086. int proxy_port_ = 0;
  16087. int target_port_ = 0;
  16088. std::atomic<int> proxy_hits_{0};
  16089. std::atomic<int> target_hits_{0};
  16090. std::atomic<bool> last_had_proxy_authz_{false};
  16091. };
  16092. inline std::unique_ptr<Client> make_client(const std::string &host,
  16093. ProxyAndTargetServers &s) {
  16094. auto cli = detail::make_unique<Client>(host, s.target_port());
  16095. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16096. cli->set_proxy("127.0.0.1", s.proxy_port());
  16097. return cli;
  16098. }
  16099. } // namespace no_proxy_test
  16100. using no_proxy_test::make_client;
  16101. using no_proxy_test::ProxyAndTargetServers;
  16102. TEST(NoProxyTest, ExactHostnameBypasses) {
  16103. ProxyAndTargetServers s;
  16104. auto cli = make_client("example.com", s);
  16105. cli->set_no_proxy({"example.com"});
  16106. auto res = cli->Get("/");
  16107. ASSERT_TRUE(res);
  16108. EXPECT_EQ(0, s.proxy_hits());
  16109. EXPECT_EQ(1, s.target_hits());
  16110. }
  16111. TEST(NoProxyTest, SubdomainBypasses) {
  16112. ProxyAndTargetServers s;
  16113. auto cli = make_client("foo.example.com", s);
  16114. cli->set_no_proxy({"example.com"});
  16115. auto res = cli->Get("/");
  16116. ASSERT_TRUE(res);
  16117. EXPECT_EQ(0, s.proxy_hits());
  16118. EXPECT_EQ(1, s.target_hits());
  16119. }
  16120. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16121. // Regression guard: "evilexample.com" must not be considered a subdomain
  16122. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16123. // check would let traffic bypass the proxy and leak credentials direct
  16124. // to the attacker host.
  16125. ProxyAndTargetServers s;
  16126. auto cli = make_client("evilexample.com", s);
  16127. cli->set_no_proxy({"example.com"});
  16128. auto res = cli->Get("/");
  16129. ASSERT_TRUE(res);
  16130. EXPECT_GE(s.proxy_hits(), 1);
  16131. EXPECT_EQ(0, s.target_hits());
  16132. }
  16133. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16134. ProxyAndTargetServers s;
  16135. auto cli = make_client("example.com.evil.com", s);
  16136. cli->set_no_proxy({"example.com"});
  16137. auto res = cli->Get("/");
  16138. ASSERT_TRUE(res);
  16139. EXPECT_GE(s.proxy_hits(), 1);
  16140. EXPECT_EQ(0, s.target_hits());
  16141. }
  16142. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16143. ProxyAndTargetServers s;
  16144. auto cli = make_client("example.com", s);
  16145. cli->set_no_proxy({".example.com"});
  16146. auto res = cli->Get("/");
  16147. ASSERT_TRUE(res);
  16148. EXPECT_EQ(0, s.proxy_hits());
  16149. EXPECT_EQ(1, s.target_hits());
  16150. }
  16151. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16152. ProxyAndTargetServers s;
  16153. auto cli = make_client("Example.COM", s);
  16154. cli->set_no_proxy({"EXAMPLE.com"});
  16155. auto res = cli->Get("/");
  16156. ASSERT_TRUE(res);
  16157. EXPECT_EQ(0, s.proxy_hits());
  16158. EXPECT_EQ(1, s.target_hits());
  16159. }
  16160. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16161. ProxyAndTargetServers s;
  16162. auto cli = make_client("example.com.", s);
  16163. cli->set_no_proxy({"example.com"});
  16164. auto res = cli->Get("/");
  16165. ASSERT_TRUE(res);
  16166. EXPECT_EQ(0, s.proxy_hits());
  16167. EXPECT_EQ(1, s.target_hits());
  16168. }
  16169. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16170. // Trailing dots must be normalized on BOTH sides — host and entry.
  16171. // An implementation that only strips the host-side trailing dot would
  16172. // fail to match host "example.com" against entry "example.com." because
  16173. // a literal substring search would compare 11 chars against 12.
  16174. ProxyAndTargetServers s;
  16175. auto cli = make_client("example.com", s);
  16176. cli->set_no_proxy({"example.com."});
  16177. auto res = cli->Get("/");
  16178. ASSERT_TRUE(res);
  16179. EXPECT_EQ(0, s.proxy_hits());
  16180. EXPECT_EQ(1, s.target_hits());
  16181. }
  16182. TEST(NoProxyTest, WildcardBypassesEverything) {
  16183. ProxyAndTargetServers s;
  16184. auto cli = make_client("anything.invalid.test", s);
  16185. cli->set_no_proxy({"*"});
  16186. auto res = cli->Get("/");
  16187. ASSERT_TRUE(res);
  16188. EXPECT_EQ(0, s.proxy_hits());
  16189. EXPECT_EQ(1, s.target_hits());
  16190. }
  16191. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16192. ProxyAndTargetServers s;
  16193. Client cli("127.0.0.1", s.target_port());
  16194. cli.set_proxy("127.0.0.1", s.proxy_port());
  16195. cli.set_no_proxy({"127.0.0.1"});
  16196. auto res = cli.Get("/");
  16197. ASSERT_TRUE(res);
  16198. EXPECT_EQ(0, s.proxy_hits());
  16199. EXPECT_EQ(1, s.target_hits());
  16200. }
  16201. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16202. ProxyAndTargetServers s;
  16203. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16204. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16205. cli.set_proxy("127.0.0.1", s.proxy_port());
  16206. cli.set_no_proxy({"::1"});
  16207. auto res = cli.Get("/");
  16208. ASSERT_TRUE(res);
  16209. EXPECT_EQ(0, s.proxy_hits());
  16210. EXPECT_EQ(1, s.target_hits());
  16211. }
  16212. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16213. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16214. // must still be recognized as IPv6 for CIDR matching. Implementations
  16215. // that detect IPv6 only when the host begins with '[' would parse the
  16216. // host as a hostname and miss the match.
  16217. ProxyAndTargetServers s;
  16218. Client cli("fe80::1", s.target_port());
  16219. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16220. cli.set_proxy("127.0.0.1", s.proxy_port());
  16221. cli.set_no_proxy({"fe80::/10"});
  16222. auto res = cli.Get("/");
  16223. ASSERT_TRUE(res);
  16224. EXPECT_EQ(0, s.proxy_hits());
  16225. EXPECT_EQ(1, s.target_hits());
  16226. }
  16227. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16228. ProxyAndTargetServers s;
  16229. Client cli("::1", s.target_port());
  16230. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16231. cli.set_proxy("127.0.0.1", s.proxy_port());
  16232. cli.set_no_proxy({"[::1]"});
  16233. auto res = cli.Get("/");
  16234. ASSERT_TRUE(res);
  16235. EXPECT_EQ(0, s.proxy_hits());
  16236. EXPECT_EQ(1, s.target_hits());
  16237. }
  16238. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16239. ProxyAndTargetServers s;
  16240. Client cli("fe80::1", s.target_port());
  16241. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16242. cli.set_proxy("127.0.0.1", s.proxy_port());
  16243. cli.set_no_proxy({"[fe80::]/10"});
  16244. auto res = cli.Get("/");
  16245. ASSERT_TRUE(res);
  16246. EXPECT_EQ(0, s.proxy_hits());
  16247. EXPECT_EQ(1, s.target_hits());
  16248. }
  16249. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16250. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16251. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16252. // tricks via address-family conversion.
  16253. ProxyAndTargetServers s;
  16254. Client cli("::ffff:127.0.0.1", s.target_port());
  16255. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16256. cli.set_proxy("127.0.0.1", s.proxy_port());
  16257. cli.set_no_proxy({"127.0.0.1"});
  16258. auto res = cli.Get("/");
  16259. ASSERT_TRUE(res);
  16260. EXPECT_GE(s.proxy_hits(), 1);
  16261. EXPECT_EQ(0, s.target_hits());
  16262. }
  16263. TEST(NoProxyTest, IPv4CidrMatch) {
  16264. ProxyAndTargetServers s;
  16265. Client cli("127.0.0.1", s.target_port());
  16266. cli.set_proxy("127.0.0.1", s.proxy_port());
  16267. cli.set_no_proxy({"127.0.0.0/8"});
  16268. auto res = cli.Get("/");
  16269. ASSERT_TRUE(res);
  16270. EXPECT_EQ(0, s.proxy_hits());
  16271. EXPECT_EQ(1, s.target_hits());
  16272. }
  16273. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16274. ProxyAndTargetServers s;
  16275. Client cli("127.0.0.1", s.target_port());
  16276. cli.set_proxy("127.0.0.1", s.proxy_port());
  16277. cli.set_no_proxy({"10.0.0.0/8"});
  16278. auto res = cli.Get("/");
  16279. ASSERT_TRUE(res);
  16280. EXPECT_GE(s.proxy_hits(), 1);
  16281. EXPECT_EQ(0, s.target_hits());
  16282. }
  16283. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16284. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16285. // IPv4 target matches.
  16286. ProxyAndTargetServers s;
  16287. Client cli("127.0.0.1", s.target_port());
  16288. cli.set_proxy("127.0.0.1", s.proxy_port());
  16289. cli.set_no_proxy({"0.0.0.0/0"});
  16290. auto res = cli.Get("/");
  16291. ASSERT_TRUE(res);
  16292. EXPECT_EQ(0, s.proxy_hits());
  16293. EXPECT_EQ(1, s.target_hits());
  16294. }
  16295. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16296. ProxyAndTargetServers s;
  16297. Client cli("127.0.0.1", s.target_port());
  16298. cli.set_proxy("127.0.0.1", s.proxy_port());
  16299. cli.set_no_proxy({"127.0.0.1"});
  16300. auto res = cli.Get("/");
  16301. ASSERT_TRUE(res);
  16302. EXPECT_EQ(0, s.proxy_hits());
  16303. EXPECT_EQ(1, s.target_hits());
  16304. }
  16305. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16306. ProxyAndTargetServers s;
  16307. Client cli("127.0.0.1", s.target_port());
  16308. cli.set_proxy("127.0.0.1", s.proxy_port());
  16309. cli.set_no_proxy({"127.0.0.0/33"});
  16310. auto res = cli.Get("/");
  16311. ASSERT_TRUE(res);
  16312. EXPECT_GE(s.proxy_hits(), 1);
  16313. EXPECT_EQ(0, s.target_hits());
  16314. }
  16315. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16316. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16317. ProxyAndTargetServers s;
  16318. Client cli("127.0.0.1", s.target_port());
  16319. cli.set_proxy("127.0.0.1", s.proxy_port());
  16320. cli.set_no_proxy({"127.0.0.1/"});
  16321. auto res = cli.Get("/");
  16322. ASSERT_TRUE(res);
  16323. EXPECT_GE(s.proxy_hits(), 1);
  16324. EXPECT_EQ(0, s.target_hits());
  16325. }
  16326. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16327. ProxyAndTargetServers s;
  16328. auto cli = make_client("internal.corp", s);
  16329. cli->set_proxy_basic_auth("u", "p");
  16330. cli->set_no_proxy({"internal.corp"});
  16331. auto res = cli->Get("/");
  16332. ASSERT_TRUE(res);
  16333. EXPECT_EQ(1, s.target_hits());
  16334. EXPECT_EQ(0, s.proxy_hits());
  16335. EXPECT_FALSE(s.last_had_proxy_authz())
  16336. << "Proxy-Authorization must not be sent direct to the target";
  16337. }
  16338. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16339. ProxyAndTargetServers s;
  16340. auto cli = make_client("public.example", s);
  16341. cli->set_proxy_basic_auth("u", "p");
  16342. cli->set_no_proxy({"internal.corp"}); // does not match
  16343. auto res = cli->Get("/");
  16344. ASSERT_TRUE(res);
  16345. EXPECT_GE(s.proxy_hits(), 1);
  16346. EXPECT_TRUE(s.last_had_proxy_authz());
  16347. }
  16348. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16349. ProxyAndTargetServers s;
  16350. auto cli = make_client("anything.test", s);
  16351. auto res = cli->Get("/");
  16352. ASSERT_TRUE(res);
  16353. EXPECT_GE(s.proxy_hits(), 1);
  16354. EXPECT_EQ(0, s.target_hits());
  16355. }
  16356. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16357. ProxyAndTargetServers s;
  16358. auto cli = make_client("example.com", s);
  16359. cli->set_no_proxy({"example.com:8080"});
  16360. auto res = cli->Get("/");
  16361. ASSERT_TRUE(res);
  16362. EXPECT_GE(s.proxy_hits(), 1);
  16363. EXPECT_EQ(0, s.target_hits());
  16364. }
  16365. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16366. ProxyAndTargetServers s;
  16367. auto cli = make_client("anything.test", s);
  16368. cli->set_no_proxy({"", " ", "\t"});
  16369. auto res = cli->Get("/");
  16370. ASSERT_TRUE(res);
  16371. EXPECT_GE(s.proxy_hits(), 1);
  16372. EXPECT_EQ(0, s.target_hits());
  16373. }
  16374. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16375. // An entry with leading/trailing whitespace must still match — env-style
  16376. // values are commonly pasted with stray spaces and an implementation
  16377. // that feeds the raw token directly to inet_pton would fail to match
  16378. // valid CIDRs because of the spaces.
  16379. ProxyAndTargetServers s;
  16380. Client cli("127.0.0.1", s.target_port());
  16381. cli.set_proxy("127.0.0.1", s.proxy_port());
  16382. cli.set_no_proxy({" 127.0.0.0/8 "});
  16383. auto res = cli.Get("/");
  16384. ASSERT_TRUE(res);
  16385. EXPECT_EQ(0, s.proxy_hits());
  16386. EXPECT_EQ(1, s.target_hits());
  16387. }
  16388. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16389. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16390. // go direct and must NOT carry Proxy-Authorization.
  16391. std::atomic<int> proxy_hits{0};
  16392. std::atomic<int> target_hits{0};
  16393. std::atomic<bool> target_saw_authz{false};
  16394. no_proxy_test::ScopedServer proxy_mock, target;
  16395. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16396. proxy_hits++;
  16397. res.status = 302;
  16398. res.set_header("Location", "http://127.0.0.1:" +
  16399. std::to_string(target.port()) + "/landed");
  16400. });
  16401. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16402. target_hits++;
  16403. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16404. res.set_content("direct", "text/plain");
  16405. });
  16406. proxy_mock.listen();
  16407. target.listen();
  16408. Client cli("public.example", target.port());
  16409. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16410. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16411. cli.set_proxy_basic_auth("u", "p");
  16412. cli.set_no_proxy({"127.0.0.1"});
  16413. cli.set_follow_location(true);
  16414. auto res = cli.Get("/redir");
  16415. ASSERT_TRUE(res);
  16416. EXPECT_GE(proxy_hits.load(), 1);
  16417. EXPECT_GE(target_hits.load(), 1);
  16418. EXPECT_FALSE(target_saw_authz.load());
  16419. }
  16420. #ifdef CPPHTTPLIB_SSL_ENABLED
  16421. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16422. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16423. // proxy creds would be sent to the (possibly hostile) origin.
  16424. std::atomic<int> target_hits{0};
  16425. std::atomic<bool> target_saw_proxy_authz{false};
  16426. no_proxy_test::ScopedServer target;
  16427. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16428. target_hits++;
  16429. if (req.has_header("Proxy-Authorization")) {
  16430. target_saw_proxy_authz = true;
  16431. }
  16432. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16433. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16434. "nonce=\"abc\", algorithm=MD5");
  16435. });
  16436. target.listen();
  16437. // The proxy address is set to the target's port: the bypass MUST kick in;
  16438. // if it doesn't, the test still routes "via proxy" to the same server and
  16439. // the Proxy-Authorization assertion below catches the leak.
  16440. Client cli("evil.example", target.port());
  16441. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16442. cli.set_proxy("127.0.0.1", target.port());
  16443. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16444. cli.set_no_proxy({"evil.example"});
  16445. auto res = cli.Get("/x");
  16446. ASSERT_TRUE(res);
  16447. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16448. EXPECT_EQ(1, target_hits.load());
  16449. EXPECT_FALSE(target_saw_proxy_authz.load());
  16450. }
  16451. #endif
  16452. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16453. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16454. std::atomic<int> proxy_hits{0};
  16455. std::atomic<int> bypass_hits{0};
  16456. std::atomic<bool> proxy_saw_c_url{false};
  16457. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16458. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16459. proxy_hits++;
  16460. if (req.path.find("/start") != std::string::npos) {
  16461. res.status = 302;
  16462. res.set_header("Location", "http://127.0.0.1:" +
  16463. std::to_string(bypass_server.port()) +
  16464. "/middle");
  16465. return;
  16466. }
  16467. if (req.path.find("/end") != std::string::npos) {
  16468. proxy_saw_c_url = true;
  16469. res.set_content("c-via-proxy", "text/plain");
  16470. return;
  16471. }
  16472. res.set_content("unexpected", "text/plain");
  16473. });
  16474. // public.example's "advertised" port is arbitrary (the request never lands
  16475. // there — it goes through the proxy), but use a dynamic value to stay
  16476. // friendly with sharded parallel runs.
  16477. int public_port = bypass_server.port();
  16478. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16479. bypass_hits++;
  16480. res.status = 302;
  16481. res.set_header("Location", "http://public.example:" +
  16482. std::to_string(public_port) + "/end");
  16483. });
  16484. proxy_mock.listen();
  16485. bypass_server.listen();
  16486. Client cli("public.example", public_port);
  16487. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16488. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16489. cli.set_no_proxy({"127.0.0.1"});
  16490. cli.set_follow_location(true);
  16491. auto res = cli.Get("/start");
  16492. ASSERT_TRUE(res);
  16493. EXPECT_EQ(StatusCode::OK_200, res->status);
  16494. EXPECT_EQ("c-via-proxy", res->body);
  16495. EXPECT_GE(proxy_hits.load(), 2);
  16496. EXPECT_GE(bypass_hits.load(), 1);
  16497. EXPECT_TRUE(proxy_saw_c_url.load());
  16498. }
  16499. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16500. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16501. // request reconnects to the correct endpoint.
  16502. std::atomic<int> proxy_hits{0};
  16503. std::atomic<int> target_hits{0};
  16504. no_proxy_test::ScopedServer proxy_mock, target;
  16505. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16506. proxy_hits++;
  16507. res.set_content("via-proxy", "text/plain");
  16508. });
  16509. target.svr().Get(".*", [&](const Request &, Response &res) {
  16510. target_hits++;
  16511. res.set_content("direct", "text/plain");
  16512. });
  16513. proxy_mock.listen();
  16514. target.listen();
  16515. Client cli("public.example", target.port());
  16516. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16517. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16518. cli.set_keep_alive(true);
  16519. auto res1 = cli.Get("/a");
  16520. ASSERT_TRUE(res1);
  16521. EXPECT_EQ("via-proxy", res1->body);
  16522. EXPECT_EQ(1, proxy_hits.load());
  16523. EXPECT_EQ(0, target_hits.load());
  16524. cli.set_no_proxy({"public.example"});
  16525. auto res2 = cli.Get("/b");
  16526. ASSERT_TRUE(res2);
  16527. EXPECT_EQ("direct", res2->body);
  16528. EXPECT_EQ(1, proxy_hits.load());
  16529. EXPECT_EQ(1, target_hits.load());
  16530. }
  16531. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16532. namespace proxy_tunnel_test {
  16533. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16534. class ScopedSSLServer {
  16535. public:
  16536. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16537. port_ = svr_.bind_to_any_port("127.0.0.1");
  16538. }
  16539. ~ScopedSSLServer() {
  16540. svr_.stop();
  16541. if (th_.joinable()) { th_.join(); }
  16542. }
  16543. SSLServer &svr() { return svr_; }
  16544. int port() const { return port_; }
  16545. void listen() {
  16546. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16547. svr_.wait_until_ready();
  16548. }
  16549. private:
  16550. SSLServer svr_;
  16551. std::thread th_;
  16552. int port_ = 0;
  16553. };
  16554. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16555. class ScopedConnectProxy {
  16556. public:
  16557. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16558. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16559. if (listen_fd_ < 0) { return; }
  16560. int yes = 1;
  16561. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16562. sockaddr_in a{};
  16563. a.sin_family = AF_INET;
  16564. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16565. a.sin_port = 0;
  16566. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16567. return;
  16568. }
  16569. socklen_t alen = sizeof(a);
  16570. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16571. 0) {
  16572. return;
  16573. }
  16574. port_ = ntohs(a.sin_port);
  16575. if (::listen(listen_fd_, 1) != 0) { return; }
  16576. th_ = std::thread([this] { run(); });
  16577. }
  16578. ~ScopedConnectProxy() {
  16579. stop_ = true;
  16580. if (listen_fd_ >= 0) {
  16581. ::shutdown(listen_fd_, SHUT_RDWR);
  16582. ::close(listen_fd_);
  16583. }
  16584. if (th_.joinable()) { th_.join(); }
  16585. }
  16586. int port() const { return port_; }
  16587. int connect_hits() const { return connect_hits_.load(); }
  16588. private:
  16589. void run() {
  16590. while (!stop_.load()) {
  16591. fd_set rfds;
  16592. FD_ZERO(&rfds);
  16593. FD_SET(listen_fd_, &rfds);
  16594. timeval tv{0, 100 * 1000};
  16595. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16596. if (sel <= 0) { continue; }
  16597. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16598. if (client_fd < 0) { continue; }
  16599. std::string req;
  16600. char buf[2048];
  16601. while (req.find("\r\n\r\n") == std::string::npos) {
  16602. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16603. if (n <= 0) { break; }
  16604. req.append(buf, static_cast<size_t>(n));
  16605. }
  16606. if (req.compare(0, 7, "CONNECT") != 0) {
  16607. ::close(client_fd);
  16608. continue;
  16609. }
  16610. connect_hits_++;
  16611. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16612. ::send(client_fd, ok, std::strlen(ok), 0);
  16613. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16614. sockaddr_in o{};
  16615. o.sin_family = AF_INET;
  16616. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16617. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16618. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16619. 0) {
  16620. ::close(client_fd);
  16621. ::close(origin_fd);
  16622. continue;
  16623. }
  16624. auto forward = [](int from, int to) {
  16625. char b[8192];
  16626. for (;;) {
  16627. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16628. if (n <= 0) { break; }
  16629. ssize_t off = 0;
  16630. while (off < n) {
  16631. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16632. if (s <= 0) {
  16633. off = n;
  16634. break;
  16635. }
  16636. off += s;
  16637. }
  16638. }
  16639. ::shutdown(to, SHUT_WR);
  16640. };
  16641. std::thread t1([&] { forward(client_fd, origin_fd); });
  16642. std::thread t2([&] { forward(origin_fd, client_fd); });
  16643. t1.join();
  16644. t2.join();
  16645. ::close(client_fd);
  16646. ::close(origin_fd);
  16647. }
  16648. }
  16649. int forward_port_ = -1;
  16650. int listen_fd_ = -1;
  16651. int port_ = 0;
  16652. std::thread th_;
  16653. std::atomic<bool> stop_{false};
  16654. std::atomic<int> connect_hits_{0};
  16655. };
  16656. } // namespace proxy_tunnel_test
  16657. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  16658. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  16659. // retry; otherwise proxy creds would be sent to the origin.
  16660. std::atomic<int> origin_hits{0};
  16661. std::atomic<bool> origin_saw_proxy_authz{false};
  16662. proxy_tunnel_test::ScopedSSLServer origin;
  16663. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  16664. origin_hits++;
  16665. if (req.has_header("Proxy-Authorization")) {
  16666. origin_saw_proxy_authz = true;
  16667. }
  16668. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16669. res.set_header("Proxy-Authenticate",
  16670. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  16671. "algorithm=MD5");
  16672. });
  16673. origin.listen();
  16674. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  16675. ASSERT_NE(0, proxy.port());
  16676. SSLClient cli(HOST, origin.port());
  16677. cli.enable_server_certificate_verification(false);
  16678. cli.set_proxy(HOST, proxy.port());
  16679. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16680. auto res = cli.Get("/x");
  16681. ASSERT_TRUE(res);
  16682. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16683. EXPECT_EQ(1, origin_hits.load());
  16684. EXPECT_FALSE(origin_saw_proxy_authz.load());
  16685. EXPECT_EQ(1, proxy.connect_hits());
  16686. }
  16687. #endif