test.cc 554 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(SetSocketOptTest, TcpNoDelay) {
  269. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_NE(sock, INVALID_SOCKET);
  271. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  272. int val = 0;
  273. socklen_t len = sizeof(val);
  274. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  275. reinterpret_cast<char *>(&val), &len));
  276. EXPECT_NE(val, 0);
  277. detail::close_socket(sock);
  278. }
  279. TEST(ClientTest, MoveConstructible) {
  280. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  281. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  282. }
  283. TEST(ClientTest, MoveAssignable) {
  284. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  285. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  286. }
  287. #ifdef _WIN32
  288. TEST(StartupTest, WSAStartup) {
  289. WSADATA wsaData;
  290. int ret = WSAStartup(0x0002, &wsaData);
  291. ASSERT_EQ(0, ret);
  292. }
  293. #endif
  294. TEST(DecodePathTest, PercentCharacter) {
  295. EXPECT_EQ(
  296. decode_path_component(
  297. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  298. U8("descrip=Gastos áéíóúñÑ 6"));
  299. }
  300. TEST(DecodePathTest, PercentCharacterNUL) {
  301. string expected;
  302. expected.push_back('x');
  303. expected.push_back('\0');
  304. expected.push_back('x');
  305. EXPECT_EQ(decode_path_component("x%00x"), expected);
  306. }
  307. TEST(DecodePathTest, UnicodeEncoding) {
  308. // %u0041 = 'A' (1-byte UTF-8)
  309. EXPECT_EQ("A", decode_path_component("%u0041"));
  310. // %u00E9 = 'é' (2-byte UTF-8)
  311. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  312. // %u3042 = 'あ' (3-byte UTF-8)
  313. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  314. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  315. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  316. // %uD800 = surrogate (invalid, silently dropped)
  317. EXPECT_EQ("", decode_path_component("%uD800"));
  318. }
  319. TEST(SanitizeFilenameTest, VariousPatterns) {
  320. // Path traversal
  321. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  322. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  323. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  324. // Normal and edge cases
  325. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  326. EXPECT_EQ("filename.txt",
  327. httplib::sanitize_filename("/path/to/filename.txt"));
  328. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  329. EXPECT_EQ("", httplib::sanitize_filename(".."));
  330. EXPECT_EQ("", httplib::sanitize_filename(""));
  331. // Null bytes stripped
  332. EXPECT_EQ("safe.txt",
  333. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  334. // Whitespace-only rejected
  335. EXPECT_EQ("", httplib::sanitize_filename(" "));
  336. }
  337. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  338. string unescapedCharacters = "-_.!~*'()";
  339. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  340. }
  341. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  342. string reservedCharacters = ";,/?:@&=+$";
  343. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  344. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  345. }
  346. TEST(ClientQueryOrder, PreserveOrder) {
  347. // This test reproduces Issue #2259: client may reorder query parameters
  348. // when sending a GET request. The expected behavior is that the client
  349. // preserves the original query string order when the caller supplied it
  350. // as part of the path.
  351. Server svr;
  352. svr.Get("/", [&](const Request &req, Response &res) {
  353. // Echo back the raw target so the test can assert ordering
  354. res.set_content(req.target, "text/plain");
  355. });
  356. std::thread t{[&] { svr.listen(HOST, PORT); }};
  357. auto se = detail::scope_exit([&] {
  358. svr.stop();
  359. t.join();
  360. ASSERT_FALSE(svr.is_running());
  361. });
  362. svr.wait_until_ready();
  363. Client cli(HOST, PORT);
  364. ASSERT_TRUE(cli.is_valid());
  365. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  366. auto res = cli.Get(original);
  367. ASSERT_TRUE(res);
  368. // Expect the echoed target to exactly match the original path (order
  369. // preserved)
  370. EXPECT_EQ(res->body, original);
  371. }
  372. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  373. string chineseCharacters = U8("中国語");
  374. string russianCharacters = U8("дом");
  375. string brazilianCharacters = U8("óculos");
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  383. string unescapedCharacters = "-_.!~*'()";
  384. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  385. }
  386. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  387. string reservedCharacters = ";,/?:@&=+$";
  388. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  389. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  390. }
  391. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  392. string chineseCharacters = U8("中国語");
  393. string russianCharacters = U8("дом");
  394. string brazilianCharacters = U8("óculos");
  395. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  396. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  397. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  398. "%D0%B4%D0%BE%D0%BC");
  399. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  400. }
  401. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  402. // Issue #2082 use case: encoding path component with ampersand
  403. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  404. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  405. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  406. }
  407. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  408. string unescapedCharacters = "-_.!~*'()";
  409. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  410. }
  411. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  412. string reservedCharacters = ";,/?:@&=+$#";
  413. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  414. }
  415. TEST(EncodeUriTest, TestUTF8Characters) {
  416. string chineseCharacters = U8("中国語");
  417. string russianCharacters = U8("дом");
  418. string brazilianCharacters = U8("óculos");
  419. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  420. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  421. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  422. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  423. }
  424. TEST(EncodeUriTest, TestCompleteUri) {
  425. string uri =
  426. "https://example.com/path/to/resource?query=value&param=test#fragment";
  427. EXPECT_EQ(
  428. httplib::encode_uri(uri),
  429. "https://example.com/path/to/resource?query=value&param=test#fragment");
  430. }
  431. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  432. string uri =
  433. "https://example.com/path with spaces/file name.html?q=hello world";
  434. EXPECT_EQ(httplib::encode_uri(uri),
  435. "https://example.com/path%20with%20spaces/"
  436. "file%20name.html?q=hello%20world");
  437. }
  438. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  439. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  440. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  441. }
  442. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  447. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  448. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  449. string encodedBrazilian = "%C3%B3culos";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  451. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  452. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  453. }
  454. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  455. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  457. "Piri Tommy Villiers - on & on");
  458. }
  459. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  461. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  462. }
  463. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  465. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  466. }
  467. TEST(DecodeUriTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriTest, TestCompleteUri) {
  476. string encodedUri = "https://example.com/path%20with%20spaces/"
  477. "file%20name.html?q=hello%20world";
  478. EXPECT_EQ(
  479. httplib::decode_uri(encodedUri),
  480. "https://example.com/path with spaces/file name.html?q=hello world");
  481. }
  482. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  483. string original =
  484. "https://example.com/path with spaces/file name.html?q=hello world";
  485. string encoded = httplib::encode_uri(original);
  486. string decoded = httplib::decode_uri(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  490. string original = "Piri Tommy Villiers - on & on";
  491. string encoded = httplib::encode_uri_component(original);
  492. string decoded = httplib::decode_uri_component(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(TrimTests, TrimStringTests) {
  496. EXPECT_EQ("abc", detail::trim_copy("abc"));
  497. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  498. EXPECT_TRUE(detail::trim_copy("").empty());
  499. }
  500. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  501. // Simple case without quality values
  502. std::vector<std::string> result1;
  503. EXPECT_TRUE(detail::parse_accept_header(
  504. "text/html,application/json,text/plain", result1));
  505. EXPECT_EQ(result1.size(), 3U);
  506. EXPECT_EQ(result1[0], "text/html");
  507. EXPECT_EQ(result1[1], "application/json");
  508. EXPECT_EQ(result1[2], "text/plain");
  509. // With quality values
  510. std::vector<std::string> result2;
  511. EXPECT_TRUE(detail::parse_accept_header(
  512. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  513. EXPECT_EQ(result2.size(), 3U);
  514. EXPECT_EQ(result2[0], "application/json"); // highest q value
  515. EXPECT_EQ(result2[1], "text/html");
  516. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  517. }
  518. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  519. // Mixed with and without quality values
  520. std::vector<std::string> result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  523. EXPECT_EQ(result.size(), 3U);
  524. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  525. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  526. EXPECT_EQ(result[2], "application/json"); // q=0.5
  527. }
  528. TEST(ParseAcceptHeaderTest, EdgeCases) {
  529. // Empty header
  530. std::vector<std::string> empty_result;
  531. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  532. EXPECT_TRUE(empty_result.empty());
  533. // Single type
  534. std::vector<std::string> single_result;
  535. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  536. EXPECT_EQ(single_result.size(), 1U);
  537. EXPECT_EQ(single_result[0], "application/json");
  538. // Wildcard types
  539. std::vector<std::string> wildcard_result;
  540. EXPECT_TRUE(detail::parse_accept_header(
  541. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  542. EXPECT_EQ(wildcard_result.size(), 3U);
  543. EXPECT_EQ(wildcard_result[0], "application/json");
  544. EXPECT_EQ(wildcard_result[1], "text/*");
  545. EXPECT_EQ(wildcard_result[2], "*/*");
  546. }
  547. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  548. // Common browser Accept header
  549. std::vector<std::string> browser_result;
  550. EXPECT_TRUE(
  551. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  552. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  553. browser_result));
  554. EXPECT_EQ(browser_result.size(), 6U);
  555. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  556. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  557. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  558. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  560. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  561. // API client header
  562. std::vector<std::string> api_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  565. api_result));
  566. EXPECT_EQ(api_result.size(), 3U);
  567. EXPECT_EQ(api_result[0], "application/json");
  568. EXPECT_EQ(api_result[1], "application/xml");
  569. EXPECT_EQ(api_result[2], "text/plain");
  570. }
  571. TEST(ParseAcceptHeaderTest, SpecialCases) {
  572. // Quality value with 3 decimal places
  573. std::vector<std::string> decimal_result;
  574. EXPECT_TRUE(detail::parse_accept_header(
  575. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  576. EXPECT_EQ(decimal_result.size(), 2U);
  577. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  578. EXPECT_EQ(decimal_result[1], "text/html");
  579. // Zero quality (should still be included but with lowest priority)
  580. std::vector<std::string> zero_q_result;
  581. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  582. zero_q_result));
  583. EXPECT_EQ(zero_q_result.size(), 2U);
  584. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  585. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  586. // No spaces around commas
  587. std::vector<std::string> no_space_result;
  588. EXPECT_TRUE(detail::parse_accept_header(
  589. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  590. no_space_result));
  591. EXPECT_EQ(no_space_result.size(), 3U);
  592. EXPECT_EQ(no_space_result[0], "text/html");
  593. EXPECT_EQ(no_space_result[1], "application/json");
  594. EXPECT_EQ(no_space_result[2], "text/plain");
  595. }
  596. TEST(ParseAcceptHeaderTest, InvalidCases) {
  597. std::vector<std::string> result;
  598. // Invalid quality value (> 1.0)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  601. // Invalid quality value (< 0.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  604. // Invalid quality value (not a number)
  605. EXPECT_FALSE(detail::parse_accept_header(
  606. "text/html;q=invalid,application/json", result));
  607. // Empty quality value
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=,application/json", result));
  610. // Invalid media type format (no slash and not wildcard)
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("invalidtype,application/json", result));
  613. // Empty media type
  614. result.clear();
  615. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  616. // Only commas
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  619. // Valid cases should still work
  620. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "*/*");
  623. EXPECT_TRUE(detail::parse_accept_header("*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*");
  626. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "text/*");
  629. }
  630. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  631. Server svr;
  632. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  633. EXPECT_EQ(req.accept_content_types.size(), 3U);
  634. EXPECT_EQ(req.accept_content_types[0], "application/json");
  635. EXPECT_EQ(req.accept_content_types[1], "text/html");
  636. EXPECT_EQ(req.accept_content_types[2], "*/*");
  637. res.set_content("ok", "text/plain");
  638. });
  639. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  640. EXPECT_TRUE(false);
  641. res.set_content("bad request", "text/plain");
  642. });
  643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  644. auto se = detail::scope_exit([&] {
  645. svr.stop();
  646. listen_thread.join();
  647. ASSERT_FALSE(svr.is_running());
  648. });
  649. svr.wait_until_ready();
  650. Client cli("localhost", PORT);
  651. {
  652. auto res =
  653. cli.Get("/accept_ok",
  654. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::OK_200, res->status);
  657. }
  658. {
  659. auto res = cli.Get("/accept_bad_request",
  660. {{"Accept", "text/html;q=abc,application/json"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  663. }
  664. }
  665. TEST(DivideTest, DivideStringTests) {
  666. auto divide = [](const std::string &str, char d) {
  667. std::string lhs;
  668. std::string rhs;
  669. detail::divide(str, d,
  670. [&](const char *lhs_data, std::size_t lhs_size,
  671. const char *rhs_data, std::size_t rhs_size) {
  672. lhs.assign(lhs_data, lhs_size);
  673. rhs.assign(rhs_data, rhs_size);
  674. });
  675. return std::make_pair(std::move(lhs), std::move(rhs));
  676. };
  677. {
  678. const auto res = divide("", '=');
  679. EXPECT_EQ(res.first, "");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "");
  686. }
  687. {
  688. const auto res = divide(" ", '=');
  689. EXPECT_EQ(res.first, " ");
  690. EXPECT_EQ(res.second, "");
  691. }
  692. {
  693. const auto res = divide("a", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "");
  696. }
  697. {
  698. const auto res = divide("a=", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "");
  701. }
  702. {
  703. const auto res = divide("=b", '=');
  704. EXPECT_EQ(res.first, "");
  705. EXPECT_EQ(res.second, "b");
  706. }
  707. {
  708. const auto res = divide("a=b", '=');
  709. EXPECT_EQ(res.first, "a");
  710. EXPECT_EQ(res.second, "b");
  711. }
  712. {
  713. const auto res = divide("a=b=", '=');
  714. EXPECT_EQ(res.first, "a");
  715. EXPECT_EQ(res.second, "b=");
  716. }
  717. {
  718. const auto res = divide("a=b=c", '=');
  719. EXPECT_EQ(res.first, "a");
  720. EXPECT_EQ(res.second, "b=c");
  721. }
  722. }
  723. TEST(SplitTest, ParseQueryString) {
  724. string s = "key1=val1&key2=val2&key3=val3";
  725. Params dic;
  726. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  727. [&](const char *b, const char *e) {
  728. string key, val;
  729. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  730. if (key.empty()) {
  731. key.assign(b2, e2);
  732. } else {
  733. val.assign(b2, e2);
  734. }
  735. });
  736. dic.emplace(key, val);
  737. });
  738. EXPECT_EQ("val1", dic.find("key1")->second);
  739. EXPECT_EQ("val2", dic.find("key2")->second);
  740. EXPECT_EQ("val3", dic.find("key3")->second);
  741. }
  742. TEST(SplitTest, ParseInvalidQueryTests) {
  743. {
  744. string s = " ";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. {
  750. string s = " = =";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. }
  756. TEST(ParseQueryTest, ParseQueryString) {
  757. {
  758. std::string s = "key1=val1&key2=val2&key3=val3";
  759. Params dic;
  760. detail::parse_query_text(s, dic);
  761. EXPECT_EQ("val1", dic.find("key1")->second);
  762. EXPECT_EQ("val2", dic.find("key2")->second);
  763. EXPECT_EQ("val3", dic.find("key3")->second);
  764. }
  765. {
  766. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  767. Params dic;
  768. detail::parse_query_text(s, dic);
  769. EXPECT_EQ("", dic.find("key1")->second);
  770. EXPECT_EQ("val1", dic.find("key2")->second);
  771. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  772. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  773. }
  774. }
  775. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  776. Params dic;
  777. EXPECT_EQ(detail::params_to_query_str(dic), "");
  778. dic.emplace("key1", "val1");
  779. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  780. dic.emplace("key2", "val2");
  781. dic.emplace("key3", "val3");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  783. }
  784. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  785. string content_type = "multipart/form-data; boundary=something";
  786. string boundary;
  787. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  788. EXPECT_TRUE(ret);
  789. EXPECT_EQ(boundary, "something");
  790. }
  791. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  792. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  793. string boundary;
  794. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  795. EXPECT_TRUE(ret);
  796. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  797. }
  798. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  799. string content_type =
  800. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  801. string boundary;
  802. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  803. EXPECT_TRUE(ret);
  804. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  805. }
  806. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  807. string content_type =
  808. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  809. string boundary;
  810. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  811. EXPECT_TRUE(ret);
  812. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  813. }
  814. TEST(GetHeaderValueTest, DefaultValue) {
  815. Headers headers = {{"Dummy", "Dummy"}};
  816. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  817. EXPECT_STREQ("text/plain", val);
  818. }
  819. TEST(GetHeaderValueTest, DefaultValueInt) {
  820. Headers headers = {{"Dummy", "Dummy"}};
  821. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  822. EXPECT_EQ(100ull, val);
  823. }
  824. TEST(GetHeaderValueTest, RegularValue) {
  825. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  826. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  827. EXPECT_STREQ("text/html", val);
  828. }
  829. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  830. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  831. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  832. EXPECT_STREQ("text/html", val);
  833. }
  834. TEST(GetHeaderValueTest, SetContent) {
  835. Response res;
  836. res.set_content("html", "text/html");
  837. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  838. res.set_content("text", "text/plain");
  839. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  840. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  841. }
  842. TEST(GetHeaderValueTest, RegularValueInt) {
  843. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  845. EXPECT_EQ(100ull, val);
  846. }
  847. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  848. Headers headers = {{"Content-Length", "x"}};
  849. auto is_invalid_value = false;
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  851. is_invalid_value);
  852. EXPECT_EQ(0ull, val);
  853. EXPECT_TRUE(is_invalid_value);
  854. }
  855. TEST(GetHeaderValueTest, Range) {
  856. {
  857. Headers headers = {make_range_header({{1, -1}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=-1", val);
  865. }
  866. {
  867. Headers headers = {make_range_header({{1, 10}})};
  868. auto val = detail::get_header_value(headers, "Range", 0, 0);
  869. EXPECT_STREQ("bytes=1-10", val);
  870. }
  871. {
  872. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  873. auto val = detail::get_header_value(headers, "Range", 0, 0);
  874. EXPECT_STREQ("bytes=1-10, 100-", val);
  875. }
  876. {
  877. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  878. auto val = detail::get_header_value(headers, "Range", 0, 0);
  879. EXPECT_STREQ("bytes=1-10, 100-200", val);
  880. }
  881. {
  882. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  883. auto val = detail::get_header_value(headers, "Range", 0, 0);
  884. EXPECT_STREQ("bytes=0-0, -1", val);
  885. }
  886. }
  887. TEST(ParseHeaderValueTest, Range) {
  888. {
  889. Ranges ranges;
  890. auto ret = detail::parse_range_header("bytes=1-", ranges);
  891. EXPECT_TRUE(ret);
  892. EXPECT_EQ(1u, ranges.size());
  893. EXPECT_EQ(1u, ranges[0].first);
  894. EXPECT_EQ(-1, ranges[0].second);
  895. }
  896. {
  897. Ranges ranges;
  898. auto ret = detail::parse_range_header("bytes=-1", ranges);
  899. EXPECT_TRUE(ret);
  900. EXPECT_EQ(1u, ranges.size());
  901. EXPECT_EQ(-1, ranges[0].first);
  902. EXPECT_EQ(1u, ranges[0].second);
  903. }
  904. {
  905. Ranges ranges;
  906. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  907. EXPECT_TRUE(ret);
  908. EXPECT_EQ(1u, ranges.size());
  909. EXPECT_EQ(1u, ranges[0].first);
  910. EXPECT_EQ(10u, ranges[0].second);
  911. }
  912. {
  913. Ranges ranges;
  914. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  915. EXPECT_FALSE(ret);
  916. }
  917. {
  918. Ranges ranges;
  919. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(2u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(-1, ranges[1].second);
  926. }
  927. {
  928. Ranges ranges;
  929. auto ret =
  930. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(3u, ranges.size());
  933. EXPECT_EQ(1u, ranges[0].first);
  934. EXPECT_EQ(10u, ranges[0].second);
  935. EXPECT_EQ(100u, ranges[1].first);
  936. EXPECT_EQ(200u, ranges[1].second);
  937. EXPECT_EQ(300u, ranges[2].first);
  938. EXPECT_EQ(400u, ranges[2].second);
  939. }
  940. {
  941. Ranges ranges;
  942. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  955. EXPECT_TRUE(ranges.empty());
  956. }
  957. }
  958. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  966. #else
  967. EXPECT_TRUE(ret == detail::EncodingType::None);
  968. #endif
  969. }
  970. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  971. Request req;
  972. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  973. Response res;
  974. res.set_header("Content-Type", "text/plain");
  975. auto ret = detail::encoding_type(req, res);
  976. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  978. #elif CPPHTTPLIB_ZLIB_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  980. #elif CPPHTTPLIB_ZSTD_SUPPORT
  981. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  982. #else
  983. EXPECT_TRUE(ret == detail::EncodingType::None);
  984. #endif
  985. }
  986. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  987. Request req;
  988. req.set_header("Accept-Encoding",
  989. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  990. Response res;
  991. res.set_header("Content-Type", "text/plain");
  992. auto ret = detail::encoding_type(req, res);
  993. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  994. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  995. #elif CPPHTTPLIB_ZLIB_SUPPORT
  996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  997. #elif CPPHTTPLIB_ZSTD_SUPPORT
  998. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  999. #else
  1000. EXPECT_TRUE(ret == detail::EncodingType::None);
  1001. #endif
  1002. }
  1003. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1004. // All supported encodings rejected with q=0 should return None
  1005. Request req;
  1006. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1007. Response res;
  1008. res.set_header("Content-Type", "text/plain");
  1009. auto ret = detail::encoding_type(req, res);
  1010. EXPECT_TRUE(ret == detail::EncodingType::None);
  1011. }
  1012. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1013. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1014. Request req;
  1015. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1016. Response res;
  1017. res.set_header("Content-Type", "text/plain");
  1018. auto ret = detail::encoding_type(req, res);
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. }
  1021. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1022. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1023. Request req;
  1024. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1025. Response res;
  1026. res.set_header("Content-Type", "text/plain");
  1027. auto ret = detail::encoding_type(req, res);
  1028. EXPECT_TRUE(ret == detail::EncodingType::None);
  1029. }
  1030. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1031. // RFC 7231: Accept-Encoding values are case-insensitive
  1032. Request req;
  1033. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1034. Response res;
  1035. res.set_header("Content-Type", "text/plain");
  1036. auto ret = detail::encoding_type(req, res);
  1037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1043. #else
  1044. EXPECT_TRUE(ret == detail::EncodingType::None);
  1045. #endif
  1046. }
  1047. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1048. // q value should determine priority, not hardcoded order
  1049. Request req;
  1050. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1051. Response res;
  1052. res.set_header("Content-Type", "text/plain");
  1053. auto ret = detail::encoding_type(req, res);
  1054. // gzip has highest q=1.0, so it should be selected even though
  1055. // br and zstd are also supported
  1056. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1060. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1062. #else
  1063. EXPECT_TRUE(ret == detail::EncodingType::None);
  1064. #endif
  1065. }
  1066. TEST(BufferStreamTest, read) {
  1067. detail::BufferStream strm1;
  1068. Stream &strm = strm1;
  1069. EXPECT_EQ(5, strm.write("hello"));
  1070. char buf[512];
  1071. EXPECT_EQ(2, strm.read(buf, 2));
  1072. EXPECT_EQ('h', buf[0]);
  1073. EXPECT_EQ('e', buf[1]);
  1074. EXPECT_EQ(2, strm.read(buf, 2));
  1075. EXPECT_EQ('l', buf[0]);
  1076. EXPECT_EQ('l', buf[1]);
  1077. EXPECT_EQ(1, strm.read(buf, 1));
  1078. EXPECT_EQ('o', buf[0]);
  1079. EXPECT_EQ(0, strm.read(buf, 1));
  1080. }
  1081. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1082. auto host = "www.httpwatch.com";
  1083. auto ip = hosted_at(host);
  1084. EXPECT_EQ("23.96.13.243", ip);
  1085. std::vector<std::string> addrs;
  1086. hosted_at(host, addrs);
  1087. EXPECT_EQ(1u, addrs.size());
  1088. }
  1089. #if 0 // It depends on each test environment...
  1090. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1091. auto host = "www.youtube.com";
  1092. std::vector<std::string> addrs;
  1093. hosted_at(host, addrs);
  1094. EXPECT_EQ(20u, addrs.size());
  1095. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1096. EXPECT_TRUE(it != addrs.end());
  1097. }
  1098. #endif
  1099. class ChunkedEncodingTest : public ::testing::Test {
  1100. protected:
  1101. ChunkedEncodingTest()
  1102. : cli_(HOST, PORT)
  1103. #ifdef CPPHTTPLIB_SSL_ENABLED
  1104. ,
  1105. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1106. #endif
  1107. {
  1108. cli_.set_connection_timeout(2);
  1109. #ifdef CPPHTTPLIB_SSL_ENABLED
  1110. cli_.enable_server_certificate_verification(false);
  1111. #endif
  1112. }
  1113. virtual void SetUp() {
  1114. read_file("./image.jpg", image_data_);
  1115. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. svr_.Get(
  1119. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1120. res.set_chunked_content_provider(
  1121. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1122. size_t remaining = image_data_.size() - offset;
  1123. if (remaining == 0) {
  1124. sink.done();
  1125. } else {
  1126. constexpr size_t CHUNK_SIZE = 1024;
  1127. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1128. sink.write(&image_data_[offset], send_size);
  1129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1130. }
  1131. return true;
  1132. });
  1133. });
  1134. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1135. svr_.wait_until_ready();
  1136. }
  1137. virtual void TearDown() {
  1138. svr_.stop();
  1139. if (!request_threads_.empty()) {
  1140. std::this_thread::sleep_for(std::chrono::seconds(1));
  1141. for (auto &t : request_threads_) {
  1142. t.join();
  1143. }
  1144. }
  1145. t_.join();
  1146. }
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. SSLClient cli_;
  1149. SSLServer svr_;
  1150. #else
  1151. Client cli_;
  1152. Server svr_;
  1153. #endif
  1154. thread t_;
  1155. std::vector<thread> request_threads_;
  1156. std::string image_data_;
  1157. };
  1158. TEST_F(ChunkedEncodingTest, NormalGet) {
  1159. auto res = cli_.Get("/chunked");
  1160. ASSERT_TRUE(res);
  1161. std::string out;
  1162. read_file("./image.jpg", out);
  1163. EXPECT_EQ(StatusCode::OK_200, res->status);
  1164. EXPECT_EQ(out, res->body);
  1165. }
  1166. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1167. std::string body;
  1168. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1169. body.append(data, data_length);
  1170. return true;
  1171. });
  1172. ASSERT_TRUE(res);
  1173. std::string out;
  1174. read_file("./image.jpg", out);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. EXPECT_EQ(out, body);
  1177. }
  1178. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1179. std::string body;
  1180. auto res = cli_.Get(
  1181. "/chunked",
  1182. [&](const Response &response) {
  1183. EXPECT_EQ(StatusCode::OK_200, response.status);
  1184. return true;
  1185. },
  1186. [&](const char *data, size_t data_length) {
  1187. body.append(data, data_length);
  1188. return true;
  1189. });
  1190. ASSERT_TRUE(res);
  1191. std::string out;
  1192. read_file("./image.jpg", out);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. EXPECT_EQ(out, body);
  1195. }
  1196. TEST(RangeTest, FromHTTPBin_Online) {
  1197. auto host = "httpbingo.org";
  1198. auto path = std::string{"/range/32"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(5);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_TRUE(res);
  1210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1211. EXPECT_EQ(StatusCode::OK_200, res->status);
  1212. }
  1213. {
  1214. Headers headers = {make_range_header({{1, -1}})};
  1215. auto res = cli.Get(path, headers);
  1216. ASSERT_TRUE(res);
  1217. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1219. }
  1220. {
  1221. Headers headers = {make_range_header({{1, 10}})};
  1222. auto res = cli.Get(path, headers);
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("bcdefghijk", res->body);
  1225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1226. }
  1227. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1228. // entire resource, while the original httpbin returned 200. Both are
  1229. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1230. {
  1231. Headers headers = {make_range_header({{0, 31}})};
  1232. auto res = cli.Get(path, headers);
  1233. ASSERT_TRUE(res);
  1234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1235. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1236. res->status == StatusCode::PartialContent_206);
  1237. }
  1238. {
  1239. Headers headers = {make_range_header({{0, -1}})};
  1240. auto res = cli.Get(path, headers);
  1241. ASSERT_TRUE(res);
  1242. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1243. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1244. res->status == StatusCode::PartialContent_206);
  1245. }
  1246. // go-httpbin returns 206 with clamped range for over-range requests,
  1247. // while the original httpbin returned 416. Both behaviors are observed
  1248. // in real servers, so we only verify the request succeeds.
  1249. {
  1250. Headers headers = {make_range_header({{0, 32}})};
  1251. auto res = cli.Get(path, headers);
  1252. ASSERT_TRUE(res);
  1253. }
  1254. }
  1255. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1256. auto host = "unresolvableaddress.local";
  1257. auto path = std::string{"/"};
  1258. #ifdef CPPHTTPLIB_SSL_ENABLED
  1259. auto port = 443;
  1260. SSLClient cli(host, port);
  1261. #else
  1262. auto port = 80;
  1263. Client cli(host, port);
  1264. #endif
  1265. cli.set_connection_timeout(1);
  1266. {
  1267. auto res = cli.Get(path);
  1268. ASSERT_FALSE(res);
  1269. }
  1270. std::this_thread::sleep_for(std::chrono::seconds(8));
  1271. }
  1272. #if defined(__linux__) && defined(__GLIBC__) && \
  1273. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1274. // Forward declaration: in split builds split.py strips `inline` and moves the
  1275. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1276. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1277. // against the symbol in both header-only and split builds.
  1278. namespace httplib {
  1279. namespace detail {
  1280. int getaddrinfo_with_timeout(const char *node, const char *service,
  1281. const struct addrinfo *hints,
  1282. struct addrinfo **res, time_t timeout_sec);
  1283. } // namespace detail
  1284. } // namespace httplib
  1285. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1286. //
  1287. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1288. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1289. // gai_suspend() call hits the connection timeout the function calls
  1290. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1291. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1292. // still alive and still references the now-destroyed stack frame.
  1293. //
  1294. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1295. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1296. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1297. // and runs them in a container.
  1298. namespace {
  1299. bool should_run_issue_2431_tests() {
  1300. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1301. return v && *v && std::string(v) != "0";
  1302. }
  1303. std::string unique_unresolvable_host(int n) {
  1304. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1305. // glibc still asks the configured nameserver — which is exactly the path
  1306. // we want to exercise. A unique label per call avoids the resolver cache.
  1307. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1308. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1309. std::to_string(n) + ".invalid";
  1310. }
  1311. } // namespace
  1312. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1313. if (!should_run_issue_2431_tests()) {
  1314. GTEST_SKIP()
  1315. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1316. }
  1317. for (int i = 0; i < 8; ++i) {
  1318. struct addrinfo hints;
  1319. memset(&hints, 0, sizeof(hints));
  1320. hints.ai_family = AF_UNSPEC;
  1321. hints.ai_socktype = SOCK_STREAM;
  1322. auto host = unique_unresolvable_host(i);
  1323. struct addrinfo *result = nullptr;
  1324. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1325. &result, /*timeout_sec=*/1);
  1326. if (rc == 0 && result) { freeaddrinfo(result); }
  1327. }
  1328. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1329. // stack region they still believe holds their gaicb.
  1330. std::this_thread::sleep_for(std::chrono::seconds(3));
  1331. }
  1332. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1333. if (!should_run_issue_2431_tests()) {
  1334. GTEST_SKIP()
  1335. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1336. }
  1337. std::atomic<bool> stop{false};
  1338. std::vector<std::thread> threads;
  1339. for (int t = 0; t < 8; ++t) {
  1340. threads.emplace_back([t, &stop] {
  1341. int i = 0;
  1342. while (!stop.load(std::memory_order_relaxed)) {
  1343. struct addrinfo hints;
  1344. memset(&hints, 0, sizeof(hints));
  1345. hints.ai_family = AF_UNSPEC;
  1346. hints.ai_socktype = SOCK_STREAM;
  1347. auto host = unique_unresolvable_host(t * 100000 + i++);
  1348. struct addrinfo *result = nullptr;
  1349. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1350. &result, /*timeout_sec=*/1);
  1351. if (rc == 0 && result) { freeaddrinfo(result); }
  1352. }
  1353. });
  1354. }
  1355. std::this_thread::sleep_for(std::chrono::seconds(8));
  1356. stop.store(true, std::memory_order_relaxed);
  1357. for (auto &th : threads) {
  1358. th.join();
  1359. }
  1360. std::this_thread::sleep_for(std::chrono::seconds(3));
  1361. }
  1362. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1363. if (!should_run_issue_2431_tests()) {
  1364. GTEST_SKIP()
  1365. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1366. }
  1367. std::atomic<bool> stop{false};
  1368. std::vector<std::thread> threads;
  1369. for (int t = 0; t < 8; ++t) {
  1370. threads.emplace_back([t, &stop] {
  1371. int i = 0;
  1372. while (!stop.load(std::memory_order_relaxed)) {
  1373. auto host = unique_unresolvable_host(t * 100000 + i++);
  1374. Client cli(host, 80);
  1375. cli.set_connection_timeout(1, 0);
  1376. cli.set_read_timeout(1, 0);
  1377. cli.set_write_timeout(1, 0);
  1378. (void)cli.Get("/");
  1379. }
  1380. });
  1381. }
  1382. std::this_thread::sleep_for(std::chrono::seconds(8));
  1383. stop.store(true, std::memory_order_relaxed);
  1384. for (auto &th : threads) {
  1385. th.join();
  1386. }
  1387. std::this_thread::sleep_for(std::chrono::seconds(3));
  1388. }
  1389. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1390. TEST(ConnectionErrorTest, InvalidHost) {
  1391. auto host = "-abcde.com";
  1392. #ifdef CPPHTTPLIB_SSL_ENABLED
  1393. auto port = 443;
  1394. SSLClient cli(host, port);
  1395. #else
  1396. auto port = 80;
  1397. Client cli(host, port);
  1398. #endif
  1399. cli.set_connection_timeout(std::chrono::seconds(2));
  1400. auto res = cli.Get("/");
  1401. ASSERT_TRUE(!res);
  1402. EXPECT_EQ(Error::Connection, res.error());
  1403. }
  1404. TEST(ConnectionErrorTest, InvalidHost2) {
  1405. auto host = "httpcan.org/";
  1406. #ifdef CPPHTTPLIB_SSL_ENABLED
  1407. SSLClient cli(host);
  1408. #else
  1409. Client cli(host);
  1410. #endif
  1411. cli.set_connection_timeout(std::chrono::seconds(2));
  1412. auto res = cli.Get("/");
  1413. ASSERT_TRUE(!res);
  1414. EXPECT_EQ(Error::Connection, res.error());
  1415. }
  1416. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1417. auto host = "httpcan.org/";
  1418. #ifdef CPPHTTPLIB_SSL_ENABLED
  1419. SSLClient cli(host);
  1420. #else
  1421. Client cli(host);
  1422. #endif
  1423. cli.set_connection_timeout(std::chrono::seconds(2));
  1424. auto res = cli.Get("/");
  1425. ASSERT_TRUE(!res);
  1426. stringstream s;
  1427. s << "error code: " << res.error();
  1428. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1429. }
  1430. TEST(ConnectionErrorTest, InvalidPort) {
  1431. auto host = "localhost";
  1432. auto port = 44380;
  1433. #ifdef CPPHTTPLIB_SSL_ENABLED
  1434. SSLClient cli(host, port);
  1435. #else
  1436. Client cli(host, port);
  1437. #endif
  1438. cli.set_connection_timeout(std::chrono::seconds(2));
  1439. auto res = cli.Get("/");
  1440. ASSERT_TRUE(!res);
  1441. EXPECT_TRUE(Error::Connection == res.error() ||
  1442. Error::ConnectionTimeout == res.error());
  1443. }
  1444. TEST(ConnectionErrorTest, Timeout_Online) {
  1445. auto host = "google.com";
  1446. #ifdef CPPHTTPLIB_SSL_ENABLED
  1447. auto port = 44380;
  1448. SSLClient cli(host, port);
  1449. #else
  1450. auto port = 8080;
  1451. Client cli(host, port);
  1452. #endif
  1453. cli.set_connection_timeout(std::chrono::seconds(2));
  1454. // only probe one address type so that the error reason
  1455. // correlates to the timed-out IPv4, not the unsupported
  1456. // IPv6 connection attempt
  1457. cli.set_address_family(AF_INET);
  1458. auto res = cli.Get("/");
  1459. ASSERT_TRUE(!res);
  1460. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1461. }
  1462. TEST(CancelTest, NoCancel_Online) {
  1463. auto host = "httpbingo.org";
  1464. auto path = std::string{"/range/32"};
  1465. #ifdef CPPHTTPLIB_SSL_ENABLED
  1466. auto port = 443;
  1467. SSLClient cli(host, port);
  1468. #else
  1469. auto port = 80;
  1470. Client cli(host, port);
  1471. #endif
  1472. cli.set_connection_timeout(std::chrono::seconds(5));
  1473. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1476. EXPECT_EQ(StatusCode::OK_200, res->status);
  1477. }
  1478. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1479. // Use /bytes with a large payload so that the DownloadProgress callback
  1480. // (which only fires for Content-Length responses) is invoked before the
  1481. // entire body is received, giving cancellation a chance to fire.
  1482. auto host = "httpbingo.org";
  1483. auto path = std::string{"/bytes/524288"};
  1484. #ifdef CPPHTTPLIB_SSL_ENABLED
  1485. auto port = 443;
  1486. SSLClient cli(host, port);
  1487. #else
  1488. auto port = 80;
  1489. Client cli(host, port);
  1490. #endif
  1491. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. ASSERT_TRUE(!res);
  1494. EXPECT_EQ(Error::Canceled, res.error());
  1495. }
  1496. TEST(CancelTest, WithCancelLargePayload_Online) {
  1497. auto host = "httpbingo.org";
  1498. auto path = std::string{"/bytes/524288"};
  1499. #ifdef CPPHTTPLIB_SSL_ENABLED
  1500. auto port = 443;
  1501. SSLClient cli(host, port);
  1502. #else
  1503. auto port = 80;
  1504. Client cli(host, port);
  1505. #endif
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. uint32_t count = 0;
  1508. auto res =
  1509. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelPost) {
  1514. Server svr;
  1515. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1535. Server svr;
  1536. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadPost) {
  1555. Server svr;
  1556. svr.set_payload_max_length(200 * 1024 * 1024);
  1557. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1558. res.set_content(LARGE_DATA, "text/plain");
  1559. });
  1560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1561. auto se = detail::scope_exit([&] {
  1562. svr.stop();
  1563. thread.join();
  1564. ASSERT_FALSE(svr.is_running());
  1565. });
  1566. svr.wait_until_ready();
  1567. Client cli(HOST, PORT);
  1568. cli.set_payload_max_length(200 * 1024 * 1024);
  1569. cli.set_connection_timeout(std::chrono::seconds(5));
  1570. auto res =
  1571. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1572. "application/json", [](uint64_t, uint64_t) { return false; });
  1573. ASSERT_TRUE(!res);
  1574. EXPECT_EQ(Error::Canceled, res.error());
  1575. }
  1576. TEST(CancelTest, NoCancelPut) {
  1577. Server svr;
  1578. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content("Hello World!", "text/plain");
  1580. });
  1581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. Client cli(HOST, PORT);
  1589. cli.set_connection_timeout(std::chrono::seconds(5));
  1590. auto res =
  1591. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1592. "application/json", [](uint64_t, uint64_t) { return true; });
  1593. ASSERT_TRUE(res);
  1594. EXPECT_EQ("Hello World!", res->body);
  1595. EXPECT_EQ(StatusCode::OK_200, res->status);
  1596. }
  1597. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1598. Server svr;
  1599. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1600. res.set_content("Hello World!", "text/plain");
  1601. });
  1602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1603. auto se = detail::scope_exit([&] {
  1604. svr.stop();
  1605. thread.join();
  1606. ASSERT_FALSE(svr.is_running());
  1607. });
  1608. svr.wait_until_ready();
  1609. Client cli(HOST, PORT);
  1610. cli.set_connection_timeout(std::chrono::seconds(5));
  1611. auto res =
  1612. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1613. "application/json", [](uint64_t, uint64_t) { return false; });
  1614. ASSERT_TRUE(!res);
  1615. EXPECT_EQ(Error::Canceled, res.error());
  1616. }
  1617. TEST(CancelTest, WithCancelLargePayloadPut) {
  1618. Server svr;
  1619. svr.set_payload_max_length(200 * 1024 * 1024);
  1620. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1621. res.set_content(LARGE_DATA, "text/plain");
  1622. });
  1623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1624. auto se = detail::scope_exit([&] {
  1625. svr.stop();
  1626. thread.join();
  1627. ASSERT_FALSE(svr.is_running());
  1628. });
  1629. svr.wait_until_ready();
  1630. Client cli(HOST, PORT);
  1631. cli.set_payload_max_length(200 * 1024 * 1024);
  1632. cli.set_connection_timeout(std::chrono::seconds(5));
  1633. auto res =
  1634. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1635. "application/json", [](uint64_t, uint64_t) { return false; });
  1636. ASSERT_TRUE(!res);
  1637. EXPECT_EQ(Error::Canceled, res.error());
  1638. }
  1639. TEST(CancelTest, NoCancelPatch) {
  1640. Server svr;
  1641. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1642. res.set_content("Hello World!", "text/plain");
  1643. });
  1644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1645. auto se = detail::scope_exit([&] {
  1646. svr.stop();
  1647. thread.join();
  1648. ASSERT_FALSE(svr.is_running());
  1649. });
  1650. svr.wait_until_ready();
  1651. Client cli(HOST, PORT);
  1652. cli.set_connection_timeout(std::chrono::seconds(5));
  1653. auto res =
  1654. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1655. "application/json", [](uint64_t, uint64_t) { return true; });
  1656. ASSERT_TRUE(res);
  1657. EXPECT_EQ("Hello World!", res->body);
  1658. EXPECT_EQ(StatusCode::OK_200, res->status);
  1659. }
  1660. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1661. Server svr;
  1662. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1663. res.set_content("Hello World!", "text/plain");
  1664. });
  1665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1666. auto se = detail::scope_exit([&] {
  1667. svr.stop();
  1668. thread.join();
  1669. ASSERT_FALSE(svr.is_running());
  1670. });
  1671. svr.wait_until_ready();
  1672. Client cli(HOST, PORT);
  1673. cli.set_connection_timeout(std::chrono::seconds(5));
  1674. auto res =
  1675. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1676. "application/json", [](uint64_t, uint64_t) { return false; });
  1677. ASSERT_TRUE(!res);
  1678. EXPECT_EQ(Error::Canceled, res.error());
  1679. }
  1680. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1681. Server svr;
  1682. svr.set_payload_max_length(200 * 1024 * 1024);
  1683. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1684. res.set_content(LARGE_DATA, "text/plain");
  1685. });
  1686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. thread.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. Client cli(HOST, PORT);
  1694. cli.set_payload_max_length(200 * 1024 * 1024);
  1695. cli.set_connection_timeout(std::chrono::seconds(5));
  1696. auto res =
  1697. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1698. "application/json", [](uint64_t, uint64_t) { return false; });
  1699. ASSERT_TRUE(!res);
  1700. EXPECT_EQ(Error::Canceled, res.error());
  1701. }
  1702. TEST(CancelTest, NoCancelDelete) {
  1703. Server svr;
  1704. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1705. res.set_content("Hello World!", "text/plain");
  1706. });
  1707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1708. auto se = detail::scope_exit([&] {
  1709. svr.stop();
  1710. thread.join();
  1711. ASSERT_FALSE(svr.is_running());
  1712. });
  1713. svr.wait_until_ready();
  1714. Client cli(HOST, PORT);
  1715. cli.set_connection_timeout(std::chrono::seconds(5));
  1716. auto res =
  1717. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1718. "application/json", [](uint64_t, uint64_t) { return true; });
  1719. ASSERT_TRUE(res);
  1720. EXPECT_EQ("Hello World!", res->body);
  1721. EXPECT_EQ(StatusCode::OK_200, res->status);
  1722. }
  1723. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1724. Server svr;
  1725. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1726. res.set_content("Hello World!", "text/plain");
  1727. });
  1728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1729. auto se = detail::scope_exit([&] {
  1730. svr.stop();
  1731. thread.join();
  1732. ASSERT_FALSE(svr.is_running());
  1733. });
  1734. svr.wait_until_ready();
  1735. Client cli(HOST, PORT);
  1736. cli.set_connection_timeout(std::chrono::seconds(5));
  1737. auto res =
  1738. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1739. "application/json", [](uint64_t, uint64_t) { return false; });
  1740. ASSERT_TRUE(!res);
  1741. EXPECT_EQ(Error::Canceled, res.error());
  1742. }
  1743. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1744. Server svr;
  1745. svr.set_payload_max_length(200 * 1024 * 1024);
  1746. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1747. res.set_content(LARGE_DATA, "text/plain");
  1748. });
  1749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1750. auto se = detail::scope_exit([&] {
  1751. svr.stop();
  1752. thread.join();
  1753. ASSERT_FALSE(svr.is_running());
  1754. });
  1755. svr.wait_until_ready();
  1756. Client cli(HOST, PORT);
  1757. cli.set_payload_max_length(200 * 1024 * 1024);
  1758. cli.set_connection_timeout(std::chrono::seconds(5));
  1759. auto res =
  1760. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1761. "application/json", [](uint64_t, uint64_t) { return false; });
  1762. ASSERT_TRUE(!res);
  1763. EXPECT_EQ(Error::Canceled, res.error());
  1764. }
  1765. static std::string remove_whitespace(const std::string &input) {
  1766. std::string output;
  1767. output.reserve(input.size());
  1768. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1769. [](unsigned char c) { return !std::isspace(c); });
  1770. return output;
  1771. }
  1772. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1773. auto host = "httpbingo.org";
  1774. auto path = std::string{"/basic-auth/hello/world"};
  1775. #ifdef CPPHTTPLIB_SSL_ENABLED
  1776. auto port = 443;
  1777. SSLClient cli(host, port);
  1778. #else
  1779. auto port = 80;
  1780. Client cli(host, port);
  1781. #endif
  1782. {
  1783. auto res = cli.Get(path);
  1784. ASSERT_TRUE(res);
  1785. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1786. }
  1787. {
  1788. auto res =
  1789. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1790. ASSERT_TRUE(res);
  1791. auto body = remove_whitespace(res->body);
  1792. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1793. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1794. EXPECT_EQ(StatusCode::OK_200, res->status);
  1795. }
  1796. {
  1797. cli.set_basic_auth("hello", "world");
  1798. auto res = cli.Get(path);
  1799. ASSERT_TRUE(res);
  1800. auto body = remove_whitespace(res->body);
  1801. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1802. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1803. EXPECT_EQ(StatusCode::OK_200, res->status);
  1804. }
  1805. {
  1806. cli.set_basic_auth("hello", "bad");
  1807. auto res = cli.Get(path);
  1808. ASSERT_TRUE(res);
  1809. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1810. }
  1811. {
  1812. cli.set_basic_auth("bad", "world");
  1813. auto res = cli.Get(path);
  1814. ASSERT_TRUE(res);
  1815. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1816. }
  1817. }
  1818. #ifdef CPPHTTPLIB_SSL_ENABLED
  1819. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1820. auto host = "httpbingo.org";
  1821. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1822. auto paths = std::vector<std::string>{
  1823. "/digest-auth/auth/hello/world/MD5",
  1824. "/digest-auth/auth/hello/world/SHA-256",
  1825. };
  1826. auto port = 443;
  1827. SSLClient cli(host, port);
  1828. {
  1829. auto res = cli.Get(unauth_path);
  1830. ASSERT_TRUE(res);
  1831. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1832. }
  1833. {
  1834. cli.set_digest_auth("hello", "world");
  1835. for (const auto &path : paths) {
  1836. auto res = cli.Get(path.c_str());
  1837. ASSERT_TRUE(res);
  1838. auto body = remove_whitespace(res->body);
  1839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. }
  1843. cli.set_digest_auth("hello", "bad");
  1844. for (const auto &path : paths) {
  1845. auto res = cli.Get(path.c_str());
  1846. ASSERT_TRUE(res);
  1847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1848. }
  1849. }
  1850. }
  1851. #endif
  1852. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1853. auto host = "google.com";
  1854. auto another_host = "example.com";
  1855. auto wrong_ip = "0.0.0.0";
  1856. #ifdef CPPHTTPLIB_SSL_ENABLED
  1857. SSLClient cli(host);
  1858. #else
  1859. Client cli(host);
  1860. #endif
  1861. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1862. auto res = cli.Get("/");
  1863. ASSERT_TRUE(res);
  1864. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1865. }
  1866. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1867. auto host = "google.com";
  1868. auto wrong_ip = "0.0.0.0";
  1869. #ifdef CPPHTTPLIB_SSL_ENABLED
  1870. SSLClient cli(host);
  1871. #else
  1872. Client cli(host);
  1873. #endif
  1874. cli.set_hostname_addr_map({{host, wrong_ip}});
  1875. auto res = cli.Get("/");
  1876. ASSERT_TRUE(!res);
  1877. EXPECT_EQ(Error::Connection, res.error());
  1878. }
  1879. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1880. auto host = "httpbingo.org";
  1881. auto path = std::string{"/absolute-redirect/3"};
  1882. #ifdef CPPHTTPLIB_SSL_ENABLED
  1883. SSLClient cli(host);
  1884. #else
  1885. Client cli(host);
  1886. #endif
  1887. cli.set_follow_location(true);
  1888. auto res = cli.Get(path);
  1889. ASSERT_TRUE(res);
  1890. EXPECT_EQ(StatusCode::OK_200, res->status);
  1891. }
  1892. TEST(RedirectTest, Redirect_Online) {
  1893. auto host = "httpbingo.org";
  1894. auto path = std::string{"/redirect/3"};
  1895. #ifdef CPPHTTPLIB_SSL_ENABLED
  1896. SSLClient cli(host);
  1897. #else
  1898. Client cli(host);
  1899. #endif
  1900. cli.set_follow_location(true);
  1901. auto res = cli.Get(path);
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(StatusCode::OK_200, res->status);
  1904. }
  1905. TEST(RelativeRedirectTest, Redirect_Online) {
  1906. auto host = "httpbingo.org";
  1907. auto path = std::string{"/relative-redirect/3"};
  1908. #ifdef CPPHTTPLIB_SSL_ENABLED
  1909. SSLClient cli(host);
  1910. #else
  1911. Client cli(host);
  1912. #endif
  1913. cli.set_follow_location(true);
  1914. auto res = cli.Get(path);
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(StatusCode::OK_200, res->status);
  1917. }
  1918. TEST(TooManyRedirectTest, Redirect_Online) {
  1919. auto host = "httpbingo.org";
  1920. auto path = std::string{"/redirect/21"};
  1921. #ifdef CPPHTTPLIB_SSL_ENABLED
  1922. SSLClient cli(host);
  1923. #else
  1924. Client cli(host);
  1925. #endif
  1926. cli.set_follow_location(true);
  1927. auto res = cli.Get(path);
  1928. ASSERT_TRUE(!res);
  1929. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1930. }
  1931. #ifdef CPPHTTPLIB_SSL_ENABLED
  1932. TEST(YahooRedirectTest, Redirect_Online) {
  1933. Client cli("yahoo.com");
  1934. auto res = cli.Get("/");
  1935. ASSERT_TRUE(res);
  1936. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1937. cli.set_follow_location(true);
  1938. res = cli.Get("/");
  1939. ASSERT_TRUE(res);
  1940. EXPECT_EQ(StatusCode::OK_200, res->status);
  1941. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1942. }
  1943. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1944. #define REDIR_HOST "httpbingo.org"
  1945. #define REDIR_PATH "/redirect-to"
  1946. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1947. SSLClient cli(REDIR_HOST);
  1948. cli.set_follow_location(true);
  1949. auto res =
  1950. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. }
  1954. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1955. SSLClient cli(REDIR_HOST);
  1956. cli.set_follow_location(true);
  1957. Params params;
  1958. params.emplace("url", "http://example.com");
  1959. params.emplace("status_code", "302");
  1960. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. }
  1964. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1965. SSLClient cli(REDIR_HOST);
  1966. cli.set_follow_location(true);
  1967. Params params;
  1968. params.emplace("url", "http://example.com");
  1969. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. }
  1973. TEST(UrlWithSpace, Redirect_Online) {
  1974. SSLClient cli("edge.forgecdn.net");
  1975. cli.set_follow_location(true);
  1976. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1977. ASSERT_TRUE(res);
  1978. EXPECT_EQ(StatusCode::OK_200, res->status);
  1979. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1980. }
  1981. #endif
  1982. #if !defined(_WIN32) && !defined(_WIN64)
  1983. TEST(ReceiveSignals, Signal) {
  1984. auto setupSignalHandlers = []() {
  1985. struct sigaction act;
  1986. sigemptyset(&act.sa_mask);
  1987. act.sa_flags = SA_SIGINFO;
  1988. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1989. switch (sig) {
  1990. case SIGINT:
  1991. default: break;
  1992. }
  1993. };
  1994. ::sigaction(SIGINT, &act, nullptr);
  1995. };
  1996. Server svr;
  1997. int port = 0;
  1998. auto thread = std::thread([&]() {
  1999. setupSignalHandlers();
  2000. port = svr.bind_to_any_port(HOST);
  2001. svr.listen_after_bind();
  2002. });
  2003. auto se = detail::scope_exit([&] {
  2004. svr.stop();
  2005. thread.join();
  2006. ASSERT_FALSE(svr.is_running());
  2007. });
  2008. svr.wait_until_ready();
  2009. ASSERT_TRUE(svr.is_running());
  2010. pthread_kill(thread.native_handle(), SIGINT);
  2011. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2012. ASSERT_TRUE(svr.is_running());
  2013. }
  2014. #endif
  2015. TEST(RedirectToDifferentPort, Redirect) {
  2016. Server svr1;
  2017. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("Hello World!", "text/plain");
  2019. });
  2020. int svr1_port = 0;
  2021. auto thread1 = std::thread([&]() {
  2022. svr1_port = svr1.bind_to_any_port(HOST);
  2023. svr1.listen_after_bind();
  2024. });
  2025. Server svr2;
  2026. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2027. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2028. });
  2029. int svr2_port = 0;
  2030. auto thread2 = std::thread([&]() {
  2031. svr2_port = svr2.bind_to_any_port(HOST);
  2032. svr2.listen_after_bind();
  2033. });
  2034. auto se = detail::scope_exit([&] {
  2035. svr2.stop();
  2036. thread2.join();
  2037. svr1.stop();
  2038. thread1.join();
  2039. ASSERT_FALSE(svr2.is_running());
  2040. ASSERT_FALSE(svr1.is_running());
  2041. });
  2042. svr1.wait_until_ready();
  2043. svr2.wait_until_ready();
  2044. Client cli("localhost", svr2_port);
  2045. cli.set_follow_location(true);
  2046. auto res = cli.Get("/2");
  2047. ASSERT_TRUE(res);
  2048. EXPECT_EQ(StatusCode::OK_200, res->status);
  2049. EXPECT_EQ("Hello World!", res->body);
  2050. }
  2051. static void
  2052. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2053. Server svr1;
  2054. std::string captured_authorization;
  2055. svr1.Get("/target", [&](const Request &req, Response &res) {
  2056. captured_authorization = req.get_header_value("Authorization");
  2057. res.set_content("OK", "text/plain");
  2058. });
  2059. int svr1_port = 0;
  2060. auto thread1 = std::thread([&]() {
  2061. svr1_port = svr1.bind_to_any_port(HOST);
  2062. svr1.listen_after_bind();
  2063. });
  2064. Server svr2;
  2065. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2066. res.set_redirect(
  2067. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2068. });
  2069. int svr2_port = 0;
  2070. auto thread2 = std::thread([&]() {
  2071. svr2_port = svr2.bind_to_any_port(HOST);
  2072. svr2.listen_after_bind();
  2073. });
  2074. auto se = detail::scope_exit([&] {
  2075. svr2.stop();
  2076. thread2.join();
  2077. svr1.stop();
  2078. thread1.join();
  2079. ASSERT_FALSE(svr2.is_running());
  2080. ASSERT_FALSE(svr1.is_running());
  2081. });
  2082. svr1.wait_until_ready();
  2083. svr2.wait_until_ready();
  2084. Client cli("localhost", svr2_port);
  2085. cli.set_follow_location(true);
  2086. set_auth(cli);
  2087. auto res = cli.Get("/redir");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::OK_200, res->status);
  2090. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2091. EXPECT_TRUE(captured_authorization.empty());
  2092. }
  2093. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2094. TestDoNotForwardCredentialsOnRedirect(
  2095. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2096. }
  2097. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2098. TestDoNotForwardCredentialsOnRedirect(
  2099. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2100. }
  2101. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2102. Server svr;
  2103. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2104. // Port number that overflows int — should not crash
  2105. res.set_redirect("http://localhost:99999999999999999999/target");
  2106. });
  2107. auto port = svr.bind_to_any_port(HOST);
  2108. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2109. auto se = detail::scope_exit([&] {
  2110. svr.stop();
  2111. thread.join();
  2112. ASSERT_FALSE(svr.is_running());
  2113. });
  2114. svr.wait_until_ready();
  2115. Client cli(HOST, port);
  2116. cli.set_follow_location(true);
  2117. auto res = cli.Get("/redir");
  2118. // Should fail gracefully, not crash (no valid response due to bad port)
  2119. EXPECT_FALSE(res);
  2120. }
  2121. TEST(RedirectFromPageWithContent, Redirect) {
  2122. Server svr;
  2123. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2124. res.set_content("___", "text/plain");
  2125. res.set_redirect("/2");
  2126. });
  2127. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2128. res.set_content("Hello World!", "text/plain");
  2129. });
  2130. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2131. auto se = detail::scope_exit([&] {
  2132. svr.stop();
  2133. th.join();
  2134. ASSERT_FALSE(svr.is_running());
  2135. });
  2136. svr.wait_until_ready();
  2137. {
  2138. Client cli("localhost", PORT);
  2139. cli.set_follow_location(true);
  2140. std::string body;
  2141. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2142. body.append(data, data_length);
  2143. return true;
  2144. });
  2145. ASSERT_TRUE(res);
  2146. EXPECT_EQ(StatusCode::OK_200, res->status);
  2147. EXPECT_EQ("Hello World!", body);
  2148. }
  2149. {
  2150. Client cli("localhost", PORT);
  2151. std::string body;
  2152. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2153. body.append(data, data_length);
  2154. return true;
  2155. });
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(StatusCode::Found_302, res->status);
  2158. EXPECT_EQ("___", body);
  2159. }
  2160. }
  2161. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2162. Server svr;
  2163. auto port_str = std::to_string(PORT);
  2164. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2165. auto expected_host = "[::1]:" + port_str;
  2166. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2167. res.set_content("___", "text/plain");
  2168. // res.set_redirect("/2");
  2169. res.set_redirect(redirect_url);
  2170. });
  2171. svr.Get("/2", [&](const Request &req, Response &res) {
  2172. auto host_header = req.headers.find("Host");
  2173. ASSERT_TRUE(host_header != req.headers.end());
  2174. EXPECT_EQ(expected_host, host_header->second);
  2175. res.set_content("Hello World!", "text/plain");
  2176. });
  2177. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2178. auto se = detail::scope_exit([&] {
  2179. svr.stop();
  2180. th.join();
  2181. ASSERT_FALSE(svr.is_running());
  2182. });
  2183. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2184. // actually starts anything, so the condition !svr.is_running() will
  2185. // always remain true, and the loop never stops.
  2186. // This basically counts how many milliseconds have passed since the
  2187. // call to svr.listen(), and if after 5 seconds nothing started yet
  2188. // aborts the test.
  2189. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2190. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2191. ASSERT_LT(milliseconds, 5000U);
  2192. }
  2193. {
  2194. Client cli("::1", PORT);
  2195. cli.set_follow_location(true);
  2196. std::string body;
  2197. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2198. body.append(data, data_length);
  2199. return true;
  2200. });
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::OK_200, res->status);
  2203. EXPECT_EQ("Hello World!", body);
  2204. }
  2205. {
  2206. Client cli("::1", PORT);
  2207. std::string body;
  2208. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2209. body.append(data, data_length);
  2210. return true;
  2211. });
  2212. ASSERT_TRUE(res);
  2213. EXPECT_EQ(StatusCode::Found_302, res->status);
  2214. EXPECT_EQ("___", body);
  2215. }
  2216. }
  2217. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2218. Server svr;
  2219. svr.Get("/foo", [](const Request &req, Response &res) {
  2220. auto a = req.params.find("a");
  2221. if (a != req.params.end()) {
  2222. res.set_content((*a).second, "text/plain");
  2223. res.status = StatusCode::OK_200;
  2224. } else {
  2225. res.status = StatusCode::BadRequest_400;
  2226. }
  2227. });
  2228. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2229. auto se = detail::scope_exit([&] {
  2230. svr.stop();
  2231. thread.join();
  2232. ASSERT_FALSE(svr.is_running());
  2233. });
  2234. svr.wait_until_ready();
  2235. {
  2236. Client cli(HOST, PORT);
  2237. cli.set_path_encode(false);
  2238. auto res = cli.Get("/foo?a=explicitly+encoded");
  2239. ASSERT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. // This expects it back with a space, as the `+` won't have been
  2242. // url-encoded, and server-side the params get decoded turning `+`
  2243. // into spaces.
  2244. EXPECT_EQ("explicitly encoded", res->body);
  2245. }
  2246. }
  2247. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2248. Server svr;
  2249. svr.Get("/", [](const Request &req, Response &) {
  2250. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2251. });
  2252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2253. auto se = detail::scope_exit([&] {
  2254. svr.stop();
  2255. thread.join();
  2256. ASSERT_FALSE(svr.is_running());
  2257. });
  2258. svr.wait_until_ready();
  2259. {
  2260. Client cli(HOST, PORT);
  2261. cli.set_path_encode(false);
  2262. auto res = cli.Get("/?something=%0A");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::OK_200, res->status);
  2265. }
  2266. }
  2267. TEST(BindServerTest, BindDualStack) {
  2268. Server svr;
  2269. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2270. res.set_content("Hello World!", "text/plain");
  2271. });
  2272. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2273. auto se = detail::scope_exit([&] {
  2274. svr.stop();
  2275. thread.join();
  2276. ASSERT_FALSE(svr.is_running());
  2277. });
  2278. svr.wait_until_ready();
  2279. {
  2280. Client cli("127.0.0.1", PORT);
  2281. auto res = cli.Get("/1");
  2282. ASSERT_TRUE(res);
  2283. EXPECT_EQ(StatusCode::OK_200, res->status);
  2284. EXPECT_EQ("Hello World!", res->body);
  2285. }
  2286. {
  2287. Client cli("::1", PORT);
  2288. auto res = cli.Get("/1");
  2289. ASSERT_TRUE(res);
  2290. EXPECT_EQ(StatusCode::OK_200, res->status);
  2291. EXPECT_EQ("Hello World!", res->body);
  2292. }
  2293. }
  2294. TEST(BindServerTest, BindAndListenSeparately) {
  2295. Server svr;
  2296. int port = svr.bind_to_any_port("0.0.0.0");
  2297. ASSERT_TRUE(svr.is_valid());
  2298. ASSERT_TRUE(port > 0);
  2299. svr.stop();
  2300. }
  2301. #ifdef CPPHTTPLIB_SSL_ENABLED
  2302. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2304. CLIENT_CA_CERT_DIR);
  2305. int port = svr.bind_to_any_port("0.0.0.0");
  2306. ASSERT_TRUE(svr.is_valid());
  2307. ASSERT_TRUE(port > 0);
  2308. svr.stop();
  2309. }
  2310. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2311. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2312. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2313. int port = svr.bind_to_any_port("0.0.0.0");
  2314. ASSERT_TRUE(svr.is_valid());
  2315. ASSERT_TRUE(port > 0);
  2316. svr.stop();
  2317. }
  2318. TEST(BindServerTest, UpdateCertsPem) {
  2319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2320. int port = svr.bind_to_any_port("0.0.0.0");
  2321. ASSERT_TRUE(svr.is_valid());
  2322. ASSERT_TRUE(port > 0);
  2323. // Read PEM files
  2324. std::string cert_pem, key_pem, ca_pem;
  2325. read_file(SERVER_CERT_FILE, cert_pem);
  2326. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2327. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2328. // Update server certificates using PEM API
  2329. ASSERT_TRUE(
  2330. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2331. ASSERT_TRUE(svr.is_valid());
  2332. svr.stop();
  2333. }
  2334. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2335. // Start server with client CA (enables client auth)
  2336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2337. ASSERT_TRUE(svr.is_valid());
  2338. bool handler_called = false;
  2339. svr.Get("/test", [&](const Request &req, Response &res) {
  2340. handler_called = true;
  2341. // Verify client certificate is present
  2342. auto cert = req.peer_cert();
  2343. EXPECT_TRUE(static_cast<bool>(cert));
  2344. res.set_content("ok", "text/plain");
  2345. });
  2346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. t.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. // Read PEM files
  2354. std::string cert_pem, key_pem, ca_pem;
  2355. read_file(SERVER_CERT_FILE, cert_pem);
  2356. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2357. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2358. // Update server certificates and client CA using PEM API while server running
  2359. ASSERT_TRUE(
  2360. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2361. // Connect with client certificate
  2362. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2363. cli.enable_server_certificate_verification(false);
  2364. cli.set_connection_timeout(30);
  2365. auto res = cli.Get("/test");
  2366. ASSERT_TRUE(res);
  2367. ASSERT_EQ(StatusCode::OK_200, res->status);
  2368. ASSERT_TRUE(handler_called);
  2369. EXPECT_EQ("ok", res->body);
  2370. }
  2371. #endif
  2372. TEST(ErrorHandlerTest, ContentLength) {
  2373. Server svr;
  2374. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2375. res.status = StatusCode::OK_200;
  2376. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2377. "text/html"); // <= Content-Length still 13
  2378. });
  2379. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2380. res.set_content("Hello World!\n", "text/plain");
  2381. res.status = 524;
  2382. });
  2383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2384. auto se = detail::scope_exit([&] {
  2385. svr.stop();
  2386. thread.join();
  2387. ASSERT_FALSE(svr.is_running());
  2388. });
  2389. svr.wait_until_ready();
  2390. {
  2391. Client cli(HOST, PORT);
  2392. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2393. ASSERT_TRUE(res);
  2394. EXPECT_EQ(StatusCode::OK_200, res->status);
  2395. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2396. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2397. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2398. }
  2399. }
  2400. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2401. TEST(ExceptionTest, WithoutExceptionHandler) {
  2402. Server svr;
  2403. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2404. throw std::runtime_error("exception...");
  2405. });
  2406. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2407. throw std::runtime_error("exception\r\n...");
  2408. });
  2409. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2410. auto se = detail::scope_exit([&] {
  2411. svr.stop();
  2412. listen_thread.join();
  2413. ASSERT_FALSE(svr.is_running());
  2414. });
  2415. svr.wait_until_ready();
  2416. Client cli("localhost", PORT);
  2417. {
  2418. auto res = cli.Get("/exception");
  2419. ASSERT_TRUE(res);
  2420. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2421. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2422. }
  2423. {
  2424. auto res = cli.Get("/unknown");
  2425. ASSERT_TRUE(res);
  2426. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2427. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2428. }
  2429. }
  2430. TEST(ExceptionTest, WithExceptionHandler) {
  2431. Server svr;
  2432. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2433. std::exception_ptr ep) {
  2434. EXPECT_FALSE(ep == nullptr);
  2435. try {
  2436. std::rethrow_exception(ep);
  2437. } catch (std::exception &e) {
  2438. EXPECT_EQ("abc", std::string(e.what()));
  2439. } catch (...) {}
  2440. res.status = StatusCode::InternalServerError_500;
  2441. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2442. "text/html"); // <= Content-Length still 13 at this point
  2443. });
  2444. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2445. res.set_content("Hello World!\n", "text/plain");
  2446. throw std::runtime_error("abc");
  2447. });
  2448. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2449. auto se = detail::scope_exit([&] {
  2450. svr.stop();
  2451. thread.join();
  2452. ASSERT_FALSE(svr.is_running());
  2453. });
  2454. svr.wait_until_ready();
  2455. for (size_t i = 0; i < 10; i++) {
  2456. Client cli(HOST, PORT);
  2457. for (size_t j = 0; j < 100; j++) {
  2458. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2459. ASSERT_TRUE(res);
  2460. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2461. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2462. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2463. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2464. }
  2465. cli.set_keep_alive(true);
  2466. for (size_t j = 0; j < 100; j++) {
  2467. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2468. ASSERT_TRUE(res);
  2469. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2470. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2471. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2472. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2473. }
  2474. }
  2475. }
  2476. TEST(ExceptionTest, AndErrorHandler) {
  2477. Server svr;
  2478. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2479. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2480. });
  2481. svr.set_exception_handler(
  2482. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2483. EXPECT_FALSE(ep == nullptr);
  2484. try {
  2485. std::rethrow_exception(ep);
  2486. } catch (std::exception &e) {
  2487. res.set_content(e.what(), "text/html");
  2488. } catch (...) {}
  2489. res.status = StatusCode::InternalServerError_500;
  2490. });
  2491. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2492. throw std::runtime_error("EXCEPTION");
  2493. });
  2494. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2495. res.set_content("ERROR", "text/html");
  2496. res.status = StatusCode::InternalServerError_500;
  2497. });
  2498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. thread.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. Client cli(HOST, PORT);
  2506. {
  2507. auto res = cli.Get("/exception");
  2508. ASSERT_TRUE(res);
  2509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2510. EXPECT_EQ("EXCEPTION", res->body);
  2511. }
  2512. {
  2513. auto res = cli.Get("/error");
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2516. EXPECT_EQ("ERROR", res->body);
  2517. }
  2518. {
  2519. auto res = cli.Get("/invalid");
  2520. ASSERT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2522. EXPECT_EQ("NOT_FOUND", res->body);
  2523. }
  2524. }
  2525. #endif
  2526. TEST(NoContentTest, ContentLength) {
  2527. Server svr;
  2528. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2529. res.status = StatusCode::NoContent_204;
  2530. });
  2531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2532. auto se = detail::scope_exit([&] {
  2533. svr.stop();
  2534. thread.join();
  2535. ASSERT_FALSE(svr.is_running());
  2536. });
  2537. svr.wait_until_ready();
  2538. {
  2539. Client cli(HOST, PORT);
  2540. auto res = cli.Get("/hi");
  2541. ASSERT_TRUE(res);
  2542. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2543. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2544. }
  2545. }
  2546. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2547. #ifdef CPPHTTPLIB_SSL_ENABLED
  2548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2549. ASSERT_TRUE(svr.is_valid());
  2550. #else
  2551. Server svr;
  2552. #endif
  2553. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2554. if (req.path == "/routing_handler") {
  2555. res.set_header("PRE_ROUTING", "on");
  2556. res.set_content("Routing Handler", "text/plain");
  2557. return httplib::Server::HandlerResponse::Handled;
  2558. }
  2559. return httplib::Server::HandlerResponse::Unhandled;
  2560. });
  2561. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2562. res.set_content("Error", "text/html");
  2563. });
  2564. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2565. if (req.path == "/routing_handler") {
  2566. res.set_header("POST_ROUTING", "on");
  2567. }
  2568. });
  2569. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2570. res.set_content("Hello World!\n", "text/plain");
  2571. });
  2572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2573. auto se = detail::scope_exit([&] {
  2574. svr.stop();
  2575. thread.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. });
  2578. svr.wait_until_ready();
  2579. {
  2580. #ifdef CPPHTTPLIB_SSL_ENABLED
  2581. SSLClient cli(HOST, PORT);
  2582. cli.enable_server_certificate_verification(false);
  2583. #else
  2584. Client cli(HOST, PORT);
  2585. #endif
  2586. auto res = cli.Get("/routing_handler");
  2587. ASSERT_TRUE(res);
  2588. EXPECT_EQ(StatusCode::OK_200, res->status);
  2589. EXPECT_EQ("Routing Handler", res->body);
  2590. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2591. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2592. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2593. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2594. }
  2595. {
  2596. #ifdef CPPHTTPLIB_SSL_ENABLED
  2597. SSLClient cli(HOST, PORT);
  2598. cli.enable_server_certificate_verification(false);
  2599. #else
  2600. Client cli(HOST, PORT);
  2601. #endif
  2602. auto res = cli.Get("/hi");
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(StatusCode::OK_200, res->status);
  2605. EXPECT_EQ("Hello World!\n", res->body);
  2606. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2607. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2608. }
  2609. {
  2610. #ifdef CPPHTTPLIB_SSL_ENABLED
  2611. SSLClient cli(HOST, PORT);
  2612. cli.enable_server_certificate_verification(false);
  2613. #else
  2614. Client cli(HOST, PORT);
  2615. #endif
  2616. auto res = cli.Get("/aaa");
  2617. ASSERT_TRUE(res);
  2618. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2619. EXPECT_EQ("Error", res->body);
  2620. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2621. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2622. }
  2623. }
  2624. TEST(RequestHandlerTest, PreRequestHandler) {
  2625. auto route_path = "/user/:user";
  2626. Server svr;
  2627. svr.Get("/hi", [](const Request &, Response &res) {
  2628. res.set_content("hi", "text/plain");
  2629. });
  2630. svr.Get(route_path, [](const Request &req, Response &res) {
  2631. res.set_content(req.path_params.at("user"), "text/plain");
  2632. });
  2633. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2634. if (req.matched_route == route_path) {
  2635. auto user = req.path_params.at("user");
  2636. if (user != "john") {
  2637. res.status = StatusCode::Forbidden_403;
  2638. res.set_content("error", "text/html");
  2639. return Server::HandlerResponse::Handled;
  2640. }
  2641. }
  2642. return Server::HandlerResponse::Unhandled;
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. {
  2653. auto res = cli.Get("/hi");
  2654. ASSERT_TRUE(res);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. EXPECT_EQ("hi", res->body);
  2657. }
  2658. {
  2659. auto res = cli.Get("/user/john");
  2660. ASSERT_TRUE(res);
  2661. EXPECT_EQ(StatusCode::OK_200, res->status);
  2662. EXPECT_EQ("john", res->body);
  2663. }
  2664. {
  2665. auto res = cli.Get("/user/invalid-user");
  2666. ASSERT_TRUE(res);
  2667. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2668. EXPECT_EQ("error", res->body);
  2669. }
  2670. }
  2671. TEST(UserDataTest, BasicOperations) {
  2672. httplib::UserData ud;
  2673. // Initially empty
  2674. EXPECT_FALSE(ud.has("key"));
  2675. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2676. // set and get
  2677. ud.set("key", 42);
  2678. EXPECT_TRUE(ud.has("key"));
  2679. auto *p = ud.get<int>("key");
  2680. ASSERT_NE(nullptr, p);
  2681. EXPECT_EQ(42, *p);
  2682. // Type mismatch → nullptr
  2683. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2684. // Overwrite with different type
  2685. ud.set("key", std::string("hello"));
  2686. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2687. auto *s = ud.get<std::string>("key");
  2688. ASSERT_NE(nullptr, s);
  2689. EXPECT_EQ("hello", *s);
  2690. // erase
  2691. ud.erase("key");
  2692. EXPECT_FALSE(ud.has("key"));
  2693. // clear
  2694. ud.set("a", 1);
  2695. ud.set("b", 2);
  2696. ud.clear();
  2697. EXPECT_FALSE(ud.has("a"));
  2698. EXPECT_FALSE(ud.has("b"));
  2699. }
  2700. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2701. struct AuthCtx {
  2702. std::string user_id;
  2703. };
  2704. Server svr;
  2705. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2706. res.user_data.set("auth", AuthCtx{"alice"});
  2707. return Server::HandlerResponse::Unhandled;
  2708. });
  2709. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2710. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2711. ASSERT_NE(nullptr, ctx);
  2712. res.set_content("Hello " + ctx->user_id, "text/plain");
  2713. });
  2714. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2715. auto se = detail::scope_exit([&] {
  2716. svr.stop();
  2717. thread.join();
  2718. ASSERT_FALSE(svr.is_running());
  2719. });
  2720. svr.wait_until_ready();
  2721. Client cli(HOST, PORT);
  2722. auto res = cli.Get("/me");
  2723. ASSERT_TRUE(res);
  2724. EXPECT_EQ(StatusCode::OK_200, res->status);
  2725. EXPECT_EQ("Hello alice", res->body);
  2726. }
  2727. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2728. struct RoleCtx {
  2729. std::string role;
  2730. };
  2731. Server svr;
  2732. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2733. res.user_data.set("role", RoleCtx{"admin"});
  2734. return Server::HandlerResponse::Unhandled;
  2735. });
  2736. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2737. auto *ctx = res.user_data.get<RoleCtx>("role");
  2738. ASSERT_NE(nullptr, ctx);
  2739. res.set_content(ctx->role, "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. auto res = cli.Get("/role");
  2750. ASSERT_TRUE(res);
  2751. EXPECT_EQ(StatusCode::OK_200, res->status);
  2752. EXPECT_EQ("admin", res->body);
  2753. }
  2754. TEST(InvalidFormatTest, StatusCode) {
  2755. Server svr;
  2756. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2757. res.set_content("Hello World!\n", "text/plain");
  2758. res.status = 9999; // Status should be a three-digit code...
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. {
  2768. Client cli(HOST, PORT);
  2769. auto res = cli.Get("/hi");
  2770. ASSERT_FALSE(res);
  2771. }
  2772. }
  2773. TEST(URLFragmentTest, WithFragment) {
  2774. Server svr;
  2775. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2776. EXPECT_TRUE(req.target == "/hi");
  2777. });
  2778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2779. auto se = detail::scope_exit([&] {
  2780. svr.stop();
  2781. thread.join();
  2782. ASSERT_FALSE(svr.is_running());
  2783. });
  2784. svr.wait_until_ready();
  2785. {
  2786. Client cli(HOST, PORT);
  2787. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2788. EXPECT_TRUE(res);
  2789. EXPECT_EQ(StatusCode::OK_200, res->status);
  2790. res = cli.Get("/hi%23key1=val1=key2=val2");
  2791. EXPECT_TRUE(res);
  2792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2793. }
  2794. }
  2795. TEST(HeaderWriter, SetHeaderWriter) {
  2796. Server svr;
  2797. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2798. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2799. return detail::write_headers(strm, hdrs);
  2800. });
  2801. svr.Get("/hi", [](const Request &req, Response &res) {
  2802. auto it = req.headers.find("CustomClientHeader");
  2803. EXPECT_TRUE(it != req.headers.end());
  2804. EXPECT_EQ(it->second, "CustomClientValue");
  2805. res.set_content("Hello World!\n", "text/plain");
  2806. });
  2807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2808. auto se = detail::scope_exit([&] {
  2809. svr.stop();
  2810. thread.join();
  2811. ASSERT_FALSE(svr.is_running());
  2812. });
  2813. svr.wait_until_ready();
  2814. {
  2815. Client cli(HOST, PORT);
  2816. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2817. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2818. return detail::write_headers(strm, hdrs);
  2819. });
  2820. auto res = cli.Get("/hi");
  2821. EXPECT_TRUE(res);
  2822. EXPECT_EQ(StatusCode::OK_200, res->status);
  2823. auto it = res->headers.find("CustomServerHeader");
  2824. EXPECT_TRUE(it != res->headers.end());
  2825. EXPECT_EQ(it->second, "CustomServerValue");
  2826. }
  2827. }
  2828. class ServerTest : public ::testing::Test {
  2829. protected:
  2830. ServerTest()
  2831. : cli_(HOST, PORT)
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. ,
  2834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2835. #endif
  2836. {
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. cli_.enable_server_certificate_verification(false);
  2839. #endif
  2840. // Allow LARGE_DATA (100MB) responses
  2841. cli_.set_payload_max_length(200 * 1024 * 1024);
  2842. }
  2843. virtual void SetUp() {
  2844. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2845. svr_.set_payload_max_length(200 * 1024 * 1024);
  2846. svr_.set_mount_point("/", "./www");
  2847. svr_.set_mount_point("/mount", "./www2");
  2848. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2849. svr_.Get("/hi",
  2850. [&](const Request & /*req*/, Response &res) {
  2851. res.set_content("Hello World!", "text/plain");
  2852. })
  2853. .Get("/file_content",
  2854. [&](const Request & /*req*/, Response &res) {
  2855. res.set_file_content("./www/dir/test.html");
  2856. })
  2857. .Get("/file_content_with_content_type",
  2858. [&](const Request & /*req*/, Response &res) {
  2859. res.set_file_content("./www/file", "text/plain");
  2860. })
  2861. .Get("/invalid_file_content",
  2862. [&](const Request & /*req*/, Response &res) {
  2863. res.set_file_content("./www/dir/invalid_file_path");
  2864. })
  2865. .Get("/http_response_splitting",
  2866. [&](const Request & /*req*/, Response &res) {
  2867. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2868. EXPECT_EQ(0U, res.headers.size());
  2869. EXPECT_FALSE(res.has_header("a"));
  2870. res.set_header("a", "1\nSet-Cookie: a=1");
  2871. EXPECT_EQ(0U, res.headers.size());
  2872. EXPECT_FALSE(res.has_header("a"));
  2873. res.set_header("a", "1\rSet-Cookie: a=1");
  2874. EXPECT_EQ(0U, res.headers.size());
  2875. EXPECT_FALSE(res.has_header("a"));
  2876. res.set_header("a\r\nb", "0");
  2877. EXPECT_EQ(0U, res.headers.size());
  2878. EXPECT_FALSE(res.has_header("a"));
  2879. res.set_header("a\rb", "0");
  2880. EXPECT_EQ(0U, res.headers.size());
  2881. EXPECT_FALSE(res.has_header("a"));
  2882. res.set_header("a\nb", "0");
  2883. EXPECT_EQ(0U, res.headers.size());
  2884. EXPECT_FALSE(res.has_header("a"));
  2885. res.set_redirect("1\r\nSet-Cookie: a=1");
  2886. EXPECT_EQ(0U, res.headers.size());
  2887. EXPECT_FALSE(res.has_header("Location"));
  2888. })
  2889. .Get("/slow",
  2890. [&](const Request & /*req*/, Response &res) {
  2891. std::this_thread::sleep_for(std::chrono::seconds(4));
  2892. res.set_content("slow", "text/plain");
  2893. })
  2894. #if 0
  2895. .Post("/slowpost",
  2896. [&](const Request & /*req*/, Response &res) {
  2897. std::this_thread::sleep_for(std::chrono::seconds(2));
  2898. res.set_content("slow", "text/plain");
  2899. })
  2900. #endif
  2901. .Get("/remote_addr",
  2902. [&](const Request &req, Response &res) {
  2903. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2904. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2905. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2906. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2907. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2908. #endif
  2909. res.set_content(req.remote_addr, "text/plain");
  2910. })
  2911. .Get("/local_addr",
  2912. [&](const Request &req, Response &res) {
  2913. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2914. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2915. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2916. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2917. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2918. #endif
  2919. auto local_addr = req.local_addr;
  2920. auto local_port = std::to_string(req.local_port);
  2921. res.set_content(local_addr.append(":").append(local_port),
  2922. "text/plain");
  2923. })
  2924. .Get("/endwith%",
  2925. [&](const Request & /*req*/, Response &res) {
  2926. res.set_content("Hello World!", "text/plain");
  2927. })
  2928. .Get("/a\\+\\+b",
  2929. [&](const Request &req, Response &res) {
  2930. ASSERT_TRUE(req.has_param("a +b"));
  2931. auto val = req.get_param_value("a +b");
  2932. res.set_content(val, "text/plain");
  2933. })
  2934. .Get("/", [&](const Request & /*req*/,
  2935. Response &res) { res.set_redirect("/hi"); })
  2936. .Post("/1",
  2937. [](const Request & /*req*/, Response &res) {
  2938. res.set_redirect("/2", StatusCode::SeeOther_303);
  2939. })
  2940. .Get("/2",
  2941. [](const Request & /*req*/, Response &res) {
  2942. res.set_content("redirected.", "text/plain");
  2943. res.status = StatusCode::OK_200;
  2944. })
  2945. .Post("/person",
  2946. [&](const Request &req, Response &res) {
  2947. if (req.has_param("name") && req.has_param("note")) {
  2948. persons_[req.get_param_value("name")] =
  2949. req.get_param_value("note");
  2950. } else {
  2951. res.status = StatusCode::BadRequest_400;
  2952. }
  2953. })
  2954. .Put("/person",
  2955. [&](const Request &req, Response &res) {
  2956. if (req.has_param("name") && req.has_param("note")) {
  2957. persons_[req.get_param_value("name")] =
  2958. req.get_param_value("note");
  2959. } else {
  2960. res.status = StatusCode::BadRequest_400;
  2961. }
  2962. })
  2963. .Get("/person/(.*)",
  2964. [&](const Request &req, Response &res) {
  2965. string name = req.matches[1];
  2966. if (persons_.find(name) != persons_.end()) {
  2967. auto note = persons_[name];
  2968. res.set_content(note, "text/plain");
  2969. } else {
  2970. res.status = StatusCode::NotFound_404;
  2971. }
  2972. })
  2973. .Delete("/person",
  2974. [&](const Request &req, Response &res) {
  2975. if (req.has_param("name")) {
  2976. string name = req.get_param_value("name");
  2977. if (persons_.find(name) != persons_.end()) {
  2978. persons_.erase(name);
  2979. res.set_content("DELETED", "text/plain");
  2980. } else {
  2981. res.status = StatusCode::NotFound_404;
  2982. }
  2983. } else {
  2984. res.status = StatusCode::BadRequest_400;
  2985. }
  2986. })
  2987. .Post("/x-www-form-urlencoded-json",
  2988. [&](const Request &req, Response &res) {
  2989. auto json = req.get_param_value("json");
  2990. ASSERT_EQ(JSON_DATA, json);
  2991. res.set_content(json, "appliation/json");
  2992. res.status = StatusCode::OK_200;
  2993. })
  2994. .Get("/streamed-chunked",
  2995. [&](const Request & /*req*/, Response &res) {
  2996. res.set_chunked_content_provider(
  2997. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2998. sink.os << "123";
  2999. sink.os << "456";
  3000. sink.os << "789";
  3001. sink.done();
  3002. return true;
  3003. });
  3004. })
  3005. .Get("/streamed-chunked-with-prohibited-trailer",
  3006. [&](const Request & /*req*/, Response &res) {
  3007. auto i = new int(0);
  3008. // Declare both a prohibited trailer (Content-Length) and an
  3009. // allowed one
  3010. res.set_header("Trailer", "Content-Length, X-Allowed");
  3011. res.set_chunked_content_provider(
  3012. "text/plain",
  3013. [i](size_t /*offset*/, DataSink &sink) {
  3014. switch (*i) {
  3015. case 0: sink.os << "123"; break;
  3016. case 1: sink.os << "456"; break;
  3017. case 2: sink.os << "789"; break;
  3018. case 3: {
  3019. sink.done_with_trailer(
  3020. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3021. } break;
  3022. }
  3023. (*i)++;
  3024. return true;
  3025. },
  3026. [i](bool success) {
  3027. EXPECT_TRUE(success);
  3028. delete i;
  3029. });
  3030. })
  3031. .Get("/streamed-chunked2",
  3032. [&](const Request & /*req*/, Response &res) {
  3033. auto i = new int(0);
  3034. res.set_chunked_content_provider(
  3035. "text/plain",
  3036. [i](size_t /*offset*/, DataSink &sink) {
  3037. switch (*i) {
  3038. case 0: sink.os << "123"; break;
  3039. case 1: sink.os << "456"; break;
  3040. case 2: sink.os << "789"; break;
  3041. case 3: sink.done(); break;
  3042. }
  3043. (*i)++;
  3044. return true;
  3045. },
  3046. [i](bool success) {
  3047. EXPECT_TRUE(success);
  3048. delete i;
  3049. });
  3050. })
  3051. .Get("/streamed-chunked-with-trailer",
  3052. [&](const Request & /*req*/, Response &res) {
  3053. auto i = new int(0);
  3054. res.set_header("Trailer", "Dummy1, Dummy2");
  3055. res.set_chunked_content_provider(
  3056. "text/plain",
  3057. [i](size_t /*offset*/, DataSink &sink) {
  3058. switch (*i) {
  3059. case 0: sink.os << "123"; break;
  3060. case 1: sink.os << "456"; break;
  3061. case 2: sink.os << "789"; break;
  3062. case 3: {
  3063. sink.done_with_trailer(
  3064. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3065. } break;
  3066. }
  3067. (*i)++;
  3068. return true;
  3069. },
  3070. [i](bool success) {
  3071. EXPECT_TRUE(success);
  3072. delete i;
  3073. });
  3074. })
  3075. .Get("/streamed",
  3076. [&](const Request & /*req*/, Response &res) {
  3077. res.set_content_provider(
  3078. 6, "text/plain",
  3079. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3080. sink.os << (offset < 3 ? "a" : "b");
  3081. return true;
  3082. });
  3083. })
  3084. .Get("/streamed-with-range",
  3085. [&](const Request &req, Response &res) {
  3086. auto data = new std::string("abcdefg");
  3087. res.set_content_provider(
  3088. data->size(), "text/plain",
  3089. [data](size_t offset, size_t length, DataSink &sink) {
  3090. size_t DATA_CHUNK_SIZE = 4;
  3091. const auto &d = *data;
  3092. auto out_len =
  3093. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3094. auto ret =
  3095. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3096. EXPECT_TRUE(ret);
  3097. return true;
  3098. },
  3099. [data, &req](bool success) {
  3100. EXPECT_EQ(success, !req.has_param("error"));
  3101. delete data;
  3102. });
  3103. })
  3104. .Get("/streamed-cancel",
  3105. [&](const Request & /*req*/, Response &res) {
  3106. res.set_content_provider(
  3107. size_t(-1), "text/plain",
  3108. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3109. sink.os << "data_chunk";
  3110. return true;
  3111. });
  3112. })
  3113. .Get("/regex-with-delimiter",
  3114. [&](const Request &req, Response & /*res*/) {
  3115. ASSERT_TRUE(req.has_param("key"));
  3116. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3117. })
  3118. .Get("/with-range",
  3119. [&](const Request & /*req*/, Response &res) {
  3120. res.set_content("abcdefg", "text/plain");
  3121. })
  3122. .Get("/test-start-time",
  3123. [&](const Request &req, Response & /*res*/) {
  3124. EXPECT_NE(req.start_time_,
  3125. std::chrono::steady_clock::time_point::min());
  3126. })
  3127. .Get("/with-range-customized-response",
  3128. [&](const Request & /*req*/, Response &res) {
  3129. res.status = StatusCode::BadRequest_400;
  3130. res.set_content(JSON_DATA, "application/json");
  3131. })
  3132. .Post("/chunked",
  3133. [&](const Request &req, Response & /*res*/) {
  3134. EXPECT_EQ(req.body, "dechunked post body");
  3135. })
  3136. .Post("/large-chunked",
  3137. [&](const Request &req, Response & /*res*/) {
  3138. std::string expected(6 * 30 * 1024u, 'a');
  3139. EXPECT_EQ(req.body, expected);
  3140. })
  3141. .Post("/multipart",
  3142. [&](const Request &req, Response & /*res*/) {
  3143. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3144. req.form.get_field_count("text2") +
  3145. req.form.get_field_count("file3") +
  3146. req.form.get_field_count("file4"));
  3147. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3148. req.form.get_file_count("file2"));
  3149. ASSERT_TRUE(!req.form.has_file("???"));
  3150. ASSERT_TRUE(!req.form.has_field("???"));
  3151. ASSERT_TRUE(req.body.empty());
  3152. {
  3153. const auto &text = req.form.get_field("text1");
  3154. EXPECT_EQ("text default", text);
  3155. }
  3156. {
  3157. const auto &text = req.form.get_field("text2");
  3158. EXPECT_EQ("aωb", text);
  3159. }
  3160. {
  3161. const auto &file = req.form.get_file("file1");
  3162. EXPECT_EQ("hello.txt", file.filename);
  3163. EXPECT_EQ("text/plain", file.content_type);
  3164. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3165. }
  3166. {
  3167. const auto &file = req.form.get_file("file2");
  3168. EXPECT_EQ("world.json", file.filename);
  3169. EXPECT_EQ("application/json", file.content_type);
  3170. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3171. }
  3172. {
  3173. const auto &text = req.form.get_field("file3");
  3174. EXPECT_EQ(0u, text.size());
  3175. }
  3176. {
  3177. const auto &text = req.form.get_field("file4");
  3178. EXPECT_EQ(0u, text.size());
  3179. }
  3180. })
  3181. .Post("/multipart/multi_file_values",
  3182. [&](const Request &req, Response & /*res*/) {
  3183. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3184. req.form.get_field_count("multi_text1"));
  3185. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3186. ASSERT_TRUE(!req.form.has_file("???"));
  3187. ASSERT_TRUE(!req.form.has_field("???"));
  3188. ASSERT_TRUE(req.body.empty());
  3189. {
  3190. const auto &text = req.form.get_field("text");
  3191. EXPECT_EQ("default text", text);
  3192. }
  3193. {
  3194. const auto &text1_values = req.form.get_fields("multi_text1");
  3195. EXPECT_EQ(2u, text1_values.size());
  3196. EXPECT_EQ("aaaaa", text1_values[0]);
  3197. EXPECT_EQ("bbbbb", text1_values[1]);
  3198. }
  3199. {
  3200. const auto &file1_values = req.form.get_files("multi_file1");
  3201. EXPECT_EQ(2u, file1_values.size());
  3202. auto file1 = file1_values[0];
  3203. EXPECT_EQ(file1.filename, "hello.txt");
  3204. EXPECT_EQ(file1.content_type, "text/plain");
  3205. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3206. auto file2 = file1_values[1];
  3207. EXPECT_EQ(file2.filename, "world.json");
  3208. EXPECT_EQ(file2.content_type, "application/json");
  3209. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3210. }
  3211. })
  3212. .Post("/empty",
  3213. [&](const Request &req, Response &res) {
  3214. EXPECT_EQ(req.body, "");
  3215. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3216. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3217. res.set_content("empty", "text/plain");
  3218. })
  3219. .Post("/empty-no-content-type",
  3220. [&](const Request &req, Response &res) {
  3221. EXPECT_EQ(req.body, "");
  3222. EXPECT_FALSE(req.has_header("Content-Type"));
  3223. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3224. res.set_content("empty-no-content-type", "text/plain");
  3225. })
  3226. .Post("/path-only",
  3227. [&](const Request &req, Response &res) {
  3228. EXPECT_EQ(req.body, "");
  3229. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3230. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3231. res.set_content("path-only", "text/plain");
  3232. })
  3233. .Post("/path-headers-only",
  3234. [&](const Request &req, Response &res) {
  3235. EXPECT_EQ(req.body, "");
  3236. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3237. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3238. EXPECT_EQ("world", req.get_header_value("hello"));
  3239. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3240. res.set_content("path-headers-only", "text/plain");
  3241. })
  3242. .Post("/post-large",
  3243. [&](const Request &req, Response &res) {
  3244. EXPECT_EQ(req.body, LARGE_DATA);
  3245. res.set_content(req.body, "text/plain");
  3246. })
  3247. .Post("/post-loopback",
  3248. [&](const Request &, Response &res,
  3249. ContentReader const &content_reader) {
  3250. std::string body;
  3251. content_reader([&](const char *data, size_t data_length) {
  3252. body.append(data, data_length);
  3253. return true;
  3254. });
  3255. res.set_content(body, "text/plain");
  3256. })
  3257. .Put("/put-loopback",
  3258. [&](const Request &, Response &res,
  3259. ContentReader const &content_reader) {
  3260. std::string body;
  3261. content_reader([&](const char *data, size_t data_length) {
  3262. body.append(data, data_length);
  3263. return true;
  3264. });
  3265. res.set_content(body, "text/plain");
  3266. })
  3267. .Patch("/patch-loopback",
  3268. [&](const Request &, Response &res,
  3269. ContentReader const &content_reader) {
  3270. std::string body;
  3271. content_reader([&](const char *data, size_t data_length) {
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. res.set_content(body, "text/plain");
  3276. })
  3277. .Put("/empty-no-content-type",
  3278. [&](const Request &req, Response &res) {
  3279. EXPECT_EQ(req.body, "");
  3280. EXPECT_FALSE(req.has_header("Content-Type"));
  3281. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3282. res.set_content("empty-no-content-type", "text/plain");
  3283. })
  3284. .Put("/put",
  3285. [&](const Request &req, Response &res) {
  3286. EXPECT_EQ(req.body, "PUT");
  3287. res.set_content(req.body, "text/plain");
  3288. })
  3289. .Put("/put-large",
  3290. [&](const Request &req, Response &res) {
  3291. EXPECT_EQ(req.body, LARGE_DATA);
  3292. res.set_content(req.body, "text/plain");
  3293. })
  3294. .Patch("/patch",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(req.body, "PATCH");
  3297. res.set_content(req.body, "text/plain");
  3298. })
  3299. .Delete("/delete",
  3300. [&](const Request & /*req*/, Response &res) {
  3301. res.set_content("DELETE", "text/plain");
  3302. })
  3303. .Delete("/delete-body",
  3304. [&](const Request &req, Response &res) {
  3305. EXPECT_EQ(req.body, "content");
  3306. res.set_content(req.body, "text/plain");
  3307. })
  3308. .Options(R"(\*)",
  3309. [&](const Request & /*req*/, Response &res) {
  3310. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3311. })
  3312. .Get("/request-target",
  3313. [&](const Request &req, Response & /*res*/) {
  3314. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3315. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3316. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3317. })
  3318. .Get("/long-query-value",
  3319. [&](const Request &req, Response & /*res*/) {
  3320. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3321. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3322. })
  3323. .Get("/too-long-query-value",
  3324. [&](const Request &req, Response & /*res*/) {
  3325. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3326. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3327. })
  3328. .Get("/array-param",
  3329. [&](const Request &req, Response & /*res*/) {
  3330. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3331. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3332. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3333. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3334. })
  3335. .Get("/array-param-values",
  3336. [&](const Request &req, Response & /*res*/) {
  3337. auto values = req.get_param_values("array");
  3338. EXPECT_EQ(3u, values.size());
  3339. EXPECT_EQ("value1", values[0]);
  3340. EXPECT_EQ("value2", values[1]);
  3341. EXPECT_EQ("value3", values[2]);
  3342. auto empty = req.get_param_values("nonexistent");
  3343. EXPECT_TRUE(empty.empty());
  3344. })
  3345. .Post("/validate-no-multiple-headers",
  3346. [&](const Request &req, Response & /*res*/) {
  3347. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3348. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3349. })
  3350. .Post("/content_receiver",
  3351. [&](const Request &req, Response &res,
  3352. const ContentReader &content_reader) {
  3353. if (req.is_multipart_form_data()) {
  3354. std::vector<FormData> items;
  3355. content_reader(
  3356. [&](const FormData &file) {
  3357. items.push_back(file);
  3358. return true;
  3359. },
  3360. [&](const char *data, size_t data_length) {
  3361. items.back().content.append(data, data_length);
  3362. return true;
  3363. });
  3364. EXPECT_EQ(5u, items.size());
  3365. {
  3366. const auto &file = get_file_value(items, "text1");
  3367. EXPECT_TRUE(file.filename.empty());
  3368. EXPECT_EQ("text default", file.content);
  3369. }
  3370. {
  3371. const auto &file = get_file_value(items, "text2");
  3372. EXPECT_TRUE(file.filename.empty());
  3373. EXPECT_EQ("aωb", file.content);
  3374. }
  3375. {
  3376. const auto &file = get_file_value(items, "file1");
  3377. EXPECT_EQ("hello.txt", file.filename);
  3378. EXPECT_EQ("text/plain", file.content_type);
  3379. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3380. }
  3381. {
  3382. const auto &file = get_file_value(items, "file2");
  3383. EXPECT_EQ("world.json", file.filename);
  3384. EXPECT_EQ("application/json", file.content_type);
  3385. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3386. }
  3387. {
  3388. const auto &file = get_file_value(items, "file3");
  3389. EXPECT_TRUE(file.filename.empty());
  3390. EXPECT_EQ("application/octet-stream", file.content_type);
  3391. EXPECT_EQ(0u, file.content.size());
  3392. }
  3393. } else {
  3394. std::string body;
  3395. content_reader([&](const char *data, size_t data_length) {
  3396. EXPECT_EQ(7U, data_length);
  3397. body.append(data, data_length);
  3398. return true;
  3399. });
  3400. EXPECT_EQ(body, "content");
  3401. res.set_content(body, "text/plain");
  3402. }
  3403. })
  3404. .Put("/content_receiver",
  3405. [&](const Request & /*req*/, Response &res,
  3406. const ContentReader &content_reader) {
  3407. std::string body;
  3408. content_reader([&](const char *data, size_t data_length) {
  3409. body.append(data, data_length);
  3410. return true;
  3411. });
  3412. EXPECT_EQ(body, "content");
  3413. res.set_content(body, "text/plain");
  3414. })
  3415. .Patch("/content_receiver",
  3416. [&](const Request & /*req*/, Response &res,
  3417. const ContentReader &content_reader) {
  3418. std::string body;
  3419. content_reader([&](const char *data, size_t data_length) {
  3420. body.append(data, data_length);
  3421. return true;
  3422. });
  3423. EXPECT_EQ(body, "content");
  3424. res.set_content(body, "text/plain");
  3425. })
  3426. .Post("/query-string-and-body",
  3427. [&](const Request &req, Response & /*res*/) {
  3428. ASSERT_TRUE(req.has_param("key"));
  3429. EXPECT_EQ(req.get_param_value("key"), "value");
  3430. EXPECT_EQ(req.body, "content");
  3431. })
  3432. .Get("/last-request",
  3433. [&](const Request &req, Response & /*res*/) {
  3434. EXPECT_EQ("close", req.get_header_value("Connection"));
  3435. })
  3436. .Get(R"(/redirect/(\d+))",
  3437. [&](const Request &req, Response &res) {
  3438. auto num = std::stoi(req.matches[1]) + 1;
  3439. std::string url = "/redirect/" + std::to_string(num);
  3440. res.set_redirect(url);
  3441. })
  3442. .Post("/binary",
  3443. [&](const Request &req, Response &res) {
  3444. EXPECT_EQ(4U, req.body.size());
  3445. EXPECT_EQ("application/octet-stream",
  3446. req.get_header_value("Content-Type"));
  3447. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3448. res.set_content(req.body, "application/octet-stream");
  3449. })
  3450. .Put("/binary",
  3451. [&](const Request &req, Response &res) {
  3452. EXPECT_EQ(4U, req.body.size());
  3453. EXPECT_EQ("application/octet-stream",
  3454. req.get_header_value("Content-Type"));
  3455. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3456. res.set_content(req.body, "application/octet-stream");
  3457. })
  3458. .Patch("/binary",
  3459. [&](const Request &req, Response &res) {
  3460. EXPECT_EQ(4U, req.body.size());
  3461. EXPECT_EQ("application/octet-stream",
  3462. req.get_header_value("Content-Type"));
  3463. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3464. res.set_content(req.body, "application/octet-stream");
  3465. })
  3466. .Delete("/binary",
  3467. [&](const Request &req, Response &res) {
  3468. EXPECT_EQ(4U, req.body.size());
  3469. EXPECT_EQ("application/octet-stream",
  3470. req.get_header_value("Content-Type"));
  3471. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3472. res.set_content(req.body, "application/octet-stream");
  3473. })
  3474. .Get("/issue1772",
  3475. [&](const Request & /*req*/, Response &res) {
  3476. res.status = 401;
  3477. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3478. })
  3479. .Delete("/issue609",
  3480. [](const httplib::Request &, httplib::Response &res,
  3481. const httplib::ContentReader &) {
  3482. res.set_content("ok", "text/plain");
  3483. })
  3484. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3485. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3486. .Get("/compress",
  3487. [&](const Request & /*req*/, Response &res) {
  3488. res.set_content(
  3489. "12345678901234567890123456789012345678901234567890123456789"
  3490. "01234567890123456789012345678901234567890",
  3491. "text/plain");
  3492. })
  3493. .Get("/compress-with-charset",
  3494. [&](const Request & /*req*/, Response &res) {
  3495. res.set_content(
  3496. "12345678901234567890123456789012345678901234567890123456789"
  3497. "01234567890123456789012345678901234567890",
  3498. "application/json; charset=utf-8");
  3499. })
  3500. .Get("/nocompress",
  3501. [&](const Request & /*req*/, Response &res) {
  3502. res.set_content(
  3503. "12345678901234567890123456789012345678901234567890123456789"
  3504. "01234567890123456789012345678901234567890",
  3505. "application/octet-stream");
  3506. })
  3507. .Post("/compress-multipart",
  3508. [&](const Request &req, Response & /*res*/) {
  3509. EXPECT_EQ(2u, req.form.fields.size());
  3510. ASSERT_TRUE(!req.form.has_field("???"));
  3511. {
  3512. const auto &text = req.form.get_field("key1");
  3513. EXPECT_EQ("test", text);
  3514. }
  3515. {
  3516. const auto &text = req.form.get_field("key2");
  3517. EXPECT_EQ("--abcdefg123", text);
  3518. }
  3519. })
  3520. #endif
  3521. ;
  3522. persons_["john"] = "programmer";
  3523. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3524. svr_.wait_until_ready();
  3525. }
  3526. virtual void TearDown() {
  3527. svr_.stop();
  3528. if (!request_threads_.empty()) {
  3529. std::this_thread::sleep_for(std::chrono::seconds(1));
  3530. for (auto &t : request_threads_) {
  3531. t.join();
  3532. }
  3533. }
  3534. t_.join();
  3535. }
  3536. map<string, string> persons_;
  3537. #ifdef CPPHTTPLIB_SSL_ENABLED
  3538. SSLClient cli_;
  3539. SSLServer svr_;
  3540. #else
  3541. Client cli_;
  3542. Server svr_;
  3543. #endif
  3544. thread t_;
  3545. std::vector<thread> request_threads_;
  3546. };
  3547. TEST_F(ServerTest, GetMethod200) {
  3548. auto res = cli_.Get("/hi");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ("HTTP/1.1", res->version);
  3551. EXPECT_EQ(StatusCode::OK_200, res->status);
  3552. EXPECT_EQ("OK", res->reason);
  3553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3555. EXPECT_EQ("Hello World!", res->body);
  3556. }
  3557. TEST_F(ServerTest, GetEmptyFile) {
  3558. auto res = cli_.Get("/empty_file");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3562. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3563. EXPECT_EQ("", res->body);
  3564. }
  3565. TEST_F(ServerTest, GetFileContent) {
  3566. auto res = cli_.Get("/file_content");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3570. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3571. EXPECT_EQ("test.html", res->body);
  3572. }
  3573. TEST_F(ServerTest, GetFileContentWithRange) {
  3574. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3575. ASSERT_TRUE(res);
  3576. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3578. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3579. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3580. EXPECT_EQ("est", res->body);
  3581. }
  3582. TEST_F(ServerTest, GetFileContentWithContentType) {
  3583. auto res = cli_.Get("/file_content_with_content_type");
  3584. ASSERT_TRUE(res);
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3587. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3588. EXPECT_EQ("file\n", res->body);
  3589. }
  3590. TEST_F(ServerTest, GetInvalidFileContent) {
  3591. auto res = cli_.Get("/invalid_file_content");
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3594. }
  3595. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3596. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3597. ASSERT_TRUE(res);
  3598. EXPECT_EQ("HTTP/1.1", res->version);
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3601. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3602. EXPECT_EQ("Hello World!", res->body);
  3603. }
  3604. TEST_F(ServerTest, GetMethod302) {
  3605. auto res = cli_.Get("/");
  3606. ASSERT_TRUE(res);
  3607. EXPECT_EQ(StatusCode::Found_302, res->status);
  3608. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3609. }
  3610. TEST_F(ServerTest, GetMethod302Redirect) {
  3611. cli_.set_follow_location(true);
  3612. auto res = cli_.Get("/");
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. EXPECT_EQ("Hello World!", res->body);
  3616. EXPECT_EQ("/hi", res->location);
  3617. }
  3618. TEST_F(ServerTest, GetMethod404) {
  3619. auto res = cli_.Get("/invalid");
  3620. ASSERT_TRUE(res);
  3621. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3622. }
  3623. TEST_F(ServerTest, HeadMethod200) {
  3624. auto res = cli_.Head("/hi");
  3625. ASSERT_TRUE(res);
  3626. EXPECT_EQ(StatusCode::OK_200, res->status);
  3627. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3628. EXPECT_TRUE(res->body.empty());
  3629. }
  3630. TEST_F(ServerTest, HeadMethod200Static) {
  3631. auto res = cli_.Head("/mount/dir/index.html");
  3632. ASSERT_TRUE(res);
  3633. EXPECT_EQ(StatusCode::OK_200, res->status);
  3634. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3635. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3636. EXPECT_TRUE(res->body.empty());
  3637. }
  3638. TEST_F(ServerTest, HeadMethod404) {
  3639. auto res = cli_.Head("/invalid");
  3640. ASSERT_TRUE(res);
  3641. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3642. EXPECT_TRUE(res->body.empty());
  3643. }
  3644. TEST_F(ServerTest, GetMethodPersonJohn) {
  3645. auto res = cli_.Get("/person/john");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::OK_200, res->status);
  3648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3649. EXPECT_EQ("programmer", res->body);
  3650. }
  3651. TEST_F(ServerTest, PostMethod1) {
  3652. auto res = cli_.Get("/person/john1");
  3653. ASSERT_TRUE(res);
  3654. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3655. res = cli_.Post("/person", "name=john1&note=coder",
  3656. "application/x-www-form-urlencoded");
  3657. ASSERT_TRUE(res);
  3658. ASSERT_EQ(StatusCode::OK_200, res->status);
  3659. res = cli_.Get("/person/john1");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3663. ASSERT_EQ("coder", res->body);
  3664. }
  3665. TEST_F(ServerTest, PostMethod2) {
  3666. auto res = cli_.Get("/person/john2");
  3667. ASSERT_TRUE(res);
  3668. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3669. Params params;
  3670. params.emplace("name", "john2");
  3671. params.emplace("note", "coder");
  3672. res = cli_.Post("/person", params);
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. res = cli_.Get("/person/john2");
  3676. ASSERT_TRUE(res);
  3677. ASSERT_EQ(StatusCode::OK_200, res->status);
  3678. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3679. ASSERT_EQ("coder", res->body);
  3680. }
  3681. TEST_F(ServerTest, PutMethod3) {
  3682. auto res = cli_.Get("/person/john3");
  3683. ASSERT_TRUE(res);
  3684. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3685. Params params;
  3686. params.emplace("name", "john3");
  3687. params.emplace("note", "coder");
  3688. res = cli_.Put("/person", params);
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::OK_200, res->status);
  3691. res = cli_.Get("/person/john3");
  3692. ASSERT_TRUE(res);
  3693. ASSERT_EQ(StatusCode::OK_200, res->status);
  3694. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3695. ASSERT_EQ("coder", res->body);
  3696. }
  3697. TEST_F(ServerTest, DeleteMethod1) {
  3698. auto res = cli_.Get("/person/john4");
  3699. ASSERT_TRUE(res);
  3700. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3701. Params params;
  3702. params.emplace("name", "john4");
  3703. params.emplace("note", "coder");
  3704. res = cli_.Post("/person", params);
  3705. ASSERT_TRUE(res);
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. res = cli_.Get("/person/john4");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3711. ASSERT_EQ("coder", res->body);
  3712. Params delete_params;
  3713. delete_params.emplace("name", "john4");
  3714. res = cli_.Delete("/person", delete_params);
  3715. ASSERT_TRUE(res);
  3716. ASSERT_EQ(StatusCode::OK_200, res->status);
  3717. ASSERT_EQ("DELETED", res->body);
  3718. res = cli_.Get("/person/john4");
  3719. ASSERT_TRUE(res);
  3720. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3721. }
  3722. TEST_F(ServerTest, DeleteMethod2) {
  3723. auto res = cli_.Get("/person/john5");
  3724. ASSERT_TRUE(res);
  3725. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3726. Params params;
  3727. params.emplace("name", "john5");
  3728. params.emplace("note", "developer");
  3729. res = cli_.Post("/person", params);
  3730. ASSERT_TRUE(res);
  3731. ASSERT_EQ(StatusCode::OK_200, res->status);
  3732. res = cli_.Get("/person/john5");
  3733. ASSERT_TRUE(res);
  3734. ASSERT_EQ(StatusCode::OK_200, res->status);
  3735. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3736. ASSERT_EQ("developer", res->body);
  3737. Params delete_params;
  3738. delete_params.emplace("name", "john5");
  3739. Headers headers;
  3740. headers.emplace("Custom-Header", "test-value");
  3741. res = cli_.Delete("/person", headers, delete_params);
  3742. ASSERT_TRUE(res);
  3743. ASSERT_EQ(StatusCode::OK_200, res->status);
  3744. ASSERT_EQ("DELETED", res->body);
  3745. res = cli_.Get("/person/john5");
  3746. ASSERT_TRUE(res);
  3747. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, DeleteMethod3) {
  3750. auto res = cli_.Get("/person/john6");
  3751. ASSERT_TRUE(res);
  3752. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3753. Params params;
  3754. params.emplace("name", "john6");
  3755. params.emplace("note", "tester");
  3756. res = cli_.Post("/person", params);
  3757. ASSERT_TRUE(res);
  3758. ASSERT_EQ(StatusCode::OK_200, res->status);
  3759. res = cli_.Get("/person/john6");
  3760. ASSERT_TRUE(res);
  3761. ASSERT_EQ(StatusCode::OK_200, res->status);
  3762. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3763. ASSERT_EQ("tester", res->body);
  3764. Params delete_params;
  3765. delete_params.emplace("name", "john6");
  3766. Headers headers;
  3767. headers.emplace("Custom-Header", "test-value");
  3768. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3769. ASSERT_TRUE(res);
  3770. ASSERT_EQ(StatusCode::OK_200, res->status);
  3771. ASSERT_EQ("DELETED", res->body);
  3772. res = cli_.Get("/person/john6");
  3773. ASSERT_TRUE(res);
  3774. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3775. }
  3776. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3777. Params params;
  3778. params.emplace("json", JSON_DATA);
  3779. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3780. ASSERT_TRUE(res);
  3781. ASSERT_EQ(StatusCode::OK_200, res->status);
  3782. ASSERT_EQ(JSON_DATA, res->body);
  3783. }
  3784. TEST_F(ServerTest, PostEmptyContent) {
  3785. auto res = cli_.Post("/empty", "", "text/plain");
  3786. ASSERT_TRUE(res);
  3787. ASSERT_EQ(StatusCode::OK_200, res->status);
  3788. ASSERT_EQ("empty", res->body);
  3789. }
  3790. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3791. auto res = cli_.Post("/empty-no-content-type");
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::OK_200, res->status);
  3794. ASSERT_EQ("empty-no-content-type", res->body);
  3795. }
  3796. TEST_F(ServerTest, PostPathOnly) {
  3797. auto res = cli_.Post("/path-only");
  3798. ASSERT_TRUE(res);
  3799. ASSERT_EQ(StatusCode::OK_200, res->status);
  3800. ASSERT_EQ("path-only", res->body);
  3801. }
  3802. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3803. auto res = cli_.Post("/path-headers-only",
  3804. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3805. ASSERT_TRUE(res);
  3806. ASSERT_EQ(StatusCode::OK_200, res->status);
  3807. ASSERT_EQ("path-headers-only", res->body);
  3808. }
  3809. TEST_F(ServerTest, PostLarge) {
  3810. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(StatusCode::OK_200, res->status);
  3813. EXPECT_EQ(LARGE_DATA, res->body);
  3814. }
  3815. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3816. auto res = cli_.Put("/empty-no-content-type");
  3817. ASSERT_TRUE(res);
  3818. ASSERT_EQ(StatusCode::OK_200, res->status);
  3819. ASSERT_EQ("empty-no-content-type", res->body);
  3820. }
  3821. TEST_F(ServerTest, GetMethodDir) {
  3822. auto res = cli_.Get("/dir/");
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3826. auto body = R"(<html>
  3827. <head>
  3828. </head>
  3829. <body>
  3830. <a href="/dir/test.html">Test</a>
  3831. <a href="/hi">hi</a>
  3832. </body>
  3833. </html>
  3834. )";
  3835. EXPECT_EQ(body, res->body);
  3836. }
  3837. TEST_F(ServerTest, GetMethodDirTest) {
  3838. auto res = cli_.Get("/dir/test.html");
  3839. ASSERT_TRUE(res);
  3840. EXPECT_EQ(StatusCode::OK_200, res->status);
  3841. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3842. EXPECT_EQ("test.html", res->body);
  3843. }
  3844. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3845. auto res = cli_.Get("/dir/../dir/test.html");
  3846. ASSERT_TRUE(res);
  3847. EXPECT_EQ(StatusCode::OK_200, res->status);
  3848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3849. EXPECT_EQ("test.html", res->body);
  3850. }
  3851. TEST_F(ServerTest, GetMethodInvalidPath) {
  3852. auto res = cli_.Get("/dir/../test.html");
  3853. ASSERT_TRUE(res);
  3854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3855. }
  3856. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3857. auto res = cli_.Get("/../www/dir/test.html");
  3858. ASSERT_TRUE(res);
  3859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3860. }
  3861. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3862. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3865. }
  3866. TEST_F(ServerTest, GetMethodDirMountTest) {
  3867. auto res = cli_.Get("/mount/dir/test.html");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3871. EXPECT_EQ("test.html", res->body);
  3872. }
  3873. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3874. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(StatusCode::OK_200, res->status);
  3877. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3878. EXPECT_EQ("test.html", res->body);
  3879. }
  3880. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3881. auto res = cli_.Get("/mount/dir/../test.html");
  3882. ASSERT_TRUE(res);
  3883. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3884. }
  3885. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3886. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3887. ASSERT_TRUE(res);
  3888. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3889. }
  3890. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3891. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3894. }
  3895. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3896. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3899. }
  3900. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3901. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3904. }
  3905. TEST_F(ServerTest, PostMethod303) {
  3906. auto res = cli_.Post("/1", "body", "text/plain");
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3909. EXPECT_EQ("/2", res->get_header_value("Location"));
  3910. }
  3911. TEST_F(ServerTest, PostMethod303Redirect) {
  3912. cli_.set_follow_location(true);
  3913. auto res = cli_.Post("/1", "body", "text/plain");
  3914. ASSERT_TRUE(res);
  3915. EXPECT_EQ(StatusCode::OK_200, res->status);
  3916. EXPECT_EQ("redirected.", res->body);
  3917. EXPECT_EQ("/2", res->location);
  3918. }
  3919. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3920. auto res = cli_.Get("/dir/test.abcde");
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::OK_200, res->status);
  3923. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3924. EXPECT_EQ("abcde", res->body);
  3925. }
  3926. TEST_F(ServerTest, StaticFileRange) {
  3927. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3930. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3931. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ(true, res->has_header("Content-Range"));
  3933. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3934. EXPECT_EQ(std::string("cd"), res->body);
  3935. }
  3936. TEST_F(ServerTest, StaticFileRanges) {
  3937. auto res =
  3938. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3941. EXPECT_TRUE(
  3942. res->get_header_value("Content-Type")
  3943. .find(
  3944. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3945. 0);
  3946. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3947. }
  3948. TEST_F(ServerTest, StaticFileRangeHead) {
  3949. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3952. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3953. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3954. EXPECT_EQ(true, res->has_header("Content-Range"));
  3955. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3956. }
  3957. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3958. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3959. ASSERT_TRUE(res);
  3960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3962. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3963. EXPECT_EQ(true, res->has_header("Content-Range"));
  3964. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3965. res->get_header_value("Content-Range"));
  3966. EXPECT_EQ("LAST\n", res->body);
  3967. }
  3968. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3969. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3972. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3973. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3974. EXPECT_EQ(true, res->has_header("Content-Range"));
  3975. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3976. }
  3977. TEST_F(ServerTest, StaticFileBigFile) {
  3978. auto res = cli_.Get("/dir/1MB.txt");
  3979. ASSERT_TRUE(res);
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3982. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3983. }
  3984. TEST_F(ServerTest, InvalidBaseDirMount) {
  3985. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3986. }
  3987. TEST_F(ServerTest, Binary) {
  3988. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3989. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3990. "application/octet-stream");
  3991. ASSERT_TRUE(res);
  3992. ASSERT_EQ(StatusCode::OK_200, res->status);
  3993. ASSERT_EQ(4U, res->body.size());
  3994. res = cli_.Put("/binary", binary.data(), binary.size(),
  3995. "application/octet-stream");
  3996. ASSERT_TRUE(res);
  3997. ASSERT_EQ(StatusCode::OK_200, res->status);
  3998. ASSERT_EQ(4U, res->body.size());
  3999. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4000. "application/octet-stream");
  4001. ASSERT_TRUE(res);
  4002. ASSERT_EQ(StatusCode::OK_200, res->status);
  4003. ASSERT_EQ(4U, res->body.size());
  4004. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4005. "application/octet-stream");
  4006. ASSERT_TRUE(res);
  4007. ASSERT_EQ(StatusCode::OK_200, res->status);
  4008. ASSERT_EQ(4U, res->body.size());
  4009. }
  4010. TEST_F(ServerTest, BinaryString) {
  4011. auto binary = std::string("\x00\x01\x02\x03", 4);
  4012. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4013. ASSERT_TRUE(res);
  4014. ASSERT_EQ(StatusCode::OK_200, res->status);
  4015. ASSERT_EQ(4U, res->body.size());
  4016. res = cli_.Put("/binary", binary, "application/octet-stream");
  4017. ASSERT_TRUE(res);
  4018. ASSERT_EQ(StatusCode::OK_200, res->status);
  4019. ASSERT_EQ(4U, res->body.size());
  4020. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4021. ASSERT_TRUE(res);
  4022. ASSERT_EQ(StatusCode::OK_200, res->status);
  4023. ASSERT_EQ(4U, res->body.size());
  4024. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4025. ASSERT_TRUE(res);
  4026. ASSERT_EQ(StatusCode::OK_200, res->status);
  4027. ASSERT_EQ(4U, res->body.size());
  4028. }
  4029. TEST_F(ServerTest, EmptyRequest) {
  4030. auto res = cli_.Get("");
  4031. ASSERT_TRUE(!res);
  4032. EXPECT_EQ(Error::Connection, res.error());
  4033. }
  4034. TEST_F(ServerTest, LongRequest) {
  4035. std::string request;
  4036. for (size_t i = 0; i < 545; i++) {
  4037. request += "/TooLongRequest";
  4038. }
  4039. request += "OK";
  4040. auto res = cli_.Get(request.c_str());
  4041. ASSERT_TRUE(res);
  4042. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4043. }
  4044. TEST_F(ServerTest, TooLongRequest) {
  4045. std::string request;
  4046. for (size_t i = 0; i < 546; i++) {
  4047. request += "/TooLongRequest";
  4048. }
  4049. request += "_NG";
  4050. auto start = std::chrono::high_resolution_clock::now();
  4051. cli_.set_keep_alive(true);
  4052. auto res = cli_.Get(request.c_str());
  4053. auto end = std::chrono::high_resolution_clock::now();
  4054. auto elapsed =
  4055. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4056. .count();
  4057. ASSERT_TRUE(res);
  4058. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4059. EXPECT_LE(elapsed, 1000);
  4060. EXPECT_EQ("close", res->get_header_value("Connection"));
  4061. EXPECT_FALSE(cli_.is_socket_open());
  4062. }
  4063. TEST_F(ServerTest, AlmostTooLongRequest) {
  4064. // test for #2046 - URI length check shouldn't include other content on req
  4065. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4066. // leading /, space, HTTP/1.1)
  4067. std::string request =
  4068. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4069. auto res = cli_.Get(request.c_str());
  4070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4072. }
  4073. TEST_F(ServerTest, LongHeader) {
  4074. Request req;
  4075. req.method = "GET";
  4076. req.path = "/hi";
  4077. std::string host_and_port;
  4078. host_and_port += HOST;
  4079. host_and_port += ":";
  4080. host_and_port += std::to_string(PORT);
  4081. req.headers.emplace("Host", host_and_port.c_str());
  4082. req.headers.emplace("Accept", "*/*");
  4083. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4084. req.headers.emplace(
  4085. "Header-Name",
  4086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4114. "@@@@@@@@@@@@@@@@");
  4115. auto res = std::make_shared<Response>();
  4116. auto error = Error::Success;
  4117. auto ret = cli_.send(req, *res, error);
  4118. ASSERT_TRUE(ret);
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. }
  4121. TEST_F(ServerTest, LongQueryValue) {
  4122. auto start = std::chrono::high_resolution_clock::now();
  4123. cli_.set_keep_alive(true);
  4124. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4125. auto end = std::chrono::high_resolution_clock::now();
  4126. auto elapsed =
  4127. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4128. .count();
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4131. EXPECT_LE(elapsed, 1000);
  4132. EXPECT_EQ("close", res->get_header_value("Connection"));
  4133. EXPECT_FALSE(cli_.is_socket_open());
  4134. }
  4135. TEST_F(ServerTest, TooLongQueryValue) {
  4136. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4137. ASSERT_FALSE(res);
  4138. EXPECT_EQ(Error::Read, res.error());
  4139. }
  4140. TEST_F(ServerTest, TooLongHeader) {
  4141. Request req;
  4142. req.method = "GET";
  4143. req.path = "/hi";
  4144. std::string host_and_port;
  4145. host_and_port += HOST;
  4146. host_and_port += ":";
  4147. host_and_port += std::to_string(PORT);
  4148. req.headers.emplace("Host", host_and_port.c_str());
  4149. req.headers.emplace("Accept", "*/*");
  4150. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4151. req.headers.emplace(
  4152. "Header-Name",
  4153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4181. "@@@@@@@@@@@@@@@@@");
  4182. auto res = std::make_shared<Response>();
  4183. auto error = Error::Success;
  4184. auto ret = cli_.send(req, *res, error);
  4185. ASSERT_TRUE(ret);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. }
  4188. TEST_F(ServerTest, HeaderCountAtLimit) {
  4189. // Test with headers just under the 100 limit
  4190. httplib::Headers headers;
  4191. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4192. // This should keep us just under the 100 header limit
  4193. for (int i = 0; i < 95; i++) {
  4194. std::string name = "X-Test-Header-" + std::to_string(i);
  4195. std::string value = "value" + std::to_string(i);
  4196. headers.emplace(name, value);
  4197. }
  4198. // This should work fine as we're under the limit
  4199. auto res = cli_.Get("/hi", headers);
  4200. EXPECT_TRUE(res);
  4201. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4202. }
  4203. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4204. // Test with many headers to exceed the 100 limit
  4205. httplib::Headers headers;
  4206. // Add 150 headers to definitely exceed the 100 limit
  4207. for (int i = 0; i < 150; i++) {
  4208. std::string name = "X-Test-Header-" + std::to_string(i);
  4209. std::string value = "value" + std::to_string(i);
  4210. headers.emplace(name, value);
  4211. }
  4212. // This should fail due to exceeding header count limit
  4213. cli_.set_keep_alive(true);
  4214. auto res = cli_.Get("/hi", headers);
  4215. // The server should respond with 400 Bad Request
  4216. ASSERT_TRUE(res);
  4217. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4218. EXPECT_EQ("close", res->get_header_value("Connection"));
  4219. EXPECT_FALSE(cli_.is_socket_open());
  4220. }
  4221. TEST_F(ServerTest, PercentEncoding) {
  4222. auto res = cli_.Get("/e%6edwith%");
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::OK_200, res->status);
  4225. }
  4226. TEST_F(ServerTest, PercentEncodingUnicode) {
  4227. auto res = cli_.Get("/e%u006edwith%");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. }
  4231. TEST_F(ServerTest, InvalidPercentEncoding) {
  4232. auto res = cli_.Get("/%endwith%");
  4233. ASSERT_TRUE(res);
  4234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4235. }
  4236. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4237. auto res = cli_.Get("/%uendwith%");
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4240. }
  4241. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4242. auto res = cli_.Get("/hello?aaa=bbb%");
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4245. }
  4246. TEST_F(ServerTest, PlusSignEncoding) {
  4247. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("a +b", res->body);
  4251. }
  4252. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4253. // This test simulates a potential DoS attack using many headers
  4254. // to verify our security fix prevents memory exhaustion
  4255. httplib::Headers attack_headers;
  4256. // Attempt to add many headers like an attacker would (200 headers to far
  4257. // exceed limit)
  4258. for (int i = 0; i < 200; i++) {
  4259. std::string name = "X-Attack-Header-" + std::to_string(i);
  4260. std::string value = "attack_payload_" + std::to_string(i);
  4261. attack_headers.emplace(name, value);
  4262. }
  4263. // Try to POST with excessive headers
  4264. cli_.set_keep_alive(true);
  4265. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4266. // Should either fail or return 400 Bad Request due to security limit
  4267. if (res) {
  4268. // If we get a response, it should be 400 Bad Request
  4269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4270. EXPECT_EQ("close", res->get_header_value("Connection"));
  4271. }
  4272. EXPECT_FALSE(cli_.is_socket_open());
  4273. }
  4274. TEST_F(ServerTest, MultipartFormData) {
  4275. UploadFormDataItems items = {
  4276. {"text1", "text default", "", ""},
  4277. {"text2", "aωb", "", ""},
  4278. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4279. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4280. {"file3", "", "", "application/octet-stream"},
  4281. {"file4", "", "", " application/json tmp-string "}};
  4282. auto res = cli_.Post("/multipart", items);
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::OK_200, res->status);
  4285. }
  4286. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4287. UploadFormDataItems items = {
  4288. {"text", "default text", "", ""},
  4289. {"multi_text1", "aaaaa", "", ""},
  4290. {"multi_text1", "bbbbb", "", ""},
  4291. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4292. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4293. "application/json"},
  4294. };
  4295. auto res = cli_.Post("/multipart/multi_file_values", items);
  4296. ASSERT_TRUE(res);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. }
  4299. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4300. auto res = cli_.Get("/hi");
  4301. ASSERT_TRUE(res);
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4304. EXPECT_EQ("Hello World!", res->body);
  4305. }
  4306. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4307. Request req;
  4308. req.method = "POST";
  4309. req.path = "/chunked";
  4310. std::string host_and_port;
  4311. host_and_port += HOST;
  4312. host_and_port += ":";
  4313. host_and_port += std::to_string(PORT);
  4314. req.headers.emplace("Host", host_and_port.c_str());
  4315. req.headers.emplace("Accept", "*/*");
  4316. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4317. req.headers.emplace("Content-Type", "text/plain");
  4318. req.headers.emplace("Content-Length", "0");
  4319. req.headers.emplace(
  4320. "Transfer-Encoding",
  4321. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4322. // Client does not chunk, so make a chunked body manually.
  4323. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4324. auto res = std::make_shared<Response>();
  4325. auto error = Error::Success;
  4326. auto ret = cli_.send(req, *res, error);
  4327. ASSERT_TRUE(ret);
  4328. EXPECT_EQ(StatusCode::OK_200, res->status);
  4329. }
  4330. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4331. // rather than treat them as valid lengths.
  4332. template <typename ClientT>
  4333. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4334. Request req;
  4335. req.method = "POST";
  4336. req.path = "/chunked";
  4337. std::string host_and_port;
  4338. host_and_port += HOST;
  4339. host_and_port += ":";
  4340. host_and_port += std::to_string(PORT);
  4341. req.headers.emplace("Host", host_and_port.c_str());
  4342. req.headers.emplace("Content-Length", "0");
  4343. req.headers.emplace("Transfer-Encoding", "chunked");
  4344. req.body = body;
  4345. auto res = std::make_shared<Response>();
  4346. auto error = Error::Success;
  4347. ASSERT_TRUE(cli.send(req, *res, error));
  4348. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4349. }
  4350. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4351. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4352. }
  4353. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4354. expect_chunked_body_rejected(
  4355. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4356. }
  4357. TEST_F(ServerTest, GetStreamed2) {
  4358. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4361. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4362. EXPECT_EQ(true, res->has_header("Content-Range"));
  4363. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4364. EXPECT_EQ(std::string("ab"), res->body);
  4365. }
  4366. TEST_F(ServerTest, GetStreamed) {
  4367. auto res = cli_.Get("/streamed");
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4371. EXPECT_EQ(std::string("aaabbb"), res->body);
  4372. }
  4373. TEST_F(ServerTest, GetStreamedWithRange1) {
  4374. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4375. ASSERT_TRUE(res);
  4376. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4377. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4378. EXPECT_EQ(true, res->has_header("Content-Range"));
  4379. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4380. EXPECT_EQ(std::string("def"), res->body);
  4381. }
  4382. TEST_F(ServerTest, GetStreamedWithRange2) {
  4383. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4386. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4387. EXPECT_EQ(true, res->has_header("Content-Range"));
  4388. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4389. EXPECT_EQ(std::string("bcdefg"), res->body);
  4390. }
  4391. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4392. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4393. ASSERT_TRUE(res);
  4394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4395. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4396. EXPECT_EQ(true, res->has_header("Content-Range"));
  4397. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4398. EXPECT_EQ(std::string("efg"), res->body);
  4399. }
  4400. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4401. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4402. ASSERT_TRUE(res);
  4403. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4404. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4405. EXPECT_EQ(false, res->has_header("Content-Range"));
  4406. EXPECT_EQ(0U, res->body.size());
  4407. }
  4408. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4409. auto res = cli_.Get("/streamed-with-range",
  4410. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4411. "92233720368547758079223372036854775807"}});
  4412. ASSERT_TRUE(res);
  4413. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4414. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4415. EXPECT_EQ(false, res->has_header("Content-Range"));
  4416. EXPECT_EQ(0U, res->body.size());
  4417. }
  4418. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4419. auto res = cli_.Get(
  4420. "/with-range",
  4421. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4422. {"Accept-Encoding", ""}});
  4423. ASSERT_TRUE(res);
  4424. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4425. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4426. EXPECT_EQ(true, res->has_header("Content-Range"));
  4427. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4428. EXPECT_EQ(std::string("abcdefg"), res->body);
  4429. }
  4430. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4431. auto res = cli_.Get("/with-range", {
  4432. {"Range", "bytes=0-"},
  4433. {"Accept-Encoding", ""},
  4434. });
  4435. ASSERT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4437. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4438. EXPECT_EQ(true, res->has_header("Content-Range"));
  4439. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4440. EXPECT_EQ(std::string("abcdefg"), res->body);
  4441. }
  4442. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4443. auto res =
  4444. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4445. ASSERT_TRUE(res);
  4446. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4447. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4448. EXPECT_EQ(false, res->has_header("Content-Range"));
  4449. EXPECT_EQ(267U, res->body.size());
  4450. // Check that both range contents are present
  4451. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4452. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4453. // Check that Content-Range headers are present for both ranges
  4454. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4455. std::string::npos);
  4456. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4457. std::string::npos);
  4458. }
  4459. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4460. Ranges ranges;
  4461. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4462. ranges.emplace_back(0, -1);
  4463. }
  4464. auto res =
  4465. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4466. ASSERT_TRUE(res);
  4467. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4468. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4469. EXPECT_EQ(false, res->has_header("Content-Range"));
  4470. EXPECT_EQ(0U, res->body.size());
  4471. }
  4472. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4473. auto res =
  4474. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4475. ASSERT_TRUE(res);
  4476. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4477. EXPECT_EQ(5U, res->body.size());
  4478. // Check that overlapping ranges are coalesced into a single range
  4479. EXPECT_EQ("bcdef", res->body);
  4480. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4481. // Should be single range, not multipart
  4482. EXPECT_TRUE(res->has_header("Content-Range"));
  4483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4484. }
  4485. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4486. auto res =
  4487. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4488. ASSERT_TRUE(res);
  4489. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4490. EXPECT_EQ(268U, res->body.size());
  4491. // Check that both range contents are present
  4492. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4493. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4494. // Check that Content-Range headers are present for both ranges
  4495. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4496. std::string::npos);
  4497. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4498. std::string::npos);
  4499. }
  4500. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4501. auto res =
  4502. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4503. ASSERT_TRUE(res);
  4504. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4505. EXPECT_EQ(269U, res->body.size());
  4506. // Check that both duplicate range contents are present
  4507. size_t first_abc = res->body.find("abc\r\n");
  4508. EXPECT_TRUE(first_abc != std::string::npos);
  4509. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4510. EXPECT_TRUE(second_abc != std::string::npos);
  4511. // Check that Content-Range headers are present for both ranges
  4512. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4513. EXPECT_TRUE(first_range != std::string::npos);
  4514. size_t second_range =
  4515. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4516. EXPECT_TRUE(second_range != std::string::npos);
  4517. }
  4518. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4519. auto res = cli_.Get("/streamed-with-range?error",
  4520. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4523. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4524. EXPECT_EQ(false, res->has_header("Content-Range"));
  4525. EXPECT_EQ(0U, res->body.size());
  4526. }
  4527. TEST_F(ServerTest, GetStreamedEndless) {
  4528. uint64_t offset = 0;
  4529. auto res = cli_.Get("/streamed-cancel",
  4530. [&](const char * /*data*/, uint64_t data_length) {
  4531. if (offset < 100) {
  4532. offset += data_length;
  4533. return true;
  4534. }
  4535. return false;
  4536. });
  4537. ASSERT_TRUE(!res);
  4538. EXPECT_EQ(Error::Canceled, res.error());
  4539. }
  4540. TEST_F(ServerTest, ClientStop) {
  4541. std::atomic_size_t count{4};
  4542. std::vector<std::thread> threads;
  4543. for (auto i = count.load(); i != 0; --i) {
  4544. threads.emplace_back([&]() {
  4545. auto res = cli_.Get("/streamed-cancel",
  4546. [&](const char *, uint64_t) { return true; });
  4547. --count;
  4548. ASSERT_TRUE(!res);
  4549. EXPECT_TRUE(res.error() == Error::Canceled ||
  4550. res.error() == Error::Read || res.error() == Error::Write);
  4551. });
  4552. }
  4553. std::this_thread::sleep_for(std::chrono::seconds(2));
  4554. while (count != 0) {
  4555. cli_.stop();
  4556. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4557. }
  4558. for (auto &t : threads) {
  4559. t.join();
  4560. }
  4561. }
  4562. TEST_F(ServerTest, GetWithRange1) {
  4563. auto res = cli_.Get("/with-range", {
  4564. make_range_header({{3, 5}}),
  4565. {"Accept-Encoding", ""},
  4566. });
  4567. ASSERT_TRUE(res);
  4568. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4569. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4570. EXPECT_EQ(true, res->has_header("Content-Range"));
  4571. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4572. EXPECT_EQ(std::string("def"), res->body);
  4573. }
  4574. TEST_F(ServerTest, GetWithRange2) {
  4575. auto res = cli_.Get("/with-range", {
  4576. make_range_header({{1, -1}}),
  4577. {"Accept-Encoding", ""},
  4578. });
  4579. ASSERT_TRUE(res);
  4580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4581. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4582. EXPECT_EQ(true, res->has_header("Content-Range"));
  4583. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4584. EXPECT_EQ(std::string("bcdefg"), res->body);
  4585. }
  4586. TEST_F(ServerTest, GetWithRange3) {
  4587. auto res = cli_.Get("/with-range", {
  4588. make_range_header({{0, 0}}),
  4589. {"Accept-Encoding", ""},
  4590. });
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4593. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4594. EXPECT_EQ(true, res->has_header("Content-Range"));
  4595. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4596. EXPECT_EQ(std::string("a"), res->body);
  4597. }
  4598. TEST_F(ServerTest, GetWithRange4) {
  4599. auto res = cli_.Get("/with-range", {
  4600. make_range_header({{-1, 2}}),
  4601. {"Accept-Encoding", ""},
  4602. });
  4603. ASSERT_TRUE(res);
  4604. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4605. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4606. EXPECT_EQ(true, res->has_header("Content-Range"));
  4607. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4608. EXPECT_EQ(std::string("fg"), res->body);
  4609. }
  4610. TEST_F(ServerTest, GetWithRange5) {
  4611. auto res = cli_.Get("/with-range", {
  4612. make_range_header({{0, 5}}),
  4613. {"Accept-Encoding", ""},
  4614. });
  4615. ASSERT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4617. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4618. EXPECT_EQ(true, res->has_header("Content-Range"));
  4619. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4620. EXPECT_EQ(std::string("abcdef"), res->body);
  4621. }
  4622. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4623. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4624. ASSERT_TRUE(res);
  4625. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4626. }
  4627. TEST_F(ServerTest, GetWithRangeMultipart) {
  4628. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4629. ASSERT_TRUE(res);
  4630. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4631. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4632. EXPECT_EQ(false, res->has_header("Content-Range"));
  4633. EXPECT_EQ(267U, res->body.size());
  4634. }
  4635. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4636. auto res =
  4637. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4638. ASSERT_TRUE(res);
  4639. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4640. }
  4641. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4642. auto res = cli_.Get("/with-range-customized-response",
  4643. {{make_range_header({{1, 2}})}});
  4644. ASSERT_TRUE(res);
  4645. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4646. EXPECT_EQ(true, res->has_header("Content-Length"));
  4647. EXPECT_EQ(false, res->has_header("Content-Range"));
  4648. EXPECT_EQ(JSON_DATA, res->body);
  4649. }
  4650. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4651. auto res = cli_.Get("/with-range-customized-response",
  4652. {{make_range_header({{1, 2}, {4, 5}})}});
  4653. ASSERT_TRUE(res);
  4654. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4655. EXPECT_EQ(true, res->has_header("Content-Length"));
  4656. EXPECT_EQ(false, res->has_header("Content-Range"));
  4657. EXPECT_EQ(JSON_DATA, res->body);
  4658. }
  4659. TEST_F(ServerTest, Issue1772) {
  4660. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4661. ASSERT_TRUE(res);
  4662. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4663. }
  4664. TEST_F(ServerTest, Issue609) {
  4665. auto res = cli_.Delete("/issue609");
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ(std::string("ok"), res->body);
  4669. }
  4670. TEST_F(ServerTest, GetStreamedChunked) {
  4671. auto res = cli_.Get("/streamed-chunked");
  4672. ASSERT_TRUE(res);
  4673. EXPECT_EQ(StatusCode::OK_200, res->status);
  4674. EXPECT_EQ(std::string("123456789"), res->body);
  4675. }
  4676. TEST_F(ServerTest, GetStreamedChunked2) {
  4677. auto res = cli_.Get("/streamed-chunked2");
  4678. ASSERT_TRUE(res);
  4679. EXPECT_EQ(StatusCode::OK_200, res->status);
  4680. EXPECT_EQ(std::string("123456789"), res->body);
  4681. }
  4682. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4683. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4684. ASSERT_TRUE(res);
  4685. EXPECT_EQ(StatusCode::OK_200, res->status);
  4686. EXPECT_EQ(std::string("123456789"), res->body);
  4687. EXPECT_TRUE(res->has_header("Trailer"));
  4688. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4689. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4690. // Trailers are now stored separately from headers (security fix)
  4691. EXPECT_EQ(2U, res->trailers.size());
  4692. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4693. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4694. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4695. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4696. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4697. // Verify trailers are NOT in headers (security verification)
  4698. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4699. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4700. }
  4701. TEST_F(ServerTest, LargeChunkedPost) {
  4702. Request req;
  4703. req.method = "POST";
  4704. req.path = "/large-chunked";
  4705. std::string host_and_port;
  4706. host_and_port += HOST;
  4707. host_and_port += ":";
  4708. host_and_port += std::to_string(PORT);
  4709. req.headers.emplace("Host", host_and_port.c_str());
  4710. req.headers.emplace("Accept", "*/*");
  4711. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4712. req.headers.emplace("Content-Type", "text/plain");
  4713. req.headers.emplace("Content-Length", "0");
  4714. req.headers.emplace("Transfer-Encoding", "chunked");
  4715. std::string long_string(30 * 1024u, 'a');
  4716. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4717. // Attempt to make a large enough post to exceed OS buffers, to test that
  4718. // the server handles short reads if the full chunk data isn't available.
  4719. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4720. auto res = std::make_shared<Response>();
  4721. auto error = Error::Success;
  4722. auto ret = cli_.send(req, *res, error);
  4723. ASSERT_TRUE(ret);
  4724. EXPECT_EQ(StatusCode::OK_200, res->status);
  4725. }
  4726. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4727. auto res = cli_.Get("/remote_addr");
  4728. ASSERT_TRUE(res);
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4731. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4732. }
  4733. TEST_F(ServerTest, GetMethodLocalAddr) {
  4734. auto res = cli_.Get("/local_addr");
  4735. ASSERT_TRUE(res);
  4736. EXPECT_EQ(StatusCode::OK_200, res->status);
  4737. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4738. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4739. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4740. }
  4741. TEST_F(ServerTest, HTTPResponseSplitting) {
  4742. auto res = cli_.Get("/http_response_splitting");
  4743. ASSERT_TRUE(res);
  4744. EXPECT_EQ(StatusCode::OK_200, res->status);
  4745. }
  4746. TEST_F(ServerTest, SlowRequest) {
  4747. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4748. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4749. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4750. }
  4751. #if 0
  4752. TEST_F(ServerTest, SlowPost) {
  4753. char buffer[64 * 1024];
  4754. memset(buffer, 0x42, sizeof(buffer));
  4755. auto res = cli_.Post(
  4756. "/slowpost", 64 * 1024 * 1024,
  4757. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4758. auto ret = sink.write(buffer, sizeof(buffer));
  4759. EXPECT_TRUE(ret);
  4760. return true;
  4761. },
  4762. "text/plain");
  4763. ASSERT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. }
  4766. TEST_F(ServerTest, SlowPostFail) {
  4767. char buffer[64 * 1024];
  4768. memset(buffer, 0x42, sizeof(buffer));
  4769. cli_.set_write_timeout(std::chrono::seconds(0));
  4770. auto res = cli_.Post(
  4771. "/slowpost", 64 * 1024 * 1024,
  4772. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4773. sink.write(buffer, sizeof(buffer));
  4774. return true;
  4775. },
  4776. "text/plain");
  4777. ASSERT_TRUE(!res);
  4778. EXPECT_EQ(Error::Write, res.error());
  4779. }
  4780. #endif
  4781. TEST_F(ServerTest, Put) {
  4782. auto res = cli_.Put("/put", "PUT", "text/plain");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("PUT", res->body);
  4786. }
  4787. TEST_F(ServerTest, PutWithContentProvider) {
  4788. auto res = cli_.Put(
  4789. "/put", 3,
  4790. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4791. sink.os << "PUT";
  4792. return true;
  4793. },
  4794. "text/plain");
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("PUT", res->body);
  4798. }
  4799. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4800. auto res = cli_.Post(
  4801. "/post", 42,
  4802. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4803. return false;
  4804. },
  4805. "text/plain");
  4806. ASSERT_TRUE(!res);
  4807. EXPECT_EQ(Error::Canceled, res.error());
  4808. }
  4809. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4810. auto res = cli_.Put(
  4811. "/put",
  4812. [](size_t /*offset*/, DataSink &sink) {
  4813. sink.os << "PUT";
  4814. sink.done();
  4815. return true;
  4816. },
  4817. "text/plain");
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. EXPECT_EQ("PUT", res->body);
  4821. }
  4822. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4823. auto res = cli_.Post(
  4824. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4825. "text/plain");
  4826. ASSERT_TRUE(!res);
  4827. EXPECT_EQ(Error::Canceled, res.error());
  4828. }
  4829. TEST_F(ServerTest, PostLoopBack) {
  4830. std::string body;
  4831. auto res = cli_.Post(
  4832. "/post-loopback", 9,
  4833. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4834. EXPECT_EQ(9u, length);
  4835. sink.write("123", 3);
  4836. sink.write("456", 3);
  4837. sink.write("789", 3);
  4838. return true;
  4839. },
  4840. "text/plain",
  4841. [&body](const char *data, size_t data_length) {
  4842. body.append(data, data_length);
  4843. return true;
  4844. });
  4845. ASSERT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::OK_200, res->status);
  4847. EXPECT_EQ("123456789", body);
  4848. }
  4849. TEST_F(ServerTest, PutLoopBack) {
  4850. std::string body;
  4851. auto res = cli_.Put(
  4852. "/put-loopback", 9,
  4853. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4854. EXPECT_EQ(9u, length);
  4855. sink.write("123", 3);
  4856. sink.write("456", 3);
  4857. sink.write("789", 3);
  4858. return true;
  4859. },
  4860. "text/plain",
  4861. [&body](const char *data, size_t data_length) {
  4862. body.append(data, data_length);
  4863. return true;
  4864. });
  4865. ASSERT_TRUE(res);
  4866. EXPECT_EQ(StatusCode::OK_200, res->status);
  4867. EXPECT_EQ("123456789", body);
  4868. }
  4869. TEST_F(ServerTest, PatchLoopBack) {
  4870. std::string body;
  4871. auto res = cli_.Patch(
  4872. "/patch-loopback", 9,
  4873. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4874. EXPECT_EQ(9u, length);
  4875. sink.write("123", 3);
  4876. sink.write("456", 3);
  4877. sink.write("789", 3);
  4878. return true;
  4879. },
  4880. "text/plain",
  4881. [&body](const char *data, size_t data_length) {
  4882. body.append(data, data_length);
  4883. return true;
  4884. });
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. EXPECT_EQ("123456789", body);
  4888. }
  4889. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4890. std::string body;
  4891. auto res = cli_.Post(
  4892. "/post-loopback",
  4893. [](size_t /*offset*/, DataSink &sink) {
  4894. sink.write("123", 3);
  4895. sink.write("456", 3);
  4896. sink.write("789", 3);
  4897. sink.done();
  4898. return true;
  4899. },
  4900. "text/plain",
  4901. [&body](const char *data, size_t data_length) {
  4902. body.append(data, data_length);
  4903. return true;
  4904. });
  4905. ASSERT_TRUE(res);
  4906. EXPECT_EQ(StatusCode::OK_200, res->status);
  4907. EXPECT_EQ("123456789", body);
  4908. }
  4909. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4910. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4911. cli_.set_compress(true);
  4912. auto res = cli_.Put(
  4913. "/put", 3,
  4914. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4915. sink.os << "PUT";
  4916. return true;
  4917. },
  4918. "text/plain");
  4919. ASSERT_TRUE(res);
  4920. EXPECT_EQ(StatusCode::OK_200, res->status);
  4921. EXPECT_EQ("PUT", res->body);
  4922. }
  4923. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4924. cli_.set_compress(true);
  4925. auto res = cli_.Post(
  4926. "/post", 42,
  4927. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4928. return false;
  4929. },
  4930. "text/plain");
  4931. ASSERT_TRUE(!res);
  4932. EXPECT_EQ(Error::Canceled, res.error());
  4933. }
  4934. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4935. cli_.set_compress(true);
  4936. auto res = cli_.Put(
  4937. "/put",
  4938. [](size_t /*offset*/, DataSink &sink) {
  4939. sink.os << "PUT";
  4940. sink.done();
  4941. return true;
  4942. },
  4943. "text/plain");
  4944. ASSERT_TRUE(res);
  4945. EXPECT_EQ(StatusCode::OK_200, res->status);
  4946. EXPECT_EQ("PUT", res->body);
  4947. }
  4948. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4949. cli_.set_compress(true);
  4950. auto res = cli_.Post(
  4951. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4952. "text/plain");
  4953. ASSERT_TRUE(!res);
  4954. EXPECT_EQ(Error::Canceled, res.error());
  4955. }
  4956. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4957. cli_.set_compress(true);
  4958. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4959. ASSERT_TRUE(res);
  4960. EXPECT_EQ(StatusCode::OK_200, res->status);
  4961. EXPECT_EQ(LARGE_DATA, res->body);
  4962. }
  4963. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4964. #ifdef CPPHTTPLIB_SSL_ENABLED
  4965. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4966. Client cli(s.c_str());
  4967. cli.enable_server_certificate_verification(false);
  4968. #else
  4969. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4970. Client cli(s.c_str());
  4971. #endif
  4972. cli.set_compress(true);
  4973. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ(LARGE_DATA, res->body);
  4977. // The compressed size should be less than a 10th of the original. May vary
  4978. // depending on the zlib library.
  4979. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4980. static_cast<uint64_t>(10 * 1024 * 1024));
  4981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4982. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4983. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4984. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4985. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4986. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4987. #endif
  4988. }
  4989. TEST_F(ServerTest, PutContentWithDeflate) {
  4990. cli_.set_compress(false);
  4991. Headers headers;
  4992. headers.emplace("Content-Encoding", "deflate");
  4993. // PUT in deflate format:
  4994. auto res = cli_.Put("/put", headers,
  4995. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4996. ASSERT_TRUE(res);
  4997. EXPECT_EQ(StatusCode::OK_200, res->status);
  4998. EXPECT_EQ("PUT", res->body);
  4999. }
  5000. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5001. Headers headers;
  5002. headers.emplace("Accept-Encoding", "gzip, deflate");
  5003. auto res = cli_.Get("/streamed-chunked", headers);
  5004. ASSERT_TRUE(res);
  5005. EXPECT_EQ(StatusCode::OK_200, res->status);
  5006. EXPECT_EQ(std::string("123456789"), res->body);
  5007. }
  5008. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5009. Headers headers;
  5010. headers.emplace("Accept-Encoding", "gzip, deflate");
  5011. auto res = cli_.Get("/streamed-chunked2", headers);
  5012. ASSERT_TRUE(res);
  5013. EXPECT_EQ(StatusCode::OK_200, res->status);
  5014. EXPECT_EQ(std::string("123456789"), res->body);
  5015. }
  5016. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5017. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5018. ASSERT_TRUE(res);
  5019. EXPECT_EQ(StatusCode::OK_200, res->status);
  5020. }
  5021. TEST(GzipDecompressor, ChunkedDecompression) {
  5022. std::string data;
  5023. for (size_t i = 0; i < 32 * 1024; ++i) {
  5024. data.push_back(static_cast<char>('a' + i % 26));
  5025. }
  5026. std::string compressed_data;
  5027. {
  5028. httplib::detail::gzip_compressor compressor;
  5029. bool result = compressor.compress(
  5030. data.data(), data.size(),
  5031. /*last=*/true,
  5032. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5033. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5034. compressed_data_size);
  5035. return true;
  5036. });
  5037. ASSERT_TRUE(result);
  5038. }
  5039. std::string decompressed_data;
  5040. {
  5041. httplib::detail::gzip_decompressor decompressor;
  5042. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5043. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5044. size_t chunk_size = 130;
  5045. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5046. chunk_begin += chunk_size) {
  5047. size_t current_chunk_size =
  5048. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5049. bool result = decompressor.decompress(
  5050. compressed_data.data() + chunk_begin, current_chunk_size,
  5051. [&](const char *decompressed_data_chunk,
  5052. size_t decompressed_data_chunk_size) {
  5053. decompressed_data.insert(decompressed_data.size(),
  5054. decompressed_data_chunk,
  5055. decompressed_data_chunk_size);
  5056. return true;
  5057. });
  5058. ASSERT_TRUE(result);
  5059. }
  5060. }
  5061. ASSERT_EQ(data, decompressed_data);
  5062. }
  5063. TEST(GzipDecompressor, DeflateDecompression) {
  5064. std::string original_text = "Raw deflate without gzip";
  5065. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5066. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5067. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5068. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5069. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5070. std::string decompressed_data;
  5071. {
  5072. httplib::detail::gzip_decompressor decompressor;
  5073. bool result = decompressor.decompress(
  5074. compressed_data.data(), compressed_data.size(),
  5075. [&](const char *decompressed_data_chunk,
  5076. size_t decompressed_data_chunk_size) {
  5077. decompressed_data.insert(decompressed_data.size(),
  5078. decompressed_data_chunk,
  5079. decompressed_data_chunk_size);
  5080. return true;
  5081. });
  5082. ASSERT_TRUE(result);
  5083. }
  5084. ASSERT_EQ(original_text, decompressed_data);
  5085. }
  5086. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5087. std::string original_text = "Raw deflate without gzip";
  5088. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5089. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5090. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5091. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5092. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5093. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5094. std::string decompressed_data;
  5095. {
  5096. httplib::detail::gzip_decompressor decompressor;
  5097. bool result = decompressor.decompress(
  5098. compressed_data.data(), compressed_data.size(),
  5099. [&](const char *decompressed_data_chunk,
  5100. size_t decompressed_data_chunk_size) {
  5101. decompressed_data.insert(decompressed_data.size(),
  5102. decompressed_data_chunk,
  5103. decompressed_data_chunk_size);
  5104. return true;
  5105. });
  5106. ASSERT_TRUE(result);
  5107. }
  5108. ASSERT_EQ(original_text, decompressed_data);
  5109. }
  5110. #endif
  5111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5112. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5113. Headers headers;
  5114. headers.emplace("Accept-Encoding", "br");
  5115. auto res = cli_.Get("/streamed-chunked", headers);
  5116. ASSERT_TRUE(res);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. EXPECT_EQ(std::string("123456789"), res->body);
  5119. }
  5120. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5121. Headers headers;
  5122. headers.emplace("Accept-Encoding", "br");
  5123. auto res = cli_.Get("/streamed-chunked2", headers);
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ(std::string("123456789"), res->body);
  5127. }
  5128. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5129. cli_.set_compress(true);
  5130. auto res = cli_.Put(
  5131. "/put", 3,
  5132. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5133. sink.os << "PUT";
  5134. return true;
  5135. },
  5136. "text/plain");
  5137. ASSERT_TRUE(res);
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ("PUT", res->body);
  5140. }
  5141. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5142. cli_.set_compress(true);
  5143. auto res = cli_.Put(
  5144. "/put",
  5145. [](size_t /*offset*/, DataSink &sink) {
  5146. sink.os << "PUT";
  5147. sink.done();
  5148. return true;
  5149. },
  5150. "text/plain");
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("PUT", res->body);
  5154. }
  5155. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5156. cli_.set_compress(true);
  5157. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5158. ASSERT_TRUE(res);
  5159. EXPECT_EQ(StatusCode::OK_200, res->status);
  5160. EXPECT_EQ(LARGE_DATA, res->body);
  5161. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5162. }
  5163. #endif
  5164. TEST_F(ServerTest, Patch) {
  5165. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5166. ASSERT_TRUE(res);
  5167. EXPECT_EQ(StatusCode::OK_200, res->status);
  5168. EXPECT_EQ("PATCH", res->body);
  5169. }
  5170. TEST_F(ServerTest, Delete) {
  5171. auto res = cli_.Delete("/delete");
  5172. ASSERT_TRUE(res);
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. EXPECT_EQ("DELETE", res->body);
  5175. }
  5176. TEST_F(ServerTest, DeleteContentReceiver) {
  5177. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5178. ASSERT_TRUE(res);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. EXPECT_EQ("content", res->body);
  5181. }
  5182. TEST_F(ServerTest, Options) {
  5183. auto res = cli_.Options("*");
  5184. ASSERT_TRUE(res);
  5185. EXPECT_EQ(StatusCode::OK_200, res->status);
  5186. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5187. EXPECT_TRUE(res->body.empty());
  5188. }
  5189. TEST_F(ServerTest, URL) {
  5190. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5191. ASSERT_TRUE(res);
  5192. EXPECT_EQ(StatusCode::OK_200, res->status);
  5193. }
  5194. TEST_F(ServerTest, ArrayParam) {
  5195. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5196. ASSERT_TRUE(res);
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. }
  5199. TEST_F(ServerTest, ArrayParamValues) {
  5200. auto res =
  5201. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5202. ASSERT_TRUE(res);
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. }
  5205. TEST_F(ServerTest, NoMultipleHeaders) {
  5206. Headers headers = {{"Content-Length", "5"}};
  5207. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5208. "text/plain");
  5209. ASSERT_TRUE(res);
  5210. EXPECT_EQ(StatusCode::OK_200, res->status);
  5211. }
  5212. TEST_F(ServerTest, PostContentReceiver) {
  5213. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5214. ASSERT_TRUE(res);
  5215. ASSERT_EQ(StatusCode::OK_200, res->status);
  5216. ASSERT_EQ("content", res->body);
  5217. }
  5218. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5219. UploadFormDataItems items = {
  5220. {"text1", "text default", "", ""},
  5221. {"text2", "aωb", "", ""},
  5222. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5223. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5224. {"file3", "", "", "application/octet-stream"},
  5225. };
  5226. auto res = cli_.Post("/content_receiver", items);
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(StatusCode::OK_200, res->status);
  5229. }
  5230. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5231. UploadFormDataItems items = {
  5232. {"text1", "text default", "", ""},
  5233. {"text2", "aωb", "", ""},
  5234. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5235. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5236. {"file3", "", "", "application/octet-stream"},
  5237. };
  5238. auto boundary = std::string("+++++");
  5239. std::string body;
  5240. for (const auto &item : items) {
  5241. body += "--" + boundary + "\r\n";
  5242. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5243. if (!item.filename.empty()) {
  5244. body += "; filename=\"" + item.filename + "\"";
  5245. }
  5246. body += "\r\n";
  5247. if (!item.content_type.empty()) {
  5248. body += "Content-Type: " + item.content_type + "\r\n";
  5249. }
  5250. body += "\r\n";
  5251. body += item.content + "\r\n";
  5252. }
  5253. body += "--" + boundary + "--\r\n";
  5254. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5255. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5256. ASSERT_TRUE(res);
  5257. EXPECT_EQ(StatusCode::OK_200, res->status);
  5258. }
  5259. TEST_F(ServerTest, PostContentReceiverGzip) {
  5260. cli_.set_compress(true);
  5261. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5262. ASSERT_TRUE(res);
  5263. ASSERT_EQ(StatusCode::OK_200, res->status);
  5264. ASSERT_EQ("content", res->body);
  5265. }
  5266. TEST_F(ServerTest, PutContentReceiver) {
  5267. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5268. ASSERT_TRUE(res);
  5269. ASSERT_EQ(StatusCode::OK_200, res->status);
  5270. ASSERT_EQ("content", res->body);
  5271. }
  5272. TEST_F(ServerTest, PatchContentReceiver) {
  5273. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5274. ASSERT_TRUE(res);
  5275. ASSERT_EQ(StatusCode::OK_200, res->status);
  5276. ASSERT_EQ("content", res->body);
  5277. }
  5278. template <typename ClientType>
  5279. void TestWithHeadersAndContentReceiver(
  5280. ClientType &cli,
  5281. std::function<Result(ClientType &, const std::string &, const Headers &,
  5282. const std::string &, const std::string &,
  5283. ContentReceiver, DownloadProgress)>
  5284. request_func) {
  5285. Headers headers;
  5286. headers.emplace("X-Custom-Header", "test-value");
  5287. std::string received_body;
  5288. auto res = request_func(
  5289. cli, "/content_receiver", headers, "content", "application/json",
  5290. [&](const char *data, size_t data_length) {
  5291. received_body.append(data, data_length);
  5292. return true;
  5293. },
  5294. nullptr);
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("content", received_body);
  5298. }
  5299. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5300. #ifdef CPPHTTPLIB_SSL_ENABLED
  5301. using ClientT = SSLClient;
  5302. #else
  5303. using ClientT = Client;
  5304. #endif
  5305. TestWithHeadersAndContentReceiver<ClientT>(
  5306. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5307. const std::string &body, const std::string &content_type,
  5308. ContentReceiver receiver, DownloadProgress progress) {
  5309. return cli.Post(path, headers, body, content_type, receiver, progress);
  5310. });
  5311. }
  5312. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5313. #ifdef CPPHTTPLIB_SSL_ENABLED
  5314. using ClientT = SSLClient;
  5315. #else
  5316. using ClientT = Client;
  5317. #endif
  5318. TestWithHeadersAndContentReceiver<ClientT>(
  5319. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5320. const std::string &body, const std::string &content_type,
  5321. ContentReceiver receiver, DownloadProgress progress) {
  5322. return cli.Put(path, headers, body, content_type, receiver, progress);
  5323. });
  5324. }
  5325. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5326. #ifdef CPPHTTPLIB_SSL_ENABLED
  5327. using ClientT = SSLClient;
  5328. #else
  5329. using ClientT = Client;
  5330. #endif
  5331. TestWithHeadersAndContentReceiver<ClientT>(
  5332. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5333. const std::string &body, const std::string &content_type,
  5334. ContentReceiver receiver, DownloadProgress progress) {
  5335. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5336. });
  5337. }
  5338. template <typename ClientType>
  5339. void TestWithHeadersAndContentReceiverWithProgress(
  5340. ClientType &cli,
  5341. std::function<Result(ClientType &, const std::string &, const Headers &,
  5342. const std::string &, const std::string &,
  5343. ContentReceiver, DownloadProgress)>
  5344. request_func) {
  5345. Headers headers;
  5346. headers.emplace("X-Test-Header", "progress-test");
  5347. std::string received_body;
  5348. auto progress_called = false;
  5349. auto res = request_func(
  5350. cli, "/content_receiver", headers, "content", "text/plain",
  5351. [&](const char *data, size_t data_length) {
  5352. received_body.append(data, data_length);
  5353. return true;
  5354. },
  5355. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5356. progress_called = true;
  5357. return true;
  5358. });
  5359. ASSERT_TRUE(res);
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. EXPECT_EQ("content", received_body);
  5362. EXPECT_TRUE(progress_called);
  5363. }
  5364. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5365. #ifdef CPPHTTPLIB_SSL_ENABLED
  5366. using ClientT = SSLClient;
  5367. #else
  5368. using ClientT = Client;
  5369. #endif
  5370. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5371. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5372. const std::string &body, const std::string &content_type,
  5373. ContentReceiver receiver, DownloadProgress progress) {
  5374. return cli.Post(path, headers, body, content_type, receiver, progress);
  5375. });
  5376. }
  5377. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5378. #ifdef CPPHTTPLIB_SSL_ENABLED
  5379. using ClientT = SSLClient;
  5380. #else
  5381. using ClientT = Client;
  5382. #endif
  5383. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5384. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5385. const std::string &body, const std::string &content_type,
  5386. ContentReceiver receiver, DownloadProgress progress) {
  5387. return cli.Put(path, headers, body, content_type, receiver, progress);
  5388. });
  5389. }
  5390. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5391. #ifdef CPPHTTPLIB_SSL_ENABLED
  5392. using ClientT = SSLClient;
  5393. #else
  5394. using ClientT = Client;
  5395. #endif
  5396. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5397. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5398. const std::string &body, const std::string &content_type,
  5399. ContentReceiver receiver, DownloadProgress progress) {
  5400. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5401. });
  5402. }
  5403. template <typename ClientType>
  5404. void TestWithHeadersAndContentReceiverError(
  5405. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5406. const Headers &, const std::string &,
  5407. const std::string &, ContentReceiver)>
  5408. request_func) {
  5409. Headers headers;
  5410. headers.emplace("X-Error-Test", "true");
  5411. std::string received_body;
  5412. auto receiver_failed = false;
  5413. auto res =
  5414. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5415. [&](const char *data, size_t data_length) {
  5416. received_body.append(data, data_length);
  5417. receiver_failed = true;
  5418. return false;
  5419. });
  5420. ASSERT_FALSE(res);
  5421. EXPECT_TRUE(receiver_failed);
  5422. }
  5423. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5424. #ifdef CPPHTTPLIB_SSL_ENABLED
  5425. using ClientT = SSLClient;
  5426. #else
  5427. using ClientT = Client;
  5428. #endif
  5429. TestWithHeadersAndContentReceiverError<ClientT>(
  5430. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5431. const std::string &body, const std::string &content_type,
  5432. ContentReceiver receiver) {
  5433. return cli.Post(path, headers, body, content_type, receiver);
  5434. });
  5435. }
  5436. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5437. #ifdef CPPHTTPLIB_SSL_ENABLED
  5438. using ClientT = SSLClient;
  5439. #else
  5440. using ClientT = Client;
  5441. #endif
  5442. TestWithHeadersAndContentReceiverError<ClientT>(
  5443. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5444. const std::string &body, const std::string &content_type,
  5445. ContentReceiver receiver) {
  5446. return cli.Put(path, headers, body, content_type, receiver);
  5447. });
  5448. }
  5449. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5450. #ifdef CPPHTTPLIB_SSL_ENABLED
  5451. using ClientT = SSLClient;
  5452. #else
  5453. using ClientT = Client;
  5454. #endif
  5455. TestWithHeadersAndContentReceiverError<ClientT>(
  5456. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5457. const std::string &body, const std::string &content_type,
  5458. ContentReceiver receiver) {
  5459. return cli.Patch(path, headers, body, content_type, receiver);
  5460. });
  5461. }
  5462. TEST_F(ServerTest, PostQueryStringAndBody) {
  5463. auto res =
  5464. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5465. ASSERT_TRUE(res);
  5466. ASSERT_EQ(StatusCode::OK_200, res->status);
  5467. }
  5468. TEST_F(ServerTest, HTTP2Magic) {
  5469. Request req;
  5470. req.method = "PRI";
  5471. req.path = "*";
  5472. req.body = "SM";
  5473. auto res = std::make_shared<Response>();
  5474. auto error = Error::Success;
  5475. auto ret = cli_.send(req, *res, error);
  5476. ASSERT_TRUE(ret);
  5477. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5478. }
  5479. TEST_F(ServerTest, KeepAlive) {
  5480. auto res = cli_.Get("/hi");
  5481. ASSERT_TRUE(res);
  5482. EXPECT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5484. EXPECT_EQ("Hello World!", res->body);
  5485. res = cli_.Get("/hi");
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5489. EXPECT_EQ("Hello World!", res->body);
  5490. res = cli_.Get("/hi");
  5491. ASSERT_TRUE(res);
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5494. EXPECT_EQ("Hello World!", res->body);
  5495. res = cli_.Get("/not-exist");
  5496. ASSERT_TRUE(res);
  5497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5498. res = cli_.Post("/empty", "", "text/plain");
  5499. ASSERT_TRUE(res);
  5500. EXPECT_EQ(StatusCode::OK_200, res->status);
  5501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("empty", res->body);
  5503. EXPECT_EQ("close", res->get_header_value("Connection"));
  5504. res = cli_.Post(
  5505. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5506. "text/plain");
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5510. EXPECT_EQ("empty", res->body);
  5511. cli_.set_keep_alive(false);
  5512. res = cli_.Get("/last-request");
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_EQ("close", res->get_header_value("Connection"));
  5516. }
  5517. TEST_F(ServerTest, TooManyRedirect) {
  5518. cli_.set_follow_location(true);
  5519. auto res = cli_.Get("/redirect/0");
  5520. ASSERT_TRUE(!res);
  5521. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5522. }
  5523. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5524. Request req;
  5525. req.method = "FOOBAR";
  5526. req.path = "/hi";
  5527. cli_.set_keep_alive(true);
  5528. auto res = cli_.send(req);
  5529. ASSERT_TRUE(res);
  5530. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5531. EXPECT_EQ("close", res->get_header_value("Connection"));
  5532. EXPECT_FALSE(cli_.is_socket_open());
  5533. }
  5534. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5535. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5536. TEST_F(ServerTest, Gzip) {
  5537. Headers headers;
  5538. headers.emplace("Accept-Encoding", "gzip, deflate");
  5539. auto res = cli_.Get("/compress", headers);
  5540. ASSERT_TRUE(res);
  5541. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5543. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5544. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5545. "7890123456789012345678901234567890",
  5546. res->body);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. }
  5549. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5550. Headers headers;
  5551. headers.emplace("Accept-Encoding", "gzip, deflate");
  5552. auto res = cli_.Get("/compress-with-charset", headers);
  5553. ASSERT_TRUE(res);
  5554. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5555. EXPECT_EQ("application/json; charset=utf-8",
  5556. res->get_header_value("Content-Type"));
  5557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5558. "7890123456789012345678901234567890",
  5559. res->body);
  5560. EXPECT_EQ(StatusCode::OK_200, res->status);
  5561. }
  5562. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5563. Headers headers;
  5564. headers.emplace("Accept-Encoding", "");
  5565. auto res = cli_.Get("/compress", headers);
  5566. ASSERT_TRUE(res);
  5567. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5569. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5571. "7890123456789012345678901234567890",
  5572. res->body);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. }
  5575. TEST_F(ServerTest, GzipWithContentReceiver) {
  5576. Headers headers;
  5577. headers.emplace("Accept-Encoding", "gzip, deflate");
  5578. std::string body;
  5579. auto res = cli_.Get("/compress", headers,
  5580. [&](const char *data, uint64_t data_length) {
  5581. EXPECT_EQ(100U, data_length);
  5582. body.append(data, data_length);
  5583. return true;
  5584. });
  5585. ASSERT_TRUE(res);
  5586. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5587. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5588. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5589. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5590. "7890123456789012345678901234567890",
  5591. body);
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. }
  5594. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5595. Headers headers;
  5596. headers.emplace("Accept-Encoding", "gzip, deflate");
  5597. cli_.set_decompress(false);
  5598. auto res = cli_.Get("/compress", headers);
  5599. ASSERT_TRUE(res);
  5600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ(33U, res->body.size());
  5604. EXPECT_EQ(StatusCode::OK_200, res->status);
  5605. }
  5606. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5607. Headers headers;
  5608. headers.emplace("Accept-Encoding", "");
  5609. std::string body;
  5610. auto res = cli_.Get("/compress", headers,
  5611. [&](const char *data, uint64_t data_length) {
  5612. EXPECT_EQ(100U, data_length);
  5613. body.append(data, data_length);
  5614. return true;
  5615. });
  5616. ASSERT_TRUE(res);
  5617. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5618. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5619. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5620. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5621. "7890123456789012345678901234567890",
  5622. body);
  5623. EXPECT_EQ(StatusCode::OK_200, res->status);
  5624. }
  5625. TEST_F(ServerTest, NoGzip) {
  5626. Headers headers;
  5627. headers.emplace("Accept-Encoding", "gzip, deflate");
  5628. auto res = cli_.Get("/nocompress", headers);
  5629. ASSERT_TRUE(res);
  5630. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5631. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5634. "7890123456789012345678901234567890",
  5635. res->body);
  5636. EXPECT_EQ(StatusCode::OK_200, res->status);
  5637. }
  5638. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5639. Headers headers;
  5640. headers.emplace("Accept-Encoding", "gzip, deflate");
  5641. std::string body;
  5642. auto res = cli_.Get("/nocompress", headers,
  5643. [&](const char *data, uint64_t data_length) {
  5644. EXPECT_EQ(100U, data_length);
  5645. body.append(data, data_length);
  5646. return true;
  5647. });
  5648. ASSERT_TRUE(res);
  5649. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5650. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5651. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5652. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5653. "7890123456789012345678901234567890",
  5654. body);
  5655. EXPECT_EQ(StatusCode::OK_200, res->status);
  5656. }
  5657. TEST_F(ServerTest, MultipartFormDataGzip) {
  5658. UploadFormDataItems items = {
  5659. {"key1", "test", "", ""},
  5660. {"key2", "--abcdefg123", "", ""},
  5661. };
  5662. cli_.set_compress(true);
  5663. auto res = cli_.Post("/compress-multipart", items);
  5664. ASSERT_TRUE(res);
  5665. EXPECT_EQ(StatusCode::OK_200, res->status);
  5666. }
  5667. #endif
  5668. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5669. TEST_F(ServerTest, Brotli) {
  5670. Headers headers;
  5671. headers.emplace("Accept-Encoding", "br");
  5672. auto res = cli_.Get("/compress", headers);
  5673. ASSERT_TRUE(res);
  5674. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5675. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5676. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5677. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5678. "7890123456789012345678901234567890",
  5679. res->body);
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. }
  5682. #endif
  5683. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5684. TEST_F(ServerTest, Zstd) {
  5685. Headers headers;
  5686. headers.emplace("Accept-Encoding", "zstd");
  5687. auto res = cli_.Get("/compress", headers);
  5688. ASSERT_TRUE(res);
  5689. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5690. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5691. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5692. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5693. "7890123456789012345678901234567890",
  5694. res->body);
  5695. EXPECT_EQ(StatusCode::OK_200, res->status);
  5696. }
  5697. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5698. Headers headers;
  5699. headers.emplace("Accept-Encoding", "");
  5700. auto res = cli_.Get("/compress", headers);
  5701. ASSERT_TRUE(res);
  5702. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5704. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5705. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5706. "7890123456789012345678901234567890",
  5707. res->body);
  5708. EXPECT_EQ(StatusCode::OK_200, res->status);
  5709. }
  5710. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5711. Headers headers;
  5712. headers.emplace("Accept-Encoding", "zstd");
  5713. std::string body;
  5714. auto res = cli_.Get("/compress", headers,
  5715. [&](const char *data, uint64_t data_length) {
  5716. EXPECT_EQ(100U, data_length);
  5717. body.append(data, data_length);
  5718. return true;
  5719. });
  5720. ASSERT_TRUE(res);
  5721. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5722. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5723. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5724. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5725. "7890123456789012345678901234567890",
  5726. body);
  5727. EXPECT_EQ(StatusCode::OK_200, res->status);
  5728. }
  5729. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5730. Headers headers;
  5731. headers.emplace("Accept-Encoding", "zstd");
  5732. cli_.set_decompress(false);
  5733. auto res = cli_.Get("/compress", headers);
  5734. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5735. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5736. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5737. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5738. ASSERT_TRUE(res);
  5739. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5740. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5741. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5742. EXPECT_EQ(StatusCode::OK_200, res->status);
  5743. ASSERT_EQ(26U, res->body.size());
  5744. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5745. 0);
  5746. }
  5747. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5748. Headers headers;
  5749. headers.emplace("Accept-Encoding", "");
  5750. std::string body;
  5751. auto res = cli_.Get("/compress", headers,
  5752. [&](const char *data, uint64_t data_length) {
  5753. EXPECT_EQ(100U, data_length);
  5754. body.append(data, data_length);
  5755. return true;
  5756. });
  5757. ASSERT_TRUE(res);
  5758. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5760. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5761. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5762. "7890123456789012345678901234567890",
  5763. body);
  5764. EXPECT_EQ(StatusCode::OK_200, res->status);
  5765. }
  5766. TEST_F(ServerTest, NoZstd) {
  5767. Headers headers;
  5768. headers.emplace("Accept-Encoding", "zstd");
  5769. auto res = cli_.Get("/nocompress", headers);
  5770. ASSERT_TRUE(res);
  5771. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5772. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5773. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5774. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5775. "7890123456789012345678901234567890",
  5776. res->body);
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. }
  5779. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5780. Headers headers;
  5781. headers.emplace("Accept-Encoding", "zstd");
  5782. std::string body;
  5783. auto res = cli_.Get("/nocompress", headers,
  5784. [&](const char *data, uint64_t data_length) {
  5785. EXPECT_EQ(100U, data_length);
  5786. body.append(data, data_length);
  5787. return true;
  5788. });
  5789. ASSERT_TRUE(res);
  5790. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5791. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5792. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5793. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5794. "7890123456789012345678901234567890",
  5795. body);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. }
  5798. // TODO: How to enable zstd ??
  5799. TEST_F(ServerTest, MultipartFormDataZstd) {
  5800. UploadFormDataItems items = {
  5801. {"key1", "test", "", ""},
  5802. {"key2", "--abcdefg123", "", ""},
  5803. };
  5804. Headers headers;
  5805. headers.emplace("Accept-Encoding", "zstd");
  5806. cli_.set_compress(true);
  5807. auto res = cli_.Post("/compress-multipart", headers, items);
  5808. ASSERT_TRUE(res);
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. }
  5811. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5812. Headers headers;
  5813. headers.emplace("Accept-Encoding", "zstd");
  5814. cli_.set_compress(true);
  5815. auto res = cli_.Put(
  5816. "/put", headers, 3,
  5817. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5818. sink.os << "PUT";
  5819. return true;
  5820. },
  5821. "text/plain");
  5822. ASSERT_TRUE(res);
  5823. EXPECT_EQ(StatusCode::OK_200, res->status);
  5824. EXPECT_EQ("PUT", res->body);
  5825. }
  5826. // Pre-compression logging tests
  5827. TEST_F(ServerTest, PreCompressionLogging) {
  5828. // Test data for compression (matches the actual /compress endpoint content)
  5829. const std::string test_content =
  5830. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5831. "3456789012345678901234567890";
  5832. // Variables to capture logging data
  5833. std::string pre_compression_body;
  5834. std::string pre_compression_content_type;
  5835. std::string pre_compression_content_encoding;
  5836. std::string post_compression_body;
  5837. std::string post_compression_content_type;
  5838. std::string post_compression_content_encoding;
  5839. // Set up pre-compression logger
  5840. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5841. const Response &res) {
  5842. pre_compression_body = res.body;
  5843. pre_compression_content_type = res.get_header_value("Content-Type");
  5844. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5845. });
  5846. // Set up post-compression logger
  5847. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5848. post_compression_body = res.body;
  5849. post_compression_content_type = res.get_header_value("Content-Type");
  5850. post_compression_content_encoding =
  5851. res.get_header_value("Content-Encoding");
  5852. });
  5853. // Test with gzip compression
  5854. Headers headers;
  5855. headers.emplace("Accept-Encoding", "gzip");
  5856. auto res = cli_.Get("/compress", headers);
  5857. // Verify response was compressed
  5858. ASSERT_TRUE(res);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5861. // Verify pre-compression logger captured uncompressed content
  5862. EXPECT_EQ(test_content, pre_compression_body);
  5863. EXPECT_EQ("text/plain", pre_compression_content_type);
  5864. EXPECT_TRUE(pre_compression_content_encoding
  5865. .empty()); // No encoding header before compression
  5866. // Verify post-compression logger captured compressed content
  5867. EXPECT_NE(test_content,
  5868. post_compression_body); // Should be different after compression
  5869. EXPECT_EQ("text/plain", post_compression_content_type);
  5870. EXPECT_EQ("gzip", post_compression_content_encoding);
  5871. // Verify compressed content is smaller
  5872. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5873. }
  5874. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5875. const std::string test_content =
  5876. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5877. "3456789012345678901234567890";
  5878. std::string pre_compression_body;
  5879. std::string post_compression_body;
  5880. svr_.set_pre_compression_logger(
  5881. [&](const Request & /*req*/, const Response &res) {
  5882. pre_compression_body = res.body;
  5883. });
  5884. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5885. post_compression_body = res.body;
  5886. });
  5887. Headers headers;
  5888. headers.emplace("Accept-Encoding", "br");
  5889. auto res = cli_.Get("/compress", headers);
  5890. ASSERT_TRUE(res);
  5891. EXPECT_EQ(StatusCode::OK_200, res->status);
  5892. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5893. // Verify pre-compression content is uncompressed
  5894. EXPECT_EQ(test_content, pre_compression_body);
  5895. // Verify post-compression content is compressed
  5896. EXPECT_NE(test_content, post_compression_body);
  5897. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5898. }
  5899. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5900. const std::string test_content =
  5901. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5902. "3456789012345678901234567890";
  5903. std::string pre_compression_body;
  5904. std::string post_compression_body;
  5905. svr_.set_pre_compression_logger(
  5906. [&](const Request & /*req*/, const Response &res) {
  5907. pre_compression_body = res.body;
  5908. });
  5909. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5910. post_compression_body = res.body;
  5911. });
  5912. // Request without compression (use /nocompress endpoint)
  5913. Headers headers;
  5914. auto res = cli_.Get("/nocompress", headers);
  5915. ASSERT_TRUE(res);
  5916. EXPECT_EQ(StatusCode::OK_200, res->status);
  5917. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5918. // Pre-compression logger should not be called when no compression is applied
  5919. EXPECT_TRUE(
  5920. pre_compression_body.empty()); // Pre-compression logger not called
  5921. EXPECT_EQ(
  5922. test_content,
  5923. post_compression_body); // Post-compression logger captures final content
  5924. }
  5925. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5926. const std::string test_content =
  5927. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5928. "3456789012345678901234567890";
  5929. std::string pre_compression_body;
  5930. bool pre_logger_called = false;
  5931. // Set only pre-compression logger
  5932. svr_.set_pre_compression_logger(
  5933. [&](const Request & /*req*/, const Response &res) {
  5934. pre_compression_body = res.body;
  5935. pre_logger_called = true;
  5936. });
  5937. Headers headers;
  5938. headers.emplace("Accept-Encoding", "gzip");
  5939. auto res = cli_.Get("/compress", headers);
  5940. ASSERT_TRUE(res);
  5941. EXPECT_EQ(StatusCode::OK_200, res->status);
  5942. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5943. // Verify pre-compression logger was called
  5944. EXPECT_TRUE(pre_logger_called);
  5945. EXPECT_EQ(test_content, pre_compression_body);
  5946. }
  5947. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5948. {
  5949. // Test with Expect: 100-continue header - success case
  5950. // Server returns 100 Continue, client sends body, server returns 200 OK
  5951. Request req;
  5952. req.method = "POST";
  5953. req.path = "/post-large";
  5954. req.set_header("Expect", "100-continue");
  5955. req.body = LARGE_DATA;
  5956. Response res;
  5957. auto error = Error::Success;
  5958. cli_.set_keep_alive(true);
  5959. auto ret = cli_.send(req, res, error);
  5960. EXPECT_TRUE(ret);
  5961. EXPECT_EQ(StatusCode::OK_200, res.status);
  5962. EXPECT_EQ(LARGE_DATA, res.body);
  5963. }
  5964. {
  5965. // Test with Expect: 100-continue header - error case
  5966. // Client should not send the body when server returns an error
  5967. Request req;
  5968. req.method = "POST";
  5969. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5970. req.set_header("Expect", "100-continue");
  5971. req.body = LARGE_DATA;
  5972. Response res;
  5973. auto error = Error::Success;
  5974. auto start = std::chrono::high_resolution_clock::now();
  5975. cli_.set_keep_alive(true);
  5976. auto ret = cli_.send(req, res, error);
  5977. auto end = std::chrono::high_resolution_clock::now();
  5978. auto elapsed =
  5979. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5980. .count();
  5981. // With Expect: 100-continue, request completes successfully but with error
  5982. EXPECT_TRUE(ret);
  5983. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5984. EXPECT_EQ("close", res.get_header_value("Connection"));
  5985. EXPECT_FALSE(cli_.is_socket_open());
  5986. EXPECT_LE(elapsed, 2000);
  5987. }
  5988. {
  5989. // Send an extra GET request to ensure error recovery without hanging
  5990. Request req;
  5991. req.method = "GET";
  5992. req.path = "/hi";
  5993. auto start = std::chrono::high_resolution_clock::now();
  5994. auto res = cli_.send(req);
  5995. auto end = std::chrono::high_resolution_clock::now();
  5996. auto elapsed =
  5997. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5998. .count();
  5999. ASSERT_TRUE(res);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. EXPECT_EQ("Hello World!", res->body);
  6002. EXPECT_LE(elapsed, 500);
  6003. }
  6004. }
  6005. TEST(ZstdDecompressor, ChunkedDecompression) {
  6006. std::string data;
  6007. for (size_t i = 0; i < 32 * 1024; ++i) {
  6008. data.push_back(static_cast<char>('a' + i % 26));
  6009. }
  6010. std::string compressed_data;
  6011. {
  6012. httplib::detail::zstd_compressor compressor;
  6013. bool result = compressor.compress(
  6014. data.data(), data.size(),
  6015. /*last=*/true,
  6016. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6017. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6018. compressed_data_size);
  6019. return true;
  6020. });
  6021. ASSERT_TRUE(result);
  6022. }
  6023. std::string decompressed_data;
  6024. {
  6025. httplib::detail::zstd_decompressor decompressor;
  6026. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6027. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6028. size_t chunk_size = 130;
  6029. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6030. chunk_begin += chunk_size) {
  6031. size_t current_chunk_size =
  6032. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6033. bool result = decompressor.decompress(
  6034. compressed_data.data() + chunk_begin, current_chunk_size,
  6035. [&](const char *decompressed_data_chunk,
  6036. size_t decompressed_data_chunk_size) {
  6037. decompressed_data.insert(decompressed_data.size(),
  6038. decompressed_data_chunk,
  6039. decompressed_data_chunk_size);
  6040. return true;
  6041. });
  6042. ASSERT_TRUE(result);
  6043. }
  6044. }
  6045. ASSERT_EQ(data, decompressed_data);
  6046. }
  6047. TEST(ZstdDecompressor, Decompress) {
  6048. std::string original_text = "Compressed with ZSTD";
  6049. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6050. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6051. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6052. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6053. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6054. std::string decompressed_data;
  6055. {
  6056. httplib::detail::zstd_decompressor decompressor;
  6057. bool result = decompressor.decompress(
  6058. compressed_data.data(), compressed_data.size(),
  6059. [&](const char *decompressed_data_chunk,
  6060. size_t decompressed_data_chunk_size) {
  6061. decompressed_data.insert(decompressed_data.size(),
  6062. decompressed_data_chunk,
  6063. decompressed_data_chunk_size);
  6064. return true;
  6065. });
  6066. ASSERT_TRUE(result);
  6067. }
  6068. ASSERT_EQ(original_text, decompressed_data);
  6069. }
  6070. #endif
  6071. // Sends a raw request to a server listening at HOST:PORT.
  6072. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6073. std::string *resp = nullptr) {
  6074. auto error = Error::Success;
  6075. auto client_sock = detail::create_client_socket(
  6076. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6077. /*connection_timeout_sec=*/5, 0,
  6078. /*read_timeout_sec=*/5, 0,
  6079. /*write_timeout_sec=*/5, 0, std::string(), error);
  6080. if (client_sock == INVALID_SOCKET) { return false; }
  6081. auto ret = detail::process_client_socket(
  6082. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6083. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6084. if (req.size() !=
  6085. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6086. return false;
  6087. }
  6088. char buf[512];
  6089. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6090. while (line_reader.getline()) {
  6091. if (resp) { *resp += line_reader.ptr(); }
  6092. }
  6093. return true;
  6094. });
  6095. detail::close_socket(client_sock);
  6096. return ret;
  6097. }
  6098. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6099. Server svr;
  6100. std::string header_value;
  6101. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6102. header_value = req.get_header_value("foo");
  6103. res.set_content("ok", "text/plain");
  6104. });
  6105. thread t = thread([&] { svr.listen(HOST, PORT); });
  6106. auto se = detail::scope_exit([&] {
  6107. svr.stop();
  6108. t.join();
  6109. ASSERT_FALSE(svr.is_running());
  6110. });
  6111. svr.wait_until_ready();
  6112. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6113. // like characters are not treated the same - use vertical tab and escape.
  6114. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6115. "foo: \t \v bar \x1B\t \r\n"
  6116. "Connection: close\r\n"
  6117. "\r\n";
  6118. std::string res;
  6119. ASSERT_TRUE(send_request(5, req, &res));
  6120. EXPECT_EQ(header_value, "");
  6121. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6122. }
  6123. // Sends a raw request and verifies that there isn't a crash or exception.
  6124. static void test_raw_request(const std::string &req,
  6125. std::string *out = nullptr) {
  6126. Server svr;
  6127. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6128. res.set_content("ok", "text/plain");
  6129. });
  6130. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6131. res.set_content("ok", "text/plain");
  6132. });
  6133. svr.Get("/header_field_value_check",
  6134. [&](const Request & /*req*/, Response &res) {
  6135. res.set_content("ok", "text/plain");
  6136. });
  6137. // Server read timeout must be longer than the client read timeout for the
  6138. // bug to reproduce, probably to force the server to process a request
  6139. // without a trailing blank line.
  6140. const time_t client_read_timeout_sec = 1;
  6141. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6142. bool listen_thread_ok = false;
  6143. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6144. auto se = detail::scope_exit([&] {
  6145. svr.stop();
  6146. t.join();
  6147. ASSERT_FALSE(svr.is_running());
  6148. EXPECT_TRUE(listen_thread_ok);
  6149. });
  6150. svr.wait_until_ready();
  6151. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6152. }
  6153. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6154. // A certain header line causes an exception if the header property is parsed
  6155. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6156. test_raw_request(
  6157. "GET /hi HTTP/1.1\r\n"
  6158. " : "
  6159. " "
  6160. " ");
  6161. }
  6162. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6163. // A certain header line causes an exception if the header property *name* is
  6164. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6165. // greedy matcher and requires backtracking when there are a lot of ":"
  6166. // characters.
  6167. // This occurs with libc++ but not libstdc++.
  6168. test_raw_request(
  6169. "GET /hi HTTP/1.1\r\n"
  6170. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6171. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6172. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6173. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6174. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6175. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6176. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6177. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6178. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6179. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6180. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6181. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6182. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6183. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6184. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6185. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6186. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6187. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6188. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6189. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6190. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6191. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6192. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6193. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6194. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6195. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6196. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6197. "&&&%%%");
  6198. }
  6199. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6200. // Make sure this doesn't crash the server.
  6201. // In a previous version of the header line regex, the "\r" rendered the line
  6202. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6203. // a new position where the leading white space ended and the field value
  6204. // began.
  6205. // The crash occurs with libc++ but not libstdc++.
  6206. test_raw_request("GET /hi HTTP/1.1\r\n"
  6207. "a:" +
  6208. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6209. "\r\n"
  6210. "\r\n");
  6211. }
  6212. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6213. std::string out;
  6214. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6215. "Content-Type: text/plain\r\n"
  6216. "Transfer-Encoding: chunked\r\n"
  6217. "\r\n"
  6218. "nothex\r\n",
  6219. &out);
  6220. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6221. }
  6222. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6223. std::string out;
  6224. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6225. "Content-Type: text/plain\r\n"
  6226. "Transfer-Encoding: chunked\r\n"
  6227. "\r\n"
  6228. "3\r\n"
  6229. "xyz\r\n"
  6230. "NaN\r\n",
  6231. &out);
  6232. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6233. }
  6234. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6235. std::string out;
  6236. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6237. "Content-Type: text/plain\r\n"
  6238. "Transfer-Encoding: chunked\r\n"
  6239. "\r\n"
  6240. // Length is too large for 64 bits.
  6241. "1ffffffffffffffff\r\n"
  6242. "xyz\r\n",
  6243. &out);
  6244. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6245. }
  6246. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6247. test_raw_request("GET /hi HTTP/1.1\r\n"
  6248. "Content-Type: text/plain\r\n\r");
  6249. }
  6250. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6251. std::string out;
  6252. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6253. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6254. }
  6255. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6256. Server svr;
  6257. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6258. EXPECT_TRUE(!req.remote_addr.empty());
  6259. });
  6260. thread t = thread([&] { svr.listen(HOST, PORT); });
  6261. auto se = detail::scope_exit([&] {
  6262. svr.stop();
  6263. t.join();
  6264. ASSERT_FALSE(svr.is_running());
  6265. });
  6266. svr.wait_until_ready();
  6267. // Send an invalid request line to trigger Bad Request
  6268. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6269. std::string out;
  6270. ASSERT_TRUE(send_request(5, bad_req, &out));
  6271. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6272. }
  6273. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6274. std::string out;
  6275. std::string request(
  6276. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6277. test_raw_request(request, &out);
  6278. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6279. }
  6280. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6281. std::string out;
  6282. std::string request(
  6283. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6284. test_raw_request(request, &out);
  6285. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6286. }
  6287. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6288. std::string out;
  6289. std::string request(
  6290. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6291. test_raw_request(request, &out);
  6292. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6293. }
  6294. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6295. std::string out;
  6296. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6297. "Test: \r\n\r\n",
  6298. &out);
  6299. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6300. }
  6301. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6302. Server svr;
  6303. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6304. res.set_header("Cache-Control", "no-cache");
  6305. res.set_chunked_content_provider(
  6306. "text/event-stream", [](size_t offset, DataSink &sink) {
  6307. std::string s = "data:";
  6308. s += std::to_string(offset);
  6309. s += "\n\n";
  6310. auto ret = sink.write(s.data(), s.size());
  6311. EXPECT_TRUE(ret);
  6312. std::this_thread::sleep_for(std::chrono::seconds(1));
  6313. return true;
  6314. });
  6315. });
  6316. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6317. svr.wait_until_ready();
  6318. Client client(HOST, PORT);
  6319. const Headers headers = {{"Accept", "text/event-stream"}};
  6320. auto get_thread = std::thread([&client, &headers]() {
  6321. auto res = client.Get(
  6322. "/events", headers,
  6323. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6324. });
  6325. auto se = detail::scope_exit([&] {
  6326. svr.stop();
  6327. get_thread.join();
  6328. listen_thread.join();
  6329. ASSERT_FALSE(svr.is_running());
  6330. });
  6331. // Give GET time to get a few messages.
  6332. std::this_thread::sleep_for(std::chrono::seconds(2));
  6333. }
  6334. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6335. httplib::Server svr;
  6336. svr.Post("/hi",
  6337. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6338. res.status = StatusCode::OK_200;
  6339. });
  6340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6341. svr.wait_until_ready();
  6342. Client cli(HOST, PORT);
  6343. auto res = cli.Post("/hi", "data", "text/plain");
  6344. ASSERT_TRUE(res);
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. svr.stop();
  6347. thread.join();
  6348. ASSERT_FALSE(svr.is_running());
  6349. res = cli.Post("/hi", "data", "text/plain");
  6350. ASSERT_FALSE(res);
  6351. }
  6352. TEST(ServerStopTest, ListenFailure) {
  6353. Server svr;
  6354. auto t = thread([&]() {
  6355. auto ret = svr.listen("????", PORT);
  6356. EXPECT_FALSE(ret);
  6357. });
  6358. svr.wait_until_ready();
  6359. svr.stop();
  6360. t.join();
  6361. }
  6362. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6363. TEST(ServerStopTest, Decommision) {
  6364. Server svr;
  6365. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6366. for (int i = 0; i < 4; i++) {
  6367. auto is_even = !(i % 2);
  6368. std::thread t{[&] {
  6369. try {
  6370. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6371. if (is_even) {
  6372. throw std::runtime_error("Some thing that happens to go wrong.");
  6373. }
  6374. svr.listen(HOST, PORT);
  6375. } catch (...) { svr.decommission(); }
  6376. }};
  6377. svr.wait_until_ready();
  6378. // Server is up
  6379. {
  6380. Client cli(HOST, PORT);
  6381. auto res = cli.Get("/hi");
  6382. if (is_even) {
  6383. EXPECT_FALSE(res);
  6384. } else {
  6385. EXPECT_TRUE(res);
  6386. EXPECT_EQ("hi...", res->body);
  6387. }
  6388. }
  6389. svr.stop();
  6390. t.join();
  6391. // Server is down...
  6392. {
  6393. Client cli(HOST, PORT);
  6394. auto res = cli.Get("/hi");
  6395. EXPECT_FALSE(res);
  6396. }
  6397. }
  6398. }
  6399. #endif
  6400. // Helper function for string body upload progress tests
  6401. template <typename SetupHandler, typename ClientCall>
  6402. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6403. ClientCall &&client_call,
  6404. const string &body) {
  6405. Server svr;
  6406. setup_handler(svr);
  6407. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6408. auto se = detail::scope_exit([&] {
  6409. svr.stop();
  6410. t.join();
  6411. });
  6412. svr.wait_until_ready();
  6413. Client cli(HOST, PORT);
  6414. vector<uint64_t> progress_values;
  6415. bool progress_called = false;
  6416. auto res =
  6417. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6418. progress_values.push_back(current);
  6419. progress_called = true;
  6420. return true;
  6421. });
  6422. ASSERT_TRUE(res);
  6423. EXPECT_EQ(200, res->status);
  6424. EXPECT_TRUE(progress_called);
  6425. }
  6426. TEST(UploadProgressTest, PostStringBodyBasic) {
  6427. TestStringBodyUploadProgress(
  6428. [](Server &svr) {
  6429. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6430. res.set_content("received", "text/plain");
  6431. });
  6432. },
  6433. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6434. return cli.Post("/test", body, "text/plain", progress_callback);
  6435. },
  6436. "test data for upload progress");
  6437. }
  6438. TEST(UploadProgressTest, PutStringBodyBasic) {
  6439. TestStringBodyUploadProgress(
  6440. [](Server &svr) {
  6441. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6442. res.set_content("put received", "text/plain");
  6443. });
  6444. },
  6445. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6446. return cli.Put("/test", body, "text/plain", progress_callback);
  6447. },
  6448. "put test data for upload progress");
  6449. }
  6450. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6451. TestStringBodyUploadProgress(
  6452. [](Server &svr) {
  6453. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6454. res.set_content("patch received", "text/plain");
  6455. });
  6456. },
  6457. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6458. return cli.Patch("/test", body, "text/plain", progress_callback);
  6459. },
  6460. "patch test data for upload progress");
  6461. }
  6462. // Helper function for content provider upload progress tests
  6463. template <typename SetupHandler, typename ClientCall>
  6464. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6465. ClientCall &&client_call) {
  6466. Server svr;
  6467. setup_handler(svr);
  6468. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6469. auto se = detail::scope_exit([&] {
  6470. svr.stop();
  6471. t.join();
  6472. });
  6473. svr.wait_until_ready();
  6474. Client cli(HOST, PORT);
  6475. vector<uint64_t> progress_values;
  6476. auto res =
  6477. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6478. progress_values.push_back(current);
  6479. return true;
  6480. });
  6481. ASSERT_TRUE(res);
  6482. EXPECT_EQ(200, res->status);
  6483. EXPECT_FALSE(progress_values.empty());
  6484. }
  6485. TEST(UploadProgressTest, PostContentProviderProgress) {
  6486. TestContentProviderUploadProgress(
  6487. [](Server &svr) {
  6488. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6489. res.set_content("provider received", "text/plain");
  6490. });
  6491. },
  6492. [](Client &cli, UploadProgress progress_callback) {
  6493. return cli.Post(
  6494. "/test", 10,
  6495. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6496. sink.os << "test data";
  6497. return true;
  6498. },
  6499. "text/plain", progress_callback);
  6500. });
  6501. }
  6502. // Helper function for multipart upload progress tests
  6503. template <typename SetupHandler, typename ClientCall>
  6504. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6505. ClientCall &&client_call,
  6506. const string &endpoint) {
  6507. Server svr;
  6508. setup_handler(svr);
  6509. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6510. auto se = detail::scope_exit([&] {
  6511. svr.stop();
  6512. t.join();
  6513. });
  6514. svr.wait_until_ready();
  6515. Client cli(HOST, PORT);
  6516. vector<uint64_t> progress_values;
  6517. UploadFormDataItems items = {
  6518. {"field1", "value1", "", ""},
  6519. {"field2", "longer value for progress tracking test", "", ""},
  6520. {"file1", "file content data for upload progress", "test.txt",
  6521. "text/plain"}};
  6522. auto res = client_call(cli, endpoint, items,
  6523. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6524. progress_values.push_back(current);
  6525. return true;
  6526. });
  6527. ASSERT_TRUE(res);
  6528. EXPECT_EQ(200, res->status);
  6529. EXPECT_FALSE(progress_values.empty());
  6530. }
  6531. TEST(UploadProgressTest, PostMultipartProgress) {
  6532. TestMultipartUploadProgress(
  6533. [](Server &svr) {
  6534. svr.Post("/multipart", [](const Request &req, Response &res) {
  6535. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6536. res.set_content("multipart received", "text/plain");
  6537. });
  6538. },
  6539. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6540. UploadProgress progress_callback) {
  6541. return cli.Post(endpoint, items, progress_callback);
  6542. },
  6543. "/multipart");
  6544. }
  6545. // Helper function for basic download progress tests
  6546. template <typename SetupHandler, typename ClientCall>
  6547. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6548. ClientCall &&client_call, const string &endpoint,
  6549. size_t expected_content_size) {
  6550. Server svr;
  6551. setup_handler(svr);
  6552. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6553. auto se = detail::scope_exit([&] {
  6554. svr.stop();
  6555. t.join();
  6556. });
  6557. svr.wait_until_ready();
  6558. Client cli(HOST, PORT);
  6559. vector<uint64_t> progress_values;
  6560. auto res = client_call(cli, endpoint,
  6561. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6562. progress_values.push_back(current);
  6563. return true;
  6564. });
  6565. ASSERT_TRUE(res);
  6566. EXPECT_EQ(200, res->status);
  6567. EXPECT_FALSE(progress_values.empty());
  6568. EXPECT_EQ(expected_content_size, res->body.size());
  6569. }
  6570. TEST(DownloadProgressTest, GetBasic) {
  6571. TestBasicDownloadProgress(
  6572. [](Server &svr) {
  6573. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6574. string content(1000, 'D');
  6575. res.set_content(content, "text/plain");
  6576. });
  6577. },
  6578. [](Client &cli, const string &endpoint,
  6579. DownloadProgress progress_callback) {
  6580. return cli.Get(endpoint, progress_callback);
  6581. },
  6582. "/download", 1000u);
  6583. }
  6584. // Helper function for content receiver download progress tests
  6585. template <typename SetupHandler, typename ClientCall>
  6586. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6587. ClientCall &&client_call,
  6588. const string &endpoint,
  6589. size_t expected_content_size) {
  6590. Server svr;
  6591. setup_handler(svr);
  6592. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6593. auto se = detail::scope_exit([&] {
  6594. svr.stop();
  6595. t.join();
  6596. });
  6597. svr.wait_until_ready();
  6598. Client cli(HOST, PORT);
  6599. vector<uint64_t> progress_values;
  6600. string received_body;
  6601. auto res = client_call(
  6602. cli, endpoint,
  6603. [&](const char *data, size_t data_length) -> bool {
  6604. received_body.append(data, data_length);
  6605. return true;
  6606. },
  6607. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6608. progress_values.push_back(current);
  6609. return true;
  6610. });
  6611. ASSERT_TRUE(res);
  6612. EXPECT_EQ(200, res->status);
  6613. EXPECT_FALSE(progress_values.empty());
  6614. EXPECT_EQ(expected_content_size, received_body.size());
  6615. EXPECT_TRUE(res->body.empty());
  6616. }
  6617. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6618. TestContentReceiverDownloadProgress(
  6619. [](Server &svr) {
  6620. svr.Get("/download-receiver",
  6621. [](const Request & /*req*/, Response &res) {
  6622. string content(2000, 'R');
  6623. res.set_content(content, "text/plain");
  6624. });
  6625. },
  6626. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6627. DownloadProgress progress_callback) {
  6628. return cli.Get(endpoint, content_receiver, progress_callback);
  6629. },
  6630. "/download-receiver", 2000u);
  6631. }
  6632. TEST(StreamingTest, NoContentLengthStreaming) {
  6633. Server svr;
  6634. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6635. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6636. if (offset < 6) {
  6637. sink.os << (offset < 3 ? "a" : "b");
  6638. } else {
  6639. sink.done();
  6640. }
  6641. return true;
  6642. });
  6643. });
  6644. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6645. auto listen_se = detail::scope_exit([&] {
  6646. svr.stop();
  6647. listen_thread.join();
  6648. ASSERT_FALSE(svr.is_running());
  6649. });
  6650. svr.wait_until_ready();
  6651. Client client(HOST, PORT);
  6652. auto get_thread = std::thread([&client]() {
  6653. std::string s;
  6654. auto res =
  6655. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6656. s += std::string(data, len);
  6657. return true;
  6658. });
  6659. ASSERT_TRUE(res);
  6660. EXPECT_EQ(StatusCode::OK_200, res->status);
  6661. EXPECT_EQ("aaabbb", s);
  6662. });
  6663. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6664. // Give GET time to get a few messages.
  6665. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6666. }
  6667. TEST(MountTest, Unmount) {
  6668. Server svr;
  6669. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6670. auto se = detail::scope_exit([&] {
  6671. svr.stop();
  6672. listen_thread.join();
  6673. ASSERT_FALSE(svr.is_running());
  6674. });
  6675. svr.wait_until_ready();
  6676. Client cli("localhost", PORT);
  6677. svr.set_mount_point("/mount2", "./www2");
  6678. auto res = cli.Get("/");
  6679. ASSERT_TRUE(res);
  6680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6681. res = cli.Get("/mount2/dir/test.html");
  6682. ASSERT_TRUE(res);
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. svr.set_mount_point("/", "./www");
  6685. res = cli.Get("/dir/");
  6686. ASSERT_TRUE(res);
  6687. EXPECT_EQ(StatusCode::OK_200, res->status);
  6688. svr.remove_mount_point("/");
  6689. res = cli.Get("/dir/");
  6690. ASSERT_TRUE(res);
  6691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6692. svr.remove_mount_point("/mount2");
  6693. res = cli.Get("/mount2/dir/test.html");
  6694. ASSERT_TRUE(res);
  6695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6696. }
  6697. TEST(MountTest, Redicect) {
  6698. Server svr;
  6699. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6700. auto se = detail::scope_exit([&] {
  6701. svr.stop();
  6702. listen_thread.join();
  6703. ASSERT_FALSE(svr.is_running());
  6704. });
  6705. svr.set_mount_point("/", "./www");
  6706. svr.wait_until_ready();
  6707. Client cli("localhost", PORT);
  6708. auto res = cli.Get("/dir/");
  6709. ASSERT_TRUE(res);
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. res = cli.Get("/dir");
  6712. ASSERT_TRUE(res);
  6713. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6714. res = cli.Get("/file");
  6715. ASSERT_TRUE(res);
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. res = cli.Get("/file/");
  6718. ASSERT_TRUE(res);
  6719. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6720. cli.set_follow_location(true);
  6721. res = cli.Get("/dir");
  6722. ASSERT_TRUE(res);
  6723. EXPECT_EQ(StatusCode::OK_200, res->status);
  6724. }
  6725. TEST(MountTest, MultibytesPathName) {
  6726. Server svr;
  6727. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6728. auto se = detail::scope_exit([&] {
  6729. svr.stop();
  6730. listen_thread.join();
  6731. ASSERT_FALSE(svr.is_running());
  6732. });
  6733. svr.set_mount_point("/", "./www");
  6734. svr.wait_until_ready();
  6735. Client cli("localhost", PORT);
  6736. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6737. ASSERT_TRUE(res);
  6738. EXPECT_EQ(StatusCode::OK_200, res->status);
  6739. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6740. }
  6741. #ifdef _WIN32
  6742. // Issue #2435: mmap::open() must succeed even when another handle holds
  6743. // the file open for writing (e.g. an active log file).
  6744. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  6745. const char *path = "mmap_concurrent_writer_test.txt";
  6746. const char *content = "hello";
  6747. {
  6748. std::ofstream f(path, std::ios::binary);
  6749. f.write(content, static_cast<std::streamsize>(strlen(content)));
  6750. }
  6751. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  6752. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  6753. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  6754. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  6755. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  6756. detail::mmap m(path);
  6757. ASSERT_TRUE(m.is_open());
  6758. EXPECT_EQ(strlen(content), m.size());
  6759. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  6760. }
  6761. #endif
  6762. TEST(KeepAliveTest, ReadTimeout) {
  6763. Server svr;
  6764. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6765. std::this_thread::sleep_for(std::chrono::seconds(2));
  6766. res.set_content("a", "text/plain");
  6767. });
  6768. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6769. res.set_content("b", "text/plain");
  6770. });
  6771. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6772. auto se = detail::scope_exit([&] {
  6773. svr.stop();
  6774. listen_thread.join();
  6775. ASSERT_FALSE(svr.is_running());
  6776. });
  6777. svr.wait_until_ready();
  6778. Client cli("localhost", PORT);
  6779. cli.set_keep_alive(true);
  6780. cli.set_read_timeout(std::chrono::seconds(1));
  6781. auto resa = cli.Get("/a");
  6782. ASSERT_FALSE(resa);
  6783. EXPECT_EQ(Error::Read, resa.error());
  6784. auto resb = cli.Get("/b");
  6785. ASSERT_TRUE(resb);
  6786. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6787. EXPECT_EQ("b", resb->body);
  6788. }
  6789. TEST(KeepAliveTest, MaxCount) {
  6790. size_t keep_alive_max_count = 3;
  6791. Server svr;
  6792. svr.set_keep_alive_max_count(keep_alive_max_count);
  6793. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6794. res.set_content("Hello World!", "text/plain");
  6795. });
  6796. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6797. auto se = detail::scope_exit([&] {
  6798. svr.stop();
  6799. listen_thread.join();
  6800. ASSERT_FALSE(svr.is_running());
  6801. });
  6802. svr.wait_until_ready();
  6803. Client cli(HOST, PORT);
  6804. cli.set_keep_alive(true);
  6805. for (size_t i = 0; i < 5; i++) {
  6806. auto result = cli.Get("/hi");
  6807. ASSERT_TRUE(result);
  6808. EXPECT_EQ(StatusCode::OK_200, result->status);
  6809. if (i == keep_alive_max_count - 1) {
  6810. EXPECT_EQ("close", result->get_header_value("Connection"));
  6811. } else {
  6812. EXPECT_FALSE(result->has_header("Connection"));
  6813. }
  6814. }
  6815. }
  6816. TEST(KeepAliveTest, Issue1041) {
  6817. Server svr;
  6818. svr.set_keep_alive_timeout(3);
  6819. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6820. res.set_content("Hello World!", "text/plain");
  6821. });
  6822. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6823. auto se = detail::scope_exit([&] {
  6824. svr.stop();
  6825. listen_thread.join();
  6826. ASSERT_FALSE(svr.is_running());
  6827. });
  6828. svr.wait_until_ready();
  6829. Client cli(HOST, PORT);
  6830. cli.set_keep_alive(true);
  6831. auto result = cli.Get("/hi");
  6832. ASSERT_TRUE(result);
  6833. EXPECT_EQ(StatusCode::OK_200, result->status);
  6834. std::this_thread::sleep_for(std::chrono::seconds(5));
  6835. result = cli.Get("/hi");
  6836. ASSERT_TRUE(result);
  6837. EXPECT_EQ(StatusCode::OK_200, result->status);
  6838. }
  6839. TEST(KeepAliveTest, Issue1959) {
  6840. Server svr;
  6841. svr.set_keep_alive_timeout(5);
  6842. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6843. res.set_content("a", "text/plain");
  6844. });
  6845. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6846. auto se = detail::scope_exit([&] {
  6847. if (!svr.is_running()) return;
  6848. svr.stop();
  6849. listen_thread.join();
  6850. ASSERT_FALSE(svr.is_running());
  6851. });
  6852. svr.wait_until_ready();
  6853. Client cli("localhost", PORT);
  6854. cli.set_keep_alive(true);
  6855. using namespace std::chrono;
  6856. auto start = steady_clock::now();
  6857. cli.Get("/a");
  6858. svr.stop();
  6859. listen_thread.join();
  6860. auto end = steady_clock::now();
  6861. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6862. EXPECT_LT(elapsed, 5000);
  6863. }
  6864. #ifdef CPPHTTPLIB_SSL_ENABLED
  6865. TEST(KeepAliveTest, SSLClientReconnection) {
  6866. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6867. ASSERT_TRUE(svr.is_valid());
  6868. svr.set_keep_alive_timeout(1);
  6869. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6870. res.set_content("Hello World!", "text/plain");
  6871. });
  6872. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6873. auto se = detail::scope_exit([&] {
  6874. svr.stop();
  6875. listen_thread.join();
  6876. ASSERT_FALSE(svr.is_running());
  6877. });
  6878. svr.wait_until_ready();
  6879. SSLClient cli(HOST, PORT);
  6880. cli.enable_server_certificate_verification(false);
  6881. cli.set_keep_alive(true);
  6882. auto result = cli.Get("/hi");
  6883. ASSERT_TRUE(result);
  6884. EXPECT_EQ(StatusCode::OK_200, result->status);
  6885. result = cli.Get("/hi");
  6886. ASSERT_TRUE(result);
  6887. EXPECT_EQ(StatusCode::OK_200, result->status);
  6888. std::this_thread::sleep_for(std::chrono::seconds(2));
  6889. // Recoonect
  6890. result = cli.Get("/hi");
  6891. ASSERT_TRUE(result);
  6892. EXPECT_EQ(StatusCode::OK_200, result->status);
  6893. result = cli.Get("/hi");
  6894. ASSERT_TRUE(result);
  6895. EXPECT_EQ(StatusCode::OK_200, result->status);
  6896. }
  6897. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6899. ASSERT_TRUE(svr.is_valid());
  6900. svr.set_keep_alive_timeout(1);
  6901. std::string content = "reconnect";
  6902. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6903. res.set_content("Hello World!", "text/plain");
  6904. });
  6905. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6906. auto se = detail::scope_exit([&] {
  6907. svr.stop();
  6908. listen_thread.join();
  6909. ASSERT_FALSE(svr.is_running());
  6910. });
  6911. svr.wait_until_ready();
  6912. SSLClient cli(HOST, PORT);
  6913. cli.enable_server_certificate_verification(false);
  6914. cli.set_keep_alive(true);
  6915. auto result = cli.Post(
  6916. "/hi", content.size(),
  6917. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6918. sink.write(content.c_str(), content.size());
  6919. return true;
  6920. },
  6921. "text/plain");
  6922. ASSERT_TRUE(result);
  6923. EXPECT_EQ(200, result->status);
  6924. std::this_thread::sleep_for(std::chrono::seconds(2));
  6925. // Recoonect
  6926. result = cli.Post(
  6927. "/hi", content.size(),
  6928. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6929. sink.write(content.c_str(), content.size());
  6930. return true;
  6931. },
  6932. "text/plain");
  6933. ASSERT_TRUE(result);
  6934. EXPECT_EQ(200, result->status);
  6935. result = cli.Post(
  6936. "/hi", content.size(),
  6937. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6938. sink.write(content.c_str(), content.size());
  6939. return true;
  6940. },
  6941. "text/plain");
  6942. ASSERT_TRUE(result);
  6943. EXPECT_EQ(200, result->status);
  6944. }
  6945. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6946. using namespace httplib::tls;
  6947. {
  6948. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6949. ASSERT_TRUE(svr.is_valid());
  6950. svr.Get("/sni", [&](const Request &req, Response &res) {
  6951. std::string expected = req.sni();
  6952. EXPECT_EQ(expected, req.get_param_value("expected"));
  6953. res.set_content("ok", "text/plain");
  6954. });
  6955. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6956. auto se = detail::scope_exit([&] {
  6957. svr.stop();
  6958. listen_thread.join();
  6959. ASSERT_FALSE(svr.is_running());
  6960. });
  6961. svr.wait_until_ready();
  6962. {
  6963. SSLClient cli("localhost", PORT);
  6964. cli.enable_server_certificate_verification(false);
  6965. auto res = cli.Get("/sni?expected=localhost");
  6966. ASSERT_TRUE(res);
  6967. }
  6968. {
  6969. SSLClient cli("::1", PORT);
  6970. cli.enable_server_certificate_verification(false);
  6971. auto res = cli.Get("/sni?expected=");
  6972. // NOTE: This may fail if the server is listening on IPv4 only
  6973. // (e.g., when localhost resolves to 127.0.0.1 only)
  6974. if (res) {
  6975. EXPECT_EQ(StatusCode::OK_200, res->status);
  6976. } else {
  6977. EXPECT_EQ(Error::Connection, res.error());
  6978. }
  6979. }
  6980. }
  6981. }
  6982. #endif
  6983. TEST(ClientProblemDetectionTest, ContentProvider) {
  6984. Server svr;
  6985. size_t content_length = 1024 * 1024;
  6986. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6987. res.set_content_provider(
  6988. content_length, "text/plain",
  6989. [&](size_t offset, size_t length, DataSink &sink) {
  6990. auto out_len = std::min(length, static_cast<size_t>(1024));
  6991. std::string out(out_len, '@');
  6992. sink.write(out.data(), out_len);
  6993. return offset < 4096;
  6994. },
  6995. [](bool success) { ASSERT_FALSE(success); });
  6996. });
  6997. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6998. res.set_content_provider(
  6999. 0, "text/plain",
  7000. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7001. EXPECT_TRUE(false);
  7002. return true;
  7003. },
  7004. [](bool success) { ASSERT_FALSE(success); });
  7005. });
  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. {
  7015. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7016. size_t /*data_length*/) { return false; });
  7017. ASSERT_FALSE(res);
  7018. }
  7019. {
  7020. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7021. size_t /*data_length*/) { return false; });
  7022. ASSERT_TRUE(res);
  7023. }
  7024. }
  7025. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7026. Server svr;
  7027. svr.set_error_handler([](Request const &, Response &res) -> void {
  7028. res.set_chunked_content_provider(
  7029. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7030. sink.os << "hello";
  7031. sink.os << "world";
  7032. sink.done();
  7033. return true;
  7034. });
  7035. });
  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.wait_until_ready();
  7043. Client cli("localhost", PORT);
  7044. auto res = cli.Get("/");
  7045. ASSERT_TRUE(res);
  7046. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7047. EXPECT_EQ("helloworld", res->body);
  7048. }
  7049. TEST(LongPollingTest, ClientCloseDetection) {
  7050. Server svr;
  7051. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7052. res.set_chunked_content_provider(
  7053. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7054. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7055. sink.os << "hello";
  7056. auto count = 10;
  7057. while (count > 0 && sink.is_writable()) {
  7058. this_thread::sleep_for(chrono::milliseconds(10));
  7059. count--;
  7060. }
  7061. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7062. return true;
  7063. });
  7064. });
  7065. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7066. auto se = detail::scope_exit([&] {
  7067. svr.stop();
  7068. listen_thread.join();
  7069. ASSERT_FALSE(svr.is_running());
  7070. });
  7071. svr.wait_until_ready();
  7072. Client cli("localhost", PORT);
  7073. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7074. EXPECT_EQ("hello", string(data, data_length));
  7075. return false; // close the socket immediately.
  7076. });
  7077. ASSERT_FALSE(res);
  7078. }
  7079. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7080. Server svr;
  7081. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7082. res.set_chunked_content_provider(
  7083. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7084. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7085. sink.os << "hello";
  7086. EXPECT_TRUE(sink.os.good());
  7087. // Wait for the client to close the connection
  7088. auto count = 10;
  7089. while (count > 0 && sink.is_writable()) {
  7090. this_thread::sleep_for(chrono::milliseconds(10));
  7091. count--;
  7092. }
  7093. // After client disconnect, write repeatedly until the socket
  7094. // write actually fails (small writes may be absorbed by the
  7095. // kernel buffer)
  7096. std::string chunk(1024, 'x');
  7097. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7098. sink.os << chunk;
  7099. }
  7100. EXPECT_TRUE(sink.os.fail());
  7101. return true;
  7102. });
  7103. });
  7104. auto port = svr.bind_to_any_port("localhost");
  7105. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7106. auto se = detail::scope_exit([&] {
  7107. svr.stop();
  7108. listen_thread.join();
  7109. ASSERT_FALSE(svr.is_running());
  7110. });
  7111. svr.wait_until_ready();
  7112. Client cli("localhost", port);
  7113. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7114. EXPECT_EQ("hello", string(data, data_length));
  7115. return false; // close the socket immediately.
  7116. });
  7117. ASSERT_FALSE(res);
  7118. }
  7119. TEST(GetWithParametersTest, GetWithParameters) {
  7120. Server svr;
  7121. svr.Get("/", [&](const Request &req, Response &) {
  7122. EXPECT_EQ("world", req.get_param_value("hello"));
  7123. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7124. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7125. });
  7126. svr.Get("/params", [&](const Request &req, Response &) {
  7127. EXPECT_EQ("world", req.get_param_value("hello"));
  7128. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7129. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7130. });
  7131. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7132. EXPECT_EQ("resource-id", req.matches[1]);
  7133. EXPECT_EQ("foo", req.get_param_value("param1"));
  7134. EXPECT_EQ("bar", req.get_param_value("param2"));
  7135. });
  7136. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7137. EXPECT_EQ("user-id", req.path_params.at("id"));
  7138. EXPECT_EQ("foo", req.get_param_value("param1"));
  7139. EXPECT_EQ("bar", req.get_param_value("param2"));
  7140. });
  7141. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7142. auto se = detail::scope_exit([&] {
  7143. svr.stop();
  7144. listen_thread.join();
  7145. ASSERT_FALSE(svr.is_running());
  7146. });
  7147. svr.wait_until_ready();
  7148. {
  7149. Client cli(HOST, PORT);
  7150. Params params;
  7151. params.emplace("hello", "world");
  7152. params.emplace("hello2", "world2");
  7153. params.emplace("hello3", "world3");
  7154. auto res = cli.Get("/", params, Headers{});
  7155. ASSERT_TRUE(res);
  7156. EXPECT_EQ(StatusCode::OK_200, res->status);
  7157. }
  7158. {
  7159. Client cli(HOST, PORT);
  7160. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7161. ASSERT_TRUE(res);
  7162. EXPECT_EQ(StatusCode::OK_200, res->status);
  7163. }
  7164. {
  7165. Client cli(HOST, PORT);
  7166. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7167. ASSERT_TRUE(res);
  7168. EXPECT_EQ(StatusCode::OK_200, res->status);
  7169. }
  7170. {
  7171. Client cli(HOST, PORT);
  7172. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7173. ASSERT_TRUE(res);
  7174. EXPECT_EQ(StatusCode::OK_200, res->status);
  7175. }
  7176. }
  7177. TEST(GetWithParametersTest, GetWithParameters2) {
  7178. Server svr;
  7179. svr.Get("/", [&](const Request &req, Response &res) {
  7180. auto text = req.get_param_value("hello");
  7181. res.set_content(text, "text/plain");
  7182. });
  7183. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7184. auto se = detail::scope_exit([&] {
  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. Params params;
  7192. params.emplace("hello", "world");
  7193. std::string body;
  7194. auto res = cli.Get("/", params, Headers{},
  7195. [&](const char *data, size_t data_length) {
  7196. body.append(data, data_length);
  7197. return true;
  7198. });
  7199. ASSERT_TRUE(res);
  7200. EXPECT_EQ(StatusCode::OK_200, res->status);
  7201. EXPECT_EQ("world", body);
  7202. }
  7203. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7204. auto host = "httpbingo.org";
  7205. auto path = std::string{"/range/32"};
  7206. #ifdef CPPHTTPLIB_SSL_ENABLED
  7207. SSLClient cli(host);
  7208. #else
  7209. Client cli(host);
  7210. #endif
  7211. cli.set_default_headers({make_range_header({{1, 10}})});
  7212. cli.set_connection_timeout(5);
  7213. {
  7214. auto res = cli.Get(path);
  7215. ASSERT_TRUE(res);
  7216. EXPECT_EQ("bcdefghijk", res->body);
  7217. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7218. }
  7219. {
  7220. auto res = cli.Get(path);
  7221. ASSERT_TRUE(res);
  7222. EXPECT_EQ("bcdefghijk", res->body);
  7223. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7224. }
  7225. }
  7226. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7227. Server svr;
  7228. svr.set_default_headers({{"Hello", "World"}});
  7229. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7230. res.set_content("ok", "text/plain");
  7231. });
  7232. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7233. auto se = detail::scope_exit([&] {
  7234. svr.stop();
  7235. listen_thread.join();
  7236. ASSERT_FALSE(svr.is_running());
  7237. });
  7238. svr.wait_until_ready();
  7239. Client cli("localhost", PORT);
  7240. auto res = cli.Get("/");
  7241. ASSERT_TRUE(res);
  7242. EXPECT_EQ(StatusCode::OK_200, res->status);
  7243. EXPECT_EQ("ok", res->body);
  7244. EXPECT_EQ("World", res->get_header_value("Hello"));
  7245. }
  7246. #ifdef CPPHTTPLIB_SSL_ENABLED
  7247. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7249. ASSERT_TRUE(svr.is_valid());
  7250. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7251. std::this_thread::sleep_for(std::chrono::seconds(2));
  7252. res.set_content("a", "text/plain");
  7253. });
  7254. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7255. res.set_content("b", "text/plain");
  7256. });
  7257. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7258. auto se = detail::scope_exit([&] {
  7259. svr.stop();
  7260. listen_thread.join();
  7261. ASSERT_FALSE(svr.is_running());
  7262. });
  7263. svr.wait_until_ready();
  7264. SSLClient cli("localhost", PORT);
  7265. cli.enable_server_certificate_verification(false);
  7266. cli.set_keep_alive(true);
  7267. cli.set_read_timeout(std::chrono::seconds(1));
  7268. auto resa = cli.Get("/a");
  7269. ASSERT_TRUE(!resa);
  7270. EXPECT_EQ(Error::Read, resa.error());
  7271. auto resb = cli.Get("/b");
  7272. ASSERT_TRUE(resb);
  7273. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7274. EXPECT_EQ("b", resb->body);
  7275. }
  7276. #endif
  7277. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7278. protected:
  7279. ServerTestWithAI_PASSIVE()
  7280. : cli_(HOST, PORT)
  7281. #ifdef CPPHTTPLIB_SSL_ENABLED
  7282. ,
  7283. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7284. #endif
  7285. {
  7286. #ifdef CPPHTTPLIB_SSL_ENABLED
  7287. cli_.enable_server_certificate_verification(false);
  7288. #endif
  7289. }
  7290. virtual void SetUp() {
  7291. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7292. res.set_content("Hello World!", "text/plain");
  7293. });
  7294. t_ = thread(
  7295. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7296. svr_.wait_until_ready();
  7297. }
  7298. virtual void TearDown() {
  7299. svr_.stop();
  7300. t_.join();
  7301. }
  7302. #ifdef CPPHTTPLIB_SSL_ENABLED
  7303. SSLClient cli_;
  7304. SSLServer svr_;
  7305. #else
  7306. Client cli_;
  7307. Server svr_;
  7308. #endif
  7309. thread t_;
  7310. };
  7311. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7312. auto res = cli_.Get("/hi");
  7313. ASSERT_TRUE(res);
  7314. EXPECT_EQ(StatusCode::OK_200, res->status);
  7315. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7316. EXPECT_EQ("Hello World!", res->body);
  7317. }
  7318. class ServerUpDownTest : public ::testing::Test {
  7319. protected:
  7320. ServerUpDownTest() : cli_(HOST, PORT) {}
  7321. virtual void SetUp() {
  7322. t_ = thread([&]() {
  7323. svr_.bind_to_any_port(HOST);
  7324. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7325. ASSERT_TRUE(svr_.listen_after_bind());
  7326. });
  7327. svr_.wait_until_ready();
  7328. }
  7329. virtual void TearDown() {
  7330. svr_.stop();
  7331. t_.join();
  7332. }
  7333. Client cli_;
  7334. Server svr_;
  7335. thread t_;
  7336. };
  7337. TEST_F(ServerUpDownTest, QuickStartStop) {
  7338. // Should not crash, especially when run with
  7339. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7340. }
  7341. class PayloadMaxLengthTest : public ::testing::Test {
  7342. protected:
  7343. PayloadMaxLengthTest()
  7344. : cli_(HOST, PORT)
  7345. #ifdef CPPHTTPLIB_SSL_ENABLED
  7346. ,
  7347. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7348. #endif
  7349. {
  7350. #ifdef CPPHTTPLIB_SSL_ENABLED
  7351. cli_.enable_server_certificate_verification(false);
  7352. #endif
  7353. }
  7354. virtual void SetUp() {
  7355. svr_.set_payload_max_length(8);
  7356. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7357. res.set_content("test", "text/plain");
  7358. });
  7359. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7360. svr_.wait_until_ready();
  7361. }
  7362. virtual void TearDown() {
  7363. svr_.stop();
  7364. t_.join();
  7365. }
  7366. #ifdef CPPHTTPLIB_SSL_ENABLED
  7367. SSLClient cli_;
  7368. SSLServer svr_;
  7369. #else
  7370. Client cli_;
  7371. Server svr_;
  7372. #endif
  7373. thread t_;
  7374. };
  7375. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7376. auto res = cli_.Post("/test", "123456789", "text/plain");
  7377. ASSERT_TRUE(res);
  7378. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7379. res = cli_.Post("/test", "12345678", "text/plain");
  7380. ASSERT_TRUE(res);
  7381. EXPECT_EQ(StatusCode::OK_200, res->status);
  7382. }
  7383. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7384. // Test chunked encoding with payload exceeding the 8-byte limit
  7385. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7386. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7387. ASSERT_TRUE(res);
  7388. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7389. }
  7390. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7391. // Test chunked encoding with payload within the 8-byte limit
  7392. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7393. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7394. ASSERT_TRUE(res);
  7395. EXPECT_EQ(StatusCode::OK_200, res->status);
  7396. }
  7397. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7398. // Test using send_request to send chunked data exceeding payload limit
  7399. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7400. "Host: " +
  7401. std::string(HOST) + ":" + std::to_string(PORT) +
  7402. "\r\n"
  7403. "Transfer-Encoding: chunked\r\n"
  7404. "Connection: close\r\n"
  7405. "\r\n"
  7406. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7407. "0123456789\r\n"
  7408. "0\r\n" // End chunk
  7409. "\r\n";
  7410. std::string response;
  7411. bool result = send_request(1, chunked_request, &response);
  7412. if (!result) {
  7413. // If send_request fails, it might be because the server closed the
  7414. // connection due to payload limit enforcement, which is acceptable
  7415. SUCCEED()
  7416. << "Server rejected oversized chunked request (connection closed)";
  7417. } else {
  7418. // If we got a response, check if it's an error response or connection was
  7419. // closed early Short response length indicates connection was closed due to
  7420. // payload limit
  7421. if (response.length() <= 10) {
  7422. SUCCEED() << "Server closed connection for oversized chunked request";
  7423. } else {
  7424. // Check for error status codes
  7425. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7426. response.find("Payload Too Large") != std::string::npos ||
  7427. response.find("400") != std::string::npos);
  7428. }
  7429. }
  7430. }
  7431. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7432. // Test request without Content-Length header exceeding payload limit
  7433. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7434. "Host: " +
  7435. std::string(HOST) + ":" +
  7436. std::to_string(PORT) +
  7437. "\r\n"
  7438. "Connection: close\r\n"
  7439. "\r\n";
  7440. // Add payload exceeding the 8-byte limit
  7441. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7442. request_without_content_length += large_payload;
  7443. std::string response;
  7444. bool result = send_request(1, request_without_content_length, &response);
  7445. if (!result) {
  7446. // If send_request fails, server likely closed connection due to payload
  7447. // limit
  7448. SUCCEED() << "Server rejected oversized request without Content-Length "
  7449. "(connection closed)";
  7450. } else {
  7451. // Check if server responded with error or closed connection early
  7452. if (response.length() <= 10) {
  7453. SUCCEED() << "Server closed connection for oversized request without "
  7454. "Content-Length";
  7455. } else {
  7456. // Check for error status codes
  7457. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7458. response.find("Payload Too Large") != std::string::npos ||
  7459. response.find("400") != std::string::npos);
  7460. }
  7461. }
  7462. }
  7463. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7464. // Test request without Content-Length header within payload limit
  7465. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7466. "Host: " +
  7467. std::string(HOST) + ":" +
  7468. std::to_string(PORT) +
  7469. "\r\n"
  7470. "Connection: close\r\n"
  7471. "\r\n";
  7472. // Add payload within the 8-byte limit
  7473. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7474. request_without_content_length += small_payload;
  7475. std::string response;
  7476. bool result = send_request(1, request_without_content_length, &response);
  7477. // For requests without Content-Length, the server may have different behavior
  7478. // The key is that it should not reject due to payload limit for small
  7479. // payloads
  7480. if (result) {
  7481. // Check for any HTTP response (success or error, but not connection closed)
  7482. if (response.length() > 10) {
  7483. SUCCEED()
  7484. << "Server processed request without Content-Length within limit";
  7485. } else {
  7486. // Short response might indicate connection closed, which is acceptable
  7487. SUCCEED() << "Server closed connection for request without "
  7488. "Content-Length (acceptable behavior)";
  7489. }
  7490. } else {
  7491. // Connection failure might be due to protocol requirements
  7492. SUCCEED() << "Connection issue with request without Content-Length "
  7493. "(environment-specific)";
  7494. }
  7495. }
  7496. class LargePayloadMaxLengthTest : public ::testing::Test {
  7497. protected:
  7498. LargePayloadMaxLengthTest()
  7499. : cli_(HOST, PORT)
  7500. #ifdef CPPHTTPLIB_SSL_ENABLED
  7501. ,
  7502. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7503. #endif
  7504. {
  7505. #ifdef CPPHTTPLIB_SSL_ENABLED
  7506. cli_.enable_server_certificate_verification(false);
  7507. #endif
  7508. }
  7509. virtual void SetUp() {
  7510. // Set 10MB payload limit
  7511. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7512. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7513. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7514. res.set_content("Large payload test", "text/plain");
  7515. });
  7516. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7517. svr_.wait_until_ready();
  7518. }
  7519. virtual void TearDown() {
  7520. svr_.stop();
  7521. t_.join();
  7522. }
  7523. #ifdef CPPHTTPLIB_SSL_ENABLED
  7524. SSLClient cli_;
  7525. SSLServer svr_;
  7526. #else
  7527. Client cli_;
  7528. Server svr_;
  7529. #endif
  7530. thread t_;
  7531. };
  7532. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7533. // Test chunked encoding with payload within 10MB limit
  7534. std::string medium_payload(5 * 1024 * 1024,
  7535. 'A'); // 5MB payload, within 10MB limit
  7536. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7537. ASSERT_TRUE(res);
  7538. EXPECT_EQ(StatusCode::OK_200, res->status);
  7539. }
  7540. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7541. // Test chunked encoding with payload exceeding 10MB limit
  7542. std::string large_payload(12 * 1024 * 1024,
  7543. 'B'); // 12MB payload, exceeds 10MB limit
  7544. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7545. // Server may either return 413 or close the connection
  7546. if (res) {
  7547. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7548. } else {
  7549. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7550. }
  7551. }
  7552. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7553. // Test request without Content-Length header within 10MB limit
  7554. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7555. "Host: " +
  7556. std::string(HOST) + ":" +
  7557. std::to_string(PORT) +
  7558. "\r\n"
  7559. "Connection: close\r\n"
  7560. "\r\n";
  7561. // Add 1MB payload (within 10MB limit)
  7562. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7563. request_without_content_length += medium_payload;
  7564. std::string response;
  7565. bool result = send_request(5, request_without_content_length, &response);
  7566. if (result) {
  7567. // Should get a proper HTTP response for payloads within limit
  7568. if (response.length() > 10) {
  7569. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7570. "10MB limit";
  7571. } else {
  7572. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7573. "Content-Length)";
  7574. }
  7575. } else {
  7576. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7577. }
  7578. }
  7579. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7580. // Test request without Content-Length header exceeding 10MB limit
  7581. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7582. "Host: " +
  7583. std::string(HOST) + ":" +
  7584. std::to_string(PORT) +
  7585. "\r\n"
  7586. "Connection: close\r\n"
  7587. "\r\n";
  7588. // Add 12MB payload (exceeds 10MB limit)
  7589. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7590. request_without_content_length += large_payload;
  7591. std::string response;
  7592. bool result = send_request(10, request_without_content_length, &response);
  7593. if (!result) {
  7594. // Server should close connection due to payload limit
  7595. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7596. "(connection closed)";
  7597. } else {
  7598. // Check for error response
  7599. if (response.length() <= 10) {
  7600. SUCCEED()
  7601. << "Server closed connection for 12MB request exceeding 10MB limit";
  7602. } else {
  7603. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7604. response.find("Payload Too Large") != std::string::npos ||
  7605. response.find("400") != std::string::npos);
  7606. }
  7607. }
  7608. }
  7609. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7610. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7611. // path.
  7612. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7613. Server svr;
  7614. const size_t LIMIT = 64 * 1024; // 64KB
  7615. svr.set_payload_max_length(LIMIT);
  7616. size_t total = 0;
  7617. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7618. const ContentReader &content_reader) {
  7619. content_reader([&](const char * /*data*/, size_t len) {
  7620. total += len;
  7621. return true;
  7622. });
  7623. res.status = 200;
  7624. res.set_content("stream_ok", "text/plain");
  7625. });
  7626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7627. auto se = detail::scope_exit([&] {
  7628. svr.stop();
  7629. thread.join();
  7630. ASSERT_FALSE(svr.is_running());
  7631. });
  7632. svr.wait_until_ready();
  7633. // Prepare 256KB raw data and gzip-compress it
  7634. std::string raw(256 * 1024, 'A');
  7635. std::string gz;
  7636. {
  7637. z_stream zs{};
  7638. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7639. Z_DEFAULT_STRATEGY);
  7640. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7641. zs.avail_in = static_cast<uInt>(raw.size());
  7642. char outbuf[4096];
  7643. int ret;
  7644. do {
  7645. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7646. zs.avail_out = sizeof(outbuf);
  7647. ret = deflate(&zs, Z_FINISH);
  7648. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7649. } while (ret != Z_STREAM_END);
  7650. deflateEnd(&zs);
  7651. }
  7652. Client cli(HOST, PORT);
  7653. cli.set_connection_timeout(std::chrono::seconds(5));
  7654. Headers headers = {{"Content-Encoding", "gzip"}};
  7655. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7656. "application/octet-stream");
  7657. ASSERT_TRUE(res);
  7658. // Server must reject oversized decompressed payloads with 413.
  7659. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7660. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7661. EXPECT_LE(total, LIMIT);
  7662. }
  7663. #endif
  7664. // Regression test for DoS vulnerability: a malicious server sending a response
  7665. // without Content-Length header must not cause unbounded memory consumption on
  7666. // the client side. The client should stop reading after a reasonable limit,
  7667. // similar to the server-side set_payload_max_length protection.
  7668. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7669. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7670. #ifndef _WIN32
  7671. signal(SIGPIPE, SIG_IGN);
  7672. #endif
  7673. auto server_thread = std::thread([] {
  7674. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7675. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7676. default_socket_options(srv);
  7677. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7678. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7679. sockaddr_in addr{};
  7680. addr.sin_family = AF_INET;
  7681. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7682. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7683. int opt = 1;
  7684. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7685. #ifdef _WIN32
  7686. reinterpret_cast<const char *>(&opt),
  7687. #else
  7688. &opt,
  7689. #endif
  7690. sizeof(opt));
  7691. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7692. ::listen(srv, 1);
  7693. sockaddr_in cli_addr{};
  7694. socklen_t cli_len = sizeof(cli_addr);
  7695. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7696. if (cli != INVALID_SOCKET) {
  7697. char buf[4096];
  7698. ::recv(cli, buf, sizeof(buf), 0);
  7699. // Malicious response: no Content-Length, no chunked encoding
  7700. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7701. "Connection: close\r\n"
  7702. "\r\n";
  7703. ::send(cli,
  7704. #ifdef _WIN32
  7705. static_cast<const char *>(response_header.c_str()),
  7706. static_cast<int>(response_header.size()),
  7707. #else
  7708. response_header.c_str(), response_header.size(),
  7709. #endif
  7710. 0);
  7711. // Send 10MB of data
  7712. std::string chunk(64 * 1024, 'A');
  7713. size_t total_sent = 0;
  7714. while (total_sent < MALICIOUS_DATA_SIZE) {
  7715. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7716. auto sent = ::send(cli,
  7717. #ifdef _WIN32
  7718. static_cast<const char *>(chunk.c_str()),
  7719. static_cast<int>(to_send),
  7720. #else
  7721. chunk.c_str(), to_send,
  7722. #endif
  7723. 0);
  7724. if (sent <= 0) break;
  7725. total_sent += static_cast<size_t>(sent);
  7726. }
  7727. detail::close_socket(cli);
  7728. }
  7729. detail::close_socket(srv);
  7730. });
  7731. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7732. size_t total_read = 0;
  7733. {
  7734. Client cli("127.0.0.1", PORT + 2);
  7735. cli.set_read_timeout(5, 0);
  7736. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7737. auto stream = cli.open_stream("GET", "/malicious");
  7738. ASSERT_TRUE(stream.is_valid());
  7739. char buffer[64 * 1024];
  7740. ssize_t n;
  7741. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7742. total_read += static_cast<size_t>(n);
  7743. }
  7744. } // StreamHandle and Client destroyed here, closing the socket
  7745. server_thread.join();
  7746. // With set_payload_max_length, the client must stop reading before consuming
  7747. // all 10MB. The read loop should be cut off at or near the configured limit.
  7748. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7749. << "Client read " << total_read << " bytes, exceeding the configured "
  7750. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7751. }
  7752. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7753. // the entire response body without truncation.
  7754. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7755. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7756. #ifndef _WIN32
  7757. signal(SIGPIPE, SIG_IGN);
  7758. #endif
  7759. auto server_thread = std::thread([] {
  7760. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7761. default_socket_options(srv);
  7762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7763. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7764. sockaddr_in addr{};
  7765. addr.sin_family = AF_INET;
  7766. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7767. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7768. int opt = 1;
  7769. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7770. #ifdef _WIN32
  7771. reinterpret_cast<const char *>(&opt),
  7772. #else
  7773. &opt,
  7774. #endif
  7775. sizeof(opt));
  7776. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7777. ::listen(srv, 1);
  7778. sockaddr_in cli_addr{};
  7779. socklen_t cli_len = sizeof(cli_addr);
  7780. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7781. if (cli != INVALID_SOCKET) {
  7782. char buf[4096];
  7783. ::recv(cli, buf, sizeof(buf), 0);
  7784. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7785. "Connection: close\r\n"
  7786. "\r\n";
  7787. ::send(cli,
  7788. #ifdef _WIN32
  7789. static_cast<const char *>(response_header.c_str()),
  7790. static_cast<int>(response_header.size()),
  7791. #else
  7792. response_header.c_str(), response_header.size(),
  7793. #endif
  7794. 0);
  7795. std::string chunk(64 * 1024, 'A');
  7796. size_t total_sent = 0;
  7797. while (total_sent < DATA_SIZE) {
  7798. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7799. auto sent = ::send(cli,
  7800. #ifdef _WIN32
  7801. static_cast<const char *>(chunk.c_str()),
  7802. static_cast<int>(to_send),
  7803. #else
  7804. chunk.c_str(), to_send,
  7805. #endif
  7806. 0);
  7807. if (sent <= 0) break;
  7808. total_sent += static_cast<size_t>(sent);
  7809. }
  7810. #ifdef _WIN32
  7811. ::shutdown(cli, SD_SEND);
  7812. #else
  7813. ::shutdown(cli, SHUT_WR);
  7814. #endif
  7815. // Drain until the client closes its end, ensuring all data is delivered
  7816. char drain[1024];
  7817. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7818. detail::close_socket(cli);
  7819. }
  7820. detail::close_socket(srv);
  7821. });
  7822. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7823. size_t total_read = 0;
  7824. {
  7825. Client cli("127.0.0.1", PORT + 2);
  7826. cli.set_read_timeout(5, 0);
  7827. cli.set_payload_max_length(0); // 0 means no limit
  7828. auto stream = cli.open_stream("GET", "/data");
  7829. ASSERT_TRUE(stream.is_valid());
  7830. char buffer[64 * 1024];
  7831. ssize_t n;
  7832. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7833. total_read += static_cast<size_t>(n);
  7834. }
  7835. }
  7836. server_thread.join();
  7837. EXPECT_EQ(total_read, DATA_SIZE)
  7838. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7839. << " bytes without truncation, but only read " << total_read << " bytes.";
  7840. }
  7841. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  7842. // enormous Content-Length must not cause the client to pre-allocate a huge
  7843. // response body buffer. The reservation is capped at payload_max_length_, and
  7844. // the read itself fails when the body exceeds the limit.
  7845. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  7846. #ifndef _WIN32
  7847. signal(SIGPIPE, SIG_IGN);
  7848. #endif
  7849. auto server_thread = std::thread([] {
  7850. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7851. default_socket_options(srv);
  7852. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7853. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7854. sockaddr_in addr{};
  7855. addr.sin_family = AF_INET;
  7856. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7857. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7858. int opt = 1;
  7859. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7860. #ifdef _WIN32
  7861. reinterpret_cast<const char *>(&opt),
  7862. #else
  7863. &opt,
  7864. #endif
  7865. sizeof(opt));
  7866. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7867. ::listen(srv, 1);
  7868. sockaddr_in cli_addr{};
  7869. socklen_t cli_len = sizeof(cli_addr);
  7870. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7871. if (cli != INVALID_SOCKET) {
  7872. char buf[4096];
  7873. ::recv(cli, buf, sizeof(buf), 0);
  7874. // Malicious response: claim a 20GB body but send only a tiny payload.
  7875. std::string response = "HTTP/1.1 200 OK\r\n"
  7876. "Content-Length: 20000000000\r\n"
  7877. "\r\n"
  7878. "abc";
  7879. ::send(cli,
  7880. #ifdef _WIN32
  7881. static_cast<const char *>(response.c_str()),
  7882. static_cast<int>(response.size()),
  7883. #else
  7884. response.c_str(), response.size(),
  7885. #endif
  7886. 0);
  7887. detail::close_socket(cli);
  7888. }
  7889. detail::close_socket(srv);
  7890. });
  7891. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7892. {
  7893. Client cli("127.0.0.1", PORT + 2);
  7894. cli.set_read_timeout(5, 0);
  7895. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  7896. // result in a 20GB pre-allocation. The Get() call is expected to fail
  7897. // (server claims more bytes than payload_max_length permits), but it must
  7898. // not exhaust memory before getting there.
  7899. auto res = cli.Get("/malicious");
  7900. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  7901. }
  7902. server_thread.join();
  7903. }
  7904. // Verify that content_receiver bypasses the default payload_max_length,
  7905. // allowing streaming downloads larger than 100MB without requiring an explicit
  7906. // set_payload_max_length call.
  7907. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7908. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7909. #ifndef _WIN32
  7910. signal(SIGPIPE, SIG_IGN);
  7911. #endif
  7912. auto server_thread = std::thread([] {
  7913. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7914. default_socket_options(srv);
  7915. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7916. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7917. sockaddr_in addr{};
  7918. addr.sin_family = AF_INET;
  7919. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7920. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7921. int opt = 1;
  7922. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7923. #ifdef _WIN32
  7924. reinterpret_cast<const char *>(&opt),
  7925. #else
  7926. &opt,
  7927. #endif
  7928. sizeof(opt));
  7929. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7930. ::listen(srv, 1);
  7931. sockaddr_in cli_addr{};
  7932. socklen_t cli_len = sizeof(cli_addr);
  7933. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7934. if (cli != INVALID_SOCKET) {
  7935. char buf[4096];
  7936. ::recv(cli, buf, sizeof(buf), 0);
  7937. // Response with Content-Length larger than default 100MB limit
  7938. auto content_length = std::to_string(DATA_SIZE);
  7939. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7940. "Content-Length: " +
  7941. content_length +
  7942. "\r\n"
  7943. "Connection: close\r\n"
  7944. "\r\n";
  7945. ::send(cli,
  7946. #ifdef _WIN32
  7947. static_cast<const char *>(response_header.c_str()),
  7948. static_cast<int>(response_header.size()),
  7949. #else
  7950. response_header.c_str(), response_header.size(),
  7951. #endif
  7952. 0);
  7953. std::string chunk(64 * 1024, 'A');
  7954. size_t total_sent = 0;
  7955. while (total_sent < DATA_SIZE) {
  7956. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7957. auto sent = ::send(cli,
  7958. #ifdef _WIN32
  7959. static_cast<const char *>(chunk.c_str()),
  7960. static_cast<int>(to_send),
  7961. #else
  7962. chunk.c_str(), to_send,
  7963. #endif
  7964. 0);
  7965. if (sent <= 0) break;
  7966. total_sent += static_cast<size_t>(sent);
  7967. }
  7968. detail::close_socket(cli);
  7969. }
  7970. detail::close_socket(srv);
  7971. });
  7972. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7973. size_t total_received = 0;
  7974. {
  7975. Client cli("127.0.0.1", PORT + 2);
  7976. cli.set_read_timeout(10, 0);
  7977. // Do NOT call set_payload_max_length — use the default 100MB limit
  7978. auto res =
  7979. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7980. total_received += data_length;
  7981. return true;
  7982. });
  7983. ASSERT_TRUE(res);
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. }
  7986. server_thread.join();
  7987. EXPECT_EQ(total_received, DATA_SIZE)
  7988. << "With content_receiver, the client should read all " << DATA_SIZE
  7989. << " bytes despite the default 100MB payload_max_length, but only read "
  7990. << total_received << " bytes.";
  7991. }
  7992. // Verify that an explicit set_payload_max_length smaller than the response is
  7993. // enforced even when a content_receiver is used.
  7994. TEST(ClientVulnerabilityTest,
  7995. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7996. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7997. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7998. #ifndef _WIN32
  7999. signal(SIGPIPE, SIG_IGN);
  8000. #endif
  8001. auto server_thread = std::thread([] {
  8002. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8003. default_socket_options(srv);
  8004. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8005. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8006. sockaddr_in addr{};
  8007. addr.sin_family = AF_INET;
  8008. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8009. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8010. int opt = 1;
  8011. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8012. #ifdef _WIN32
  8013. reinterpret_cast<const char *>(&opt),
  8014. #else
  8015. &opt,
  8016. #endif
  8017. sizeof(opt));
  8018. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8019. ::listen(srv, 1);
  8020. sockaddr_in cli_addr{};
  8021. socklen_t cli_len = sizeof(cli_addr);
  8022. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8023. if (cli != INVALID_SOCKET) {
  8024. char buf[4096];
  8025. ::recv(cli, buf, sizeof(buf), 0);
  8026. auto content_length = std::to_string(DATA_SIZE);
  8027. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8028. "Content-Length: " +
  8029. content_length +
  8030. "\r\n"
  8031. "Connection: close\r\n"
  8032. "\r\n";
  8033. ::send(cli,
  8034. #ifdef _WIN32
  8035. static_cast<const char *>(response_header.c_str()),
  8036. static_cast<int>(response_header.size()),
  8037. #else
  8038. response_header.c_str(), response_header.size(),
  8039. #endif
  8040. 0);
  8041. std::string chunk(64 * 1024, 'A');
  8042. size_t total_sent = 0;
  8043. while (total_sent < DATA_SIZE) {
  8044. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8045. auto sent = ::send(cli,
  8046. #ifdef _WIN32
  8047. static_cast<const char *>(chunk.c_str()),
  8048. static_cast<int>(to_send),
  8049. #else
  8050. chunk.c_str(), to_send,
  8051. #endif
  8052. 0);
  8053. if (sent <= 0) break;
  8054. total_sent += static_cast<size_t>(sent);
  8055. }
  8056. detail::close_socket(cli);
  8057. }
  8058. detail::close_socket(srv);
  8059. });
  8060. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8061. size_t total_received = 0;
  8062. {
  8063. Client cli("127.0.0.1", PORT + 2);
  8064. cli.set_read_timeout(10, 0);
  8065. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8066. auto res =
  8067. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8068. total_received += data_length;
  8069. return true;
  8070. });
  8071. // Should fail because 200MB exceeds the explicit 150MB limit
  8072. EXPECT_FALSE(res);
  8073. }
  8074. server_thread.join();
  8075. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8076. << "Client with content_receiver should respect the explicit "
  8077. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8078. << total_received << " bytes.";
  8079. }
  8080. // Verify that an explicit set_payload_max_length larger than the response
  8081. // allows the content_receiver to read all data successfully.
  8082. TEST(ClientVulnerabilityTest,
  8083. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8084. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8085. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8086. #ifndef _WIN32
  8087. signal(SIGPIPE, SIG_IGN);
  8088. #endif
  8089. auto server_thread = std::thread([] {
  8090. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8091. default_socket_options(srv);
  8092. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8093. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8094. sockaddr_in addr{};
  8095. addr.sin_family = AF_INET;
  8096. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8097. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8098. int opt = 1;
  8099. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8100. #ifdef _WIN32
  8101. reinterpret_cast<const char *>(&opt),
  8102. #else
  8103. &opt,
  8104. #endif
  8105. sizeof(opt));
  8106. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8107. ::listen(srv, 1);
  8108. sockaddr_in cli_addr{};
  8109. socklen_t cli_len = sizeof(cli_addr);
  8110. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8111. if (cli != INVALID_SOCKET) {
  8112. char buf[4096];
  8113. ::recv(cli, buf, sizeof(buf), 0);
  8114. auto content_length = std::to_string(DATA_SIZE);
  8115. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8116. "Content-Length: " +
  8117. content_length +
  8118. "\r\n"
  8119. "Connection: close\r\n"
  8120. "\r\n";
  8121. ::send(cli,
  8122. #ifdef _WIN32
  8123. static_cast<const char *>(response_header.c_str()),
  8124. static_cast<int>(response_header.size()),
  8125. #else
  8126. response_header.c_str(), response_header.size(),
  8127. #endif
  8128. 0);
  8129. std::string chunk(64 * 1024, 'A');
  8130. size_t total_sent = 0;
  8131. while (total_sent < DATA_SIZE) {
  8132. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8133. auto sent = ::send(cli,
  8134. #ifdef _WIN32
  8135. static_cast<const char *>(chunk.c_str()),
  8136. static_cast<int>(to_send),
  8137. #else
  8138. chunk.c_str(), to_send,
  8139. #endif
  8140. 0);
  8141. if (sent <= 0) break;
  8142. total_sent += static_cast<size_t>(sent);
  8143. }
  8144. #ifdef _WIN32
  8145. ::shutdown(cli, SD_SEND);
  8146. #else
  8147. ::shutdown(cli, SHUT_WR);
  8148. #endif
  8149. char drain[1024];
  8150. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8151. detail::close_socket(cli);
  8152. }
  8153. detail::close_socket(srv);
  8154. });
  8155. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8156. size_t total_received = 0;
  8157. {
  8158. Client cli("127.0.0.1", PORT + 2);
  8159. cli.set_read_timeout(10, 0);
  8160. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8161. auto res =
  8162. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8163. total_received += data_length;
  8164. return true;
  8165. });
  8166. ASSERT_TRUE(res);
  8167. EXPECT_EQ(StatusCode::OK_200, res->status);
  8168. }
  8169. server_thread.join();
  8170. EXPECT_EQ(total_received, DATA_SIZE)
  8171. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8172. << " bytes (larger than " << DATA_SIZE
  8173. << " bytes response), content_receiver should read all data, but only "
  8174. "read "
  8175. << total_received << " bytes.";
  8176. }
  8177. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8178. // Regression test for "zip bomb" attack on the client side: a malicious server
  8179. // sends a small gzip-compressed response that decompresses to a huge payload.
  8180. // The client must enforce payload_max_length on the decompressed size.
  8181. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8182. constexpr size_t DECOMPRESSED_SIZE =
  8183. 10 * 1024 * 1024; // 10MB after decompression
  8184. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8185. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8186. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8187. std::string compressed;
  8188. {
  8189. httplib::detail::gzip_compressor compressor;
  8190. bool ok =
  8191. compressor.compress(uncompressed.data(), uncompressed.size(),
  8192. /*last=*/true, [&](const char *buf, size_t len) {
  8193. compressed.append(buf, len);
  8194. return true;
  8195. });
  8196. ASSERT_TRUE(ok);
  8197. }
  8198. // Sanity: compressed data should be much smaller than the decompressed size
  8199. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8200. #ifndef _WIN32
  8201. signal(SIGPIPE, SIG_IGN);
  8202. #endif
  8203. // Set up the listening socket in the main thread so the server is guaranteed
  8204. // to be ready before the client connects (eliminates race condition).
  8205. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8206. default_socket_options(srv);
  8207. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8208. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8209. sockaddr_in addr{};
  8210. addr.sin_family = AF_INET;
  8211. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8212. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8213. int opt = 1;
  8214. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8215. #ifdef _WIN32
  8216. reinterpret_cast<const char *>(&opt),
  8217. #else
  8218. &opt,
  8219. #endif
  8220. sizeof(opt));
  8221. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8222. ASSERT_EQ(0, ::listen(srv, 1));
  8223. auto server_thread = std::thread([&compressed, srv] {
  8224. sockaddr_in cli_addr{};
  8225. socklen_t cli_len = sizeof(cli_addr);
  8226. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8227. if (cli != INVALID_SOCKET) {
  8228. // Read the full HTTP request (until \r\n\r\n)
  8229. char buf[4096];
  8230. size_t total = 0;
  8231. while (total < sizeof(buf)) {
  8232. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8233. if (n <= 0) break;
  8234. total += static_cast<size_t>(n);
  8235. // Check for end of headers
  8236. if (total >= 4) {
  8237. std::string req(buf, total);
  8238. if (req.find("\r\n\r\n") != std::string::npos) break;
  8239. }
  8240. }
  8241. // Malicious response: gzip-compressed body, no Content-Length
  8242. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8243. "Content-Encoding: gzip\r\n"
  8244. "Connection: close\r\n"
  8245. "\r\n";
  8246. ::send(cli,
  8247. #ifdef _WIN32
  8248. static_cast<const char *>(response_header.c_str()),
  8249. static_cast<int>(response_header.size()),
  8250. #else
  8251. response_header.c_str(), response_header.size(),
  8252. #endif
  8253. 0);
  8254. // Send the compressed payload (small on the wire, huge when decompressed)
  8255. size_t total_sent = 0;
  8256. while (total_sent < compressed.size()) {
  8257. auto to_send = std::min(compressed.size() - total_sent,
  8258. static_cast<size_t>(64 * 1024));
  8259. auto sent =
  8260. ::send(cli,
  8261. #ifdef _WIN32
  8262. static_cast<const char *>(compressed.c_str() + total_sent),
  8263. static_cast<int>(to_send),
  8264. #else
  8265. compressed.c_str() + total_sent, to_send,
  8266. #endif
  8267. 0);
  8268. if (sent <= 0) break;
  8269. total_sent += static_cast<size_t>(sent);
  8270. }
  8271. detail::close_socket(cli);
  8272. }
  8273. });
  8274. auto se = detail::scope_exit([&] {
  8275. detail::close_socket(srv);
  8276. server_thread.join();
  8277. });
  8278. size_t total_decompressed = 0;
  8279. {
  8280. Client cli("127.0.0.1", PORT + 3);
  8281. cli.set_read_timeout(5, 0);
  8282. cli.set_decompress(true);
  8283. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8284. auto stream = cli.open_stream("GET", "/zipbomb");
  8285. ASSERT_TRUE(stream.is_valid());
  8286. char buffer[64 * 1024];
  8287. ssize_t n;
  8288. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8289. total_decompressed += static_cast<size_t>(n);
  8290. }
  8291. }
  8292. // The decompressed size must be capped by payload_max_length. Without
  8293. // protection, the client would decompress the full 10MB from a tiny
  8294. // compressed payload, enabling a zip bomb DoS attack.
  8295. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8296. << "Client decompressed " << total_decompressed
  8297. << " bytes from a gzip response. The decompressed size should be "
  8298. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8299. }
  8300. #endif
  8301. TEST(HostAndPortPropertiesTest, NoSSL) {
  8302. httplib::Client cli("www.google.com", 1234);
  8303. ASSERT_EQ("www.google.com", cli.host());
  8304. ASSERT_EQ(1234, cli.port());
  8305. }
  8306. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8307. httplib::Client cli("www.google.com:1234");
  8308. ASSERT_EQ("www.google.com", cli.host());
  8309. ASSERT_EQ(1234, cli.port());
  8310. }
  8311. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8312. // Port number that overflows int — should not crash, client becomes invalid
  8313. httplib::Client cli("http://www.google.com:99999999999999999999");
  8314. ASSERT_FALSE(cli.is_valid());
  8315. }
  8316. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8317. // Port 99999 exceeds valid range (1-65535) — should not crash
  8318. httplib::Client cli("http://www.google.com:99999");
  8319. ASSERT_FALSE(cli.is_valid());
  8320. }
  8321. #ifdef CPPHTTPLIB_SSL_ENABLED
  8322. TEST(HostAndPortPropertiesTest, SSL) {
  8323. httplib::SSLClient cli("www.google.com");
  8324. ASSERT_EQ("www.google.com", cli.host());
  8325. ASSERT_EQ(443, cli.port());
  8326. }
  8327. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8328. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8329. std::string cert;
  8330. read_file(CA_CERT_FILE, cert);
  8331. httplib::SSLClient httplib_client("www.google.com");
  8332. // Load CA store first time
  8333. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8334. // Load CA store second time (update)
  8335. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8336. // Verify client is still valid and can make connections
  8337. httplib_client.enable_server_certificate_verification(true);
  8338. auto res = httplib_client.Get("/");
  8339. ASSERT_TRUE(res);
  8340. // Google may return 200 or 301 depending on various factors
  8341. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8342. res->status == StatusCode::MovedPermanently_301);
  8343. }
  8344. TEST(SSLClientTest, ServerNameIndication_Online) {
  8345. auto host = "httpbingo.org";
  8346. auto path = std::string{"/get"};
  8347. SSLClient cli(host, 443);
  8348. auto res = cli.Get(path);
  8349. ASSERT_TRUE(res);
  8350. ASSERT_EQ(StatusCode::OK_200, res->status);
  8351. }
  8352. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8353. // Use a site that will cause SSL verification failure due to self-signed cert
  8354. SSLClient cli("self-signed.badssl.com", 443);
  8355. cli.enable_server_certificate_verification(true);
  8356. auto res = cli.Get("/");
  8357. ASSERT_TRUE(!res);
  8358. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8359. // Verify backend error is captured for SSLServerVerification
  8360. // This occurs when certificate verification fails
  8361. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8362. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8363. EXPECT_NE(0UL, res.ssl_backend_error());
  8364. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8365. // For OpenSSL, ssl_error is 0 for verification errors
  8366. EXPECT_EQ(0, res.ssl_error());
  8367. #if !defined(_WIN32) || \
  8368. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8369. // On non-Windows or when Windows Schannel is disabled, the error comes
  8370. // from OpenSSL's verification
  8371. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8372. res.ssl_backend_error());
  8373. #endif
  8374. #endif
  8375. }
  8376. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8377. // Use a site where hostname doesn't match the certificate
  8378. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8379. SSLClient cli("wrong.host.badssl.com", 443);
  8380. cli.enable_server_certificate_verification(true);
  8381. cli.enable_server_hostname_verification(true);
  8382. auto res = cli.Get("/");
  8383. ASSERT_TRUE(!res);
  8384. // The error type depends on when hostname verification occurs:
  8385. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8386. // - Mbed TLS: SSLServerVerification (during handshake)
  8387. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8388. res.error() == Error::SSLServerVerification);
  8389. // Verify backend error is captured for hostname verification failure
  8390. EXPECT_NE(0UL, res.ssl_backend_error());
  8391. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8392. // For OpenSSL, ssl_error is 0 for verification errors
  8393. EXPECT_EQ(0, res.ssl_error());
  8394. #if !defined(_WIN32) || \
  8395. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8396. // On non-Windows or when Windows Schannel is disabled, the error comes
  8397. // from OpenSSL's hostname verification
  8398. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8399. res.ssl_backend_error());
  8400. #endif
  8401. #endif
  8402. }
  8403. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8404. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8405. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8406. SSLClient cli("www.google.com", 443);
  8407. cli.enable_server_certificate_verification(true);
  8408. auto res = cli.Get("/");
  8409. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8410. }
  8411. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8412. SSLClient cli("www.google.com", 443);
  8413. cli.enable_server_certificate_verification(true);
  8414. cli.enable_windows_certificate_verification(false);
  8415. auto res = cli.Get("/");
  8416. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8417. }
  8418. #endif
  8419. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8420. Client cli("https://google.com");
  8421. auto res = cli.Get("/");
  8422. ASSERT_TRUE(res);
  8423. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8424. }
  8425. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8426. SSLClient cli("google.com");
  8427. cli.set_ca_cert_path(CA_CERT_FILE);
  8428. auto res = cli.Get("/");
  8429. ASSERT_TRUE(res);
  8430. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8431. }
  8432. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8433. SSLClient cli("google.com");
  8434. cli.enable_server_certificate_verification(true);
  8435. cli.set_ca_cert_path("hello");
  8436. auto res = cli.Get("/");
  8437. ASSERT_TRUE(!res);
  8438. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8439. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8440. // should be set
  8441. EXPECT_EQ(0, res.ssl_error());
  8442. // Verify backend error is captured for SSLLoadingCerts
  8443. // This error occurs when loading CA certificates fails
  8444. EXPECT_NE(0UL, res.ssl_backend_error());
  8445. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8446. // OpenSSL specific error codes:
  8447. // > openssl errstr 0x80000002
  8448. // error:80000002:system library::No such file or directory
  8449. // > openssl errstr 0xA000126
  8450. // error:0A000126:SSL routines::unexpected eof while reading
  8451. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8452. res.ssl_backend_error() == 0xA000126);
  8453. #endif
  8454. }
  8455. TEST(SSLClientTest, ServerCertificateVerification4) {
  8456. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8457. ASSERT_TRUE(svr.is_valid());
  8458. svr.Get("/test", [&](const Request &, Response &res) {
  8459. res.set_content("test", "text/plain");
  8460. svr.stop();
  8461. ASSERT_TRUE(true);
  8462. });
  8463. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8464. auto se = detail::scope_exit([&] {
  8465. t.join();
  8466. ASSERT_FALSE(svr.is_running());
  8467. });
  8468. svr.wait_until_ready();
  8469. SSLClient cli("127.0.0.1", PORT);
  8470. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8471. cli.enable_server_certificate_verification(true);
  8472. cli.set_connection_timeout(30);
  8473. auto res = cli.Get("/test");
  8474. ASSERT_TRUE(res);
  8475. ASSERT_EQ(StatusCode::OK_200, res->status);
  8476. }
  8477. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8478. std::string cert;
  8479. read_file(CA_CERT_FILE, cert);
  8480. SSLClient cli("google.com");
  8481. cli.load_ca_cert_store(cert.data(), cert.size());
  8482. const auto res = cli.Get("/");
  8483. ASSERT_TRUE(res);
  8484. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8485. }
  8486. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8487. // clang-format off
  8488. static constexpr char cert[] =
  8489. "GlobalSign Root CA\n"
  8490. "==================\n"
  8491. "-----BEGIN CERTIFICATE-----\n"
  8492. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8493. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8494. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8495. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8496. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8497. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8498. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8499. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8500. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8501. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8502. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8503. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8504. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8505. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8506. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8507. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8508. "-----END CERTIFICATE-----\n";
  8509. // clang-format on
  8510. SSLClient cli("google.com");
  8511. cli.load_ca_cert_store(cert, sizeof(cert));
  8512. const auto res = cli.Get("/");
  8513. ASSERT_TRUE(res);
  8514. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8515. }
  8516. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8517. SSLClient cli("www.youtube.com");
  8518. cli.set_ca_cert_path(CA_CERT_FILE);
  8519. cli.enable_server_certificate_verification(true);
  8520. cli.set_follow_location(true);
  8521. auto res = cli.Get("/");
  8522. ASSERT_TRUE(res);
  8523. ASSERT_EQ(StatusCode::OK_200, res->status);
  8524. }
  8525. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8526. SSLClient cli("wWw.YouTube.Com");
  8527. cli.set_ca_cert_path(CA_CERT_FILE);
  8528. cli.enable_server_certificate_verification(true);
  8529. cli.enable_server_hostname_verification(true);
  8530. cli.set_follow_location(true);
  8531. auto res = cli.Get("/");
  8532. ASSERT_TRUE(res);
  8533. ASSERT_EQ(StatusCode::OK_200, res->status);
  8534. }
  8535. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8536. SSLClient cli("gOoGlE.COm");
  8537. cli.enable_server_certificate_verification(true);
  8538. cli.enable_server_hostname_verification(true);
  8539. cli.set_follow_location(true);
  8540. auto res = cli.Get("/");
  8541. ASSERT_TRUE(res);
  8542. ASSERT_EQ(StatusCode::OK_200, res->status);
  8543. }
  8544. TEST(SSLClientTest, Issue2004_Online) {
  8545. Client client("https://google.com");
  8546. client.set_follow_location(true);
  8547. auto res = client.Get("/");
  8548. ASSERT_TRUE(res);
  8549. ASSERT_EQ(StatusCode::OK_200, res->status);
  8550. auto body = res->body;
  8551. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8552. }
  8553. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8554. // Create SSLClient with invalid cert/key to make is_valid() return false
  8555. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8556. "nonexistent_key.pem");
  8557. // is_valid() should be false due to cert loading failure
  8558. ASSERT_FALSE(cli.is_valid());
  8559. auto res = cli.Get("/");
  8560. ASSERT_FALSE(res);
  8561. EXPECT_EQ(Error::SSLConnection, res.error());
  8562. }
  8563. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8564. // Test for Issue #2251: SSL error not properly reported when client cert
  8565. // and key paths are swapped or mismatched
  8566. // This simulates the scenario where user accidentally swaps the cert and key
  8567. // files
  8568. // Using client cert file as private key and vice versa (completely wrong)
  8569. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8570. // Should fail validation due to cert/key mismatch
  8571. ASSERT_FALSE(cli.is_valid());
  8572. // Attempt to make a request should fail with proper error
  8573. auto res = cli.Get("/");
  8574. ASSERT_FALSE(res);
  8575. EXPECT_EQ(Error::SSLConnection, res.error());
  8576. // SSL error should be recorded in the Result object (this is the key fix for
  8577. // Issue #2251)
  8578. auto backend_error = res.ssl_backend_error();
  8579. EXPECT_NE(0u, backend_error);
  8580. }
  8581. // Tests cert/key mismatch detection at the TLS context level
  8582. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8583. // Test that using mismatched cert/key causes connection failure.
  8584. // We verify this at the SSLClient level rather than through internal
  8585. // TLS API functions.
  8586. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8587. cli.enable_server_certificate_verification(false);
  8588. cli.set_connection_timeout(2);
  8589. // The mismatch should cause a connection or handshake error
  8590. auto res = cli.Get("/test");
  8591. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8592. // Either way, the request should fail
  8593. EXPECT_FALSE(res);
  8594. }
  8595. #endif
  8596. #if 0
  8597. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8598. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8599. ASSERT_TRUE(cli != nullptr);
  8600. cli->set_address_family(AF_INET6);
  8601. cli->set_interface("en0");
  8602. auto res = cli->Get("/get");
  8603. ASSERT_TRUE(res);
  8604. ASSERT_EQ(StatusCode::OK_200, res->status);
  8605. }
  8606. #endif
  8607. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8608. #ifdef CPPHTTPLIB_SSL_ENABLED
  8609. void ClientCertPresent(
  8610. const std::string &client_cert_file,
  8611. const std::string &client_private_key_file,
  8612. const std::string &client_encrypted_private_key_pass = std::string()) {
  8613. using namespace httplib::tls;
  8614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8615. CLIENT_CA_CERT_DIR);
  8616. ASSERT_TRUE(svr.is_valid());
  8617. svr.Get("/test", [&](const Request &req, Response &res) {
  8618. res.set_content("test", "text/plain");
  8619. auto cert = req.peer_cert();
  8620. ASSERT_TRUE(static_cast<bool>(cert));
  8621. std::string common_name = cert.subject_cn();
  8622. EXPECT_EQ("Common Name", common_name);
  8623. });
  8624. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8625. auto se = detail::scope_exit([&] {
  8626. svr.stop();
  8627. t.join();
  8628. ASSERT_FALSE(svr.is_running());
  8629. });
  8630. svr.wait_until_ready();
  8631. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8632. client_encrypted_private_key_pass);
  8633. cli.enable_server_certificate_verification(false);
  8634. cli.set_connection_timeout(30);
  8635. auto res = cli.Get("/test");
  8636. ASSERT_TRUE(res);
  8637. ASSERT_EQ(StatusCode::OK_200, res->status);
  8638. }
  8639. TEST(SSLClientServerTest, ClientCertPresent) {
  8640. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8641. }
  8642. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8643. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8644. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8645. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8646. }
  8647. // PEM memory-based constructor tests (works with all TLS backends)
  8648. void PemMemoryClientCertPresent(
  8649. const std::string &client_cert_file,
  8650. const std::string &client_private_key_file,
  8651. const std::string &client_encrypted_private_key_pass = std::string()) {
  8652. // Read PEM files into memory
  8653. std::string server_cert_pem, server_key_pem;
  8654. std::string client_ca_pem;
  8655. std::string client_cert_pem, client_key_pem;
  8656. read_file(SERVER_CERT_FILE, server_cert_pem);
  8657. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8658. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8659. read_file(client_cert_file, client_cert_pem);
  8660. read_file(client_private_key_file, client_key_pem);
  8661. // Create server with PEM memory
  8662. SSLServer::PemMemory server_pem = {
  8663. server_cert_pem.c_str(),
  8664. server_cert_pem.size(),
  8665. server_key_pem.c_str(),
  8666. server_key_pem.size(),
  8667. client_ca_pem.c_str(),
  8668. client_ca_pem.size(),
  8669. nullptr // no password for server key
  8670. };
  8671. SSLServer svr(server_pem);
  8672. ASSERT_TRUE(svr.is_valid());
  8673. svr.Get("/test", [&](const Request &, Response &res) {
  8674. res.set_content("test", "text/plain");
  8675. });
  8676. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8677. auto se = detail::scope_exit([&] {
  8678. svr.stop();
  8679. t.join();
  8680. ASSERT_FALSE(svr.is_running());
  8681. });
  8682. svr.wait_until_ready();
  8683. // Create client with PEM memory
  8684. const char *password = client_encrypted_private_key_pass.empty()
  8685. ? nullptr
  8686. : client_encrypted_private_key_pass.c_str();
  8687. SSLClient::PemMemory client_pem = {
  8688. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8689. client_key_pem.size(), password};
  8690. SSLClient cli(HOST, PORT, client_pem);
  8691. cli.enable_server_certificate_verification(false);
  8692. cli.set_connection_timeout(30);
  8693. auto res = cli.Get("/test");
  8694. ASSERT_TRUE(res);
  8695. ASSERT_EQ(StatusCode::OK_200, res->status);
  8696. }
  8697. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8698. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8699. }
  8700. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8701. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8702. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8703. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8704. }
  8705. TEST(SSLClientServerTest, ClientCertMissing) {
  8706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8707. CLIENT_CA_CERT_DIR);
  8708. ASSERT_TRUE(svr.is_valid());
  8709. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8710. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8711. auto se = detail::scope_exit([&] {
  8712. svr.stop();
  8713. t.join();
  8714. ASSERT_FALSE(svr.is_running());
  8715. });
  8716. svr.wait_until_ready();
  8717. SSLClient cli(HOST, PORT);
  8718. cli.set_connection_timeout(30);
  8719. auto res = cli.Get("/test");
  8720. ASSERT_TRUE(!res);
  8721. // When client cert is missing and server requires it, connection fails
  8722. // Error type depends on backend implementation
  8723. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8724. res.error() == Error::SSLConnection);
  8725. // Verify backend error is captured
  8726. // Note: This test may have different error codes depending on the exact
  8727. // verification failure
  8728. EXPECT_NE(0UL, res.ssl_backend_error());
  8729. }
  8730. TEST(SSLClientServerTest, TrustDirOptional) {
  8731. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8732. ASSERT_TRUE(svr.is_valid());
  8733. svr.Get("/test", [&](const Request &, Response &res) {
  8734. res.set_content("test", "text/plain");
  8735. });
  8736. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8737. auto se = detail::scope_exit([&] {
  8738. svr.stop();
  8739. t.join();
  8740. ASSERT_FALSE(svr.is_running());
  8741. });
  8742. svr.wait_until_ready();
  8743. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8744. cli.enable_server_certificate_verification(false);
  8745. cli.set_connection_timeout(30);
  8746. auto res = cli.Get("/test");
  8747. ASSERT_TRUE(res);
  8748. ASSERT_EQ(StatusCode::OK_200, res->status);
  8749. }
  8750. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8751. class NoListenSSLServer : public SSLServer {
  8752. public:
  8753. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8754. const char *client_ca_cert_file_path,
  8755. const char *client_ca_cert_dir_path = nullptr)
  8756. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8757. client_ca_cert_dir_path),
  8758. stop_(false) {}
  8759. std::atomic_bool stop_;
  8760. private:
  8761. bool process_and_close_socket(socket_t /*sock*/) override {
  8762. // Don't create SSL context
  8763. while (!stop_.load()) {
  8764. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8765. }
  8766. return true;
  8767. }
  8768. };
  8769. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8770. CLIENT_CA_CERT_FILE);
  8771. ASSERT_TRUE(svr.is_valid());
  8772. svr.Get("/test", [&](const Request &, Response &res) {
  8773. res.set_content("test", "text/plain");
  8774. });
  8775. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8776. auto se = detail::scope_exit([&] {
  8777. svr.stop_ = true;
  8778. svr.stop();
  8779. t.join();
  8780. ASSERT_FALSE(svr.is_running());
  8781. });
  8782. svr.wait_until_ready();
  8783. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8784. cli.enable_server_certificate_verification(false);
  8785. cli.set_connection_timeout(1);
  8786. auto res = cli.Get("/test");
  8787. ASSERT_TRUE(!res);
  8788. EXPECT_EQ(Error::SSLConnection, res.error());
  8789. // Timeout results in WantRead error code (maps to backend-specific value)
  8790. EXPECT_NE(0, res.ssl_error());
  8791. }
  8792. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8793. // Test SSLServer with client certificate verification using the standard
  8794. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8796. CLIENT_CA_CERT_DIR);
  8797. ASSERT_TRUE(svr.is_valid());
  8798. svr.Get("/test", [&](const Request &req, Response &res) {
  8799. res.set_content("test", "text/plain");
  8800. auto cert = req.peer_cert();
  8801. ASSERT_TRUE(static_cast<bool>(cert));
  8802. auto common_name = cert.subject_cn();
  8803. EXPECT_EQ("Common Name", common_name);
  8804. });
  8805. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8806. auto se = detail::scope_exit([&] {
  8807. svr.stop();
  8808. t.join();
  8809. ASSERT_FALSE(svr.is_running());
  8810. });
  8811. svr.wait_until_ready();
  8812. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8813. cli.enable_server_certificate_verification(false);
  8814. cli.set_connection_timeout(30);
  8815. auto res = cli.Get("/test");
  8816. ASSERT_TRUE(res);
  8817. ASSERT_EQ(StatusCode::OK_200, res->status);
  8818. }
  8819. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8820. // Verifies that wildcard matching and exact matching work consistently
  8821. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8822. using namespace httplib::tls;
  8823. // We need a running server to test against
  8824. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8825. ASSERT_TRUE(svr.is_valid());
  8826. svr.Get("/test", [](const Request &, Response &res) {
  8827. res.set_content("ok", "text/plain");
  8828. });
  8829. thread t([&]() { svr.listen(HOST, PORT); });
  8830. auto se = detail::scope_exit([&] {
  8831. svr.stop();
  8832. t.join();
  8833. });
  8834. svr.wait_until_ready();
  8835. bool verify_callback_called = false;
  8836. bool verify_result_wrong = false;
  8837. SSLClient cli(HOST, PORT);
  8838. cli.enable_server_certificate_verification(true);
  8839. cli.set_ca_cert_path(CA_CERT_FILE);
  8840. cli.set_connection_timeout(5);
  8841. // Note: Test certificate has CN="Common Name", not "localhost"
  8842. bool verify_result_cn = false;
  8843. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8844. verify_callback_called = true;
  8845. if (!ctx.cert) return false;
  8846. // Test 1: "Common Name" should match (our test server cert CN)
  8847. verify_result_cn = ctx.check_hostname("Common Name");
  8848. // Test 2: wrong hostname should not match
  8849. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8850. return true; // Accept for the purpose of this test
  8851. });
  8852. auto res = cli.Get("/test");
  8853. // The request may succeed or fail depending on cert configuration
  8854. // but the callback should have been called
  8855. ASSERT_TRUE(verify_callback_called)
  8856. << "Verify callback should have been called";
  8857. // CN="Common Name" should match our test certificate
  8858. EXPECT_TRUE(verify_result_cn)
  8859. << "verify_hostname should match 'Common Name' (certificate CN)";
  8860. // Wrong hostname should not match
  8861. EXPECT_FALSE(verify_result_wrong)
  8862. << "verify_hostname should not match 'wronghost.example.com'";
  8863. }
  8864. #endif
  8865. // mbedTLS-specific callback constructor test
  8866. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8867. #ifdef CPPHTTPLIB_SSL_ENABLED
  8868. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8870. ASSERT_TRUE(svr.is_valid());
  8871. // Set up a handler to verify client certificate is present
  8872. bool client_cert_verified = false;
  8873. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8874. // Verify that client certificate was provided
  8875. client_cert_verified = true;
  8876. res.set_content("success", "text/plain");
  8877. });
  8878. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8879. auto se = detail::scope_exit([&] {
  8880. svr.stop();
  8881. t.join();
  8882. ASSERT_FALSE(svr.is_running());
  8883. });
  8884. svr.wait_until_ready();
  8885. // Client with certificate
  8886. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8887. cli.enable_server_certificate_verification(false);
  8888. cli.set_connection_timeout(30);
  8889. auto res = cli.Get("/test");
  8890. ASSERT_TRUE(res);
  8891. ASSERT_EQ(StatusCode::OK_200, res->status);
  8892. ASSERT_TRUE(client_cert_verified);
  8893. EXPECT_EQ("success", res->body);
  8894. }
  8895. #endif
  8896. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8897. // backends
  8898. #ifdef CPPHTTPLIB_SSL_ENABLED
  8899. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8900. using namespace httplib::tls;
  8901. // Test that when client CA cert file is provided,
  8902. // the server properly requests and validates client certificates
  8903. // Create a server with client authentication
  8904. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8905. ASSERT_TRUE(svr.is_valid());
  8906. bool handler_called = false;
  8907. svr.Get("/test", [&](const Request &req, Response &res) {
  8908. handler_called = true;
  8909. // Verify that a client certificate was provided
  8910. auto cert = req.peer_cert();
  8911. ASSERT_TRUE(static_cast<bool>(cert));
  8912. // Get the issuer name
  8913. std::string issuer_str = cert.issuer_name();
  8914. ASSERT_FALSE(issuer_str.empty());
  8915. // The client certificate should be issued by our test CA
  8916. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8917. res.set_content("authenticated", "text/plain");
  8918. });
  8919. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8920. auto se = detail::scope_exit([&] {
  8921. svr.stop();
  8922. t.join();
  8923. ASSERT_FALSE(svr.is_running());
  8924. });
  8925. svr.wait_until_ready();
  8926. // Connect with a client certificate issued by the CA
  8927. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8928. cli.enable_server_certificate_verification(false);
  8929. cli.set_connection_timeout(30);
  8930. auto res = cli.Get("/test");
  8931. ASSERT_TRUE(res);
  8932. ASSERT_EQ(StatusCode::OK_200, res->status);
  8933. ASSERT_TRUE(handler_called);
  8934. EXPECT_EQ("authenticated", res->body);
  8935. }
  8936. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8937. using namespace httplib::tls;
  8938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8939. ASSERT_TRUE(svr.is_valid());
  8940. svr.Get("/test", [](const Request &, Response &res) {
  8941. res.set_content("ok", "text/plain");
  8942. });
  8943. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8944. auto se = detail::scope_exit([&] {
  8945. svr.stop();
  8946. t.join();
  8947. });
  8948. svr.wait_until_ready();
  8949. SSLClient cli(HOST, PORT);
  8950. cli.enable_server_certificate_verification(false);
  8951. cli.set_connection_timeout(30);
  8952. bool cert_checked = false;
  8953. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8954. if (ctx.cert) {
  8955. auto sans = ctx.sans();
  8956. // Test certificate may or may not have SANs - just verify the API
  8957. // works If SANs exist, verify the types are valid
  8958. for (const auto &san : sans) {
  8959. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8960. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8961. san.type == SanType::OTHER);
  8962. EXPECT_FALSE(san.value.empty());
  8963. }
  8964. cert_checked = true;
  8965. }
  8966. return true;
  8967. });
  8968. auto res = cli.Get("/test");
  8969. ASSERT_TRUE(res);
  8970. EXPECT_TRUE(cert_checked);
  8971. }
  8972. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8973. using namespace httplib::tls;
  8974. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8975. ASSERT_TRUE(svr.is_valid());
  8976. svr.Get("/test", [](const Request &, Response &res) {
  8977. res.set_content("ok", "text/plain");
  8978. });
  8979. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8980. auto se = detail::scope_exit([&] {
  8981. svr.stop();
  8982. t.join();
  8983. });
  8984. svr.wait_until_ready();
  8985. SSLClient cli(HOST, PORT);
  8986. cli.enable_server_certificate_verification(false);
  8987. cli.set_connection_timeout(30);
  8988. bool validity_checked = false;
  8989. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8990. if (ctx.cert) {
  8991. time_t not_before = 0, not_after = 0;
  8992. bool result = ctx.validity(not_before, not_after);
  8993. EXPECT_TRUE(result);
  8994. // Verify that not_before < now < not_after for a valid cert
  8995. time_t now = time(nullptr);
  8996. EXPECT_LT(not_before, now);
  8997. EXPECT_GT(not_after, now);
  8998. validity_checked = true;
  8999. }
  9000. return true;
  9001. });
  9002. auto res = cli.Get("/test");
  9003. ASSERT_TRUE(res);
  9004. EXPECT_TRUE(validity_checked);
  9005. }
  9006. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9007. using namespace httplib::tls;
  9008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9009. ASSERT_TRUE(svr.is_valid());
  9010. svr.Get("/test", [](const Request &, Response &res) {
  9011. res.set_content("ok", "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. });
  9018. svr.wait_until_ready();
  9019. SSLClient cli(HOST, PORT);
  9020. cli.enable_server_certificate_verification(false);
  9021. cli.set_connection_timeout(30);
  9022. bool serial_checked = false;
  9023. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9024. if (ctx.cert) {
  9025. std::string serial = ctx.serial();
  9026. EXPECT_FALSE(serial.empty());
  9027. // Serial should be a hex string
  9028. for (char c : serial) {
  9029. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9030. (c >= 'a' && c <= 'f'));
  9031. }
  9032. serial_checked = true;
  9033. }
  9034. return true;
  9035. });
  9036. auto res = cli.Get("/test");
  9037. ASSERT_TRUE(res);
  9038. EXPECT_TRUE(serial_checked);
  9039. }
  9040. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9041. // Test 1: Valid CA file - no error should be recorded
  9042. {
  9043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9044. CLIENT_CA_CERT_FILE);
  9045. ASSERT_TRUE(svr.is_valid());
  9046. // With valid setup, last_ssl_error should be 0
  9047. EXPECT_EQ(0, svr.ssl_last_error());
  9048. }
  9049. // Test 2: Invalid CA file content
  9050. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9051. {
  9052. // Create a temporary file with completely invalid content
  9053. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9054. {
  9055. std::ofstream ofs(temp_invalid_ca);
  9056. ofs << "This is not a certificate file at all\n";
  9057. ofs << "Just plain text content\n";
  9058. }
  9059. // Create server with invalid CA file
  9060. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9061. // Clean up temporary file
  9062. std::remove(temp_invalid_ca);
  9063. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9064. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9065. // Note: SSL_CTX_load_verify_locations typically fails first,
  9066. // but our error handling code path is still exercised
  9067. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9068. }
  9069. }
  9070. TEST(VerifyCallbackTest, VerifyContextFields) {
  9071. using namespace httplib::tls;
  9072. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9073. ASSERT_TRUE(svr.is_valid());
  9074. svr.Get("/test", [](const Request &, Response &res) {
  9075. res.set_content("ok", "text/plain");
  9076. });
  9077. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9078. auto se = detail::scope_exit([&] {
  9079. svr.stop();
  9080. t.join();
  9081. });
  9082. svr.wait_until_ready();
  9083. SSLClient cli(HOST, PORT);
  9084. cli.enable_server_certificate_verification(false);
  9085. cli.set_connection_timeout(30);
  9086. int callback_count = 0;
  9087. bool saw_leaf_cert = false;
  9088. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9089. if (ctx.cert) {
  9090. callback_count++;
  9091. // We should see at least one certificate (the leaf)
  9092. std::string cn = ctx.subject_cn();
  9093. if (!cn.empty()) { saw_leaf_cert = true; }
  9094. // Verify context fields are populated
  9095. EXPECT_NE(ctx.session, nullptr);
  9096. EXPECT_GE(ctx.depth, 0);
  9097. }
  9098. return true;
  9099. });
  9100. auto res = cli.Get("/test");
  9101. ASSERT_TRUE(res);
  9102. EXPECT_GT(callback_count, 0);
  9103. EXPECT_TRUE(saw_leaf_cert);
  9104. }
  9105. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9106. using httplib::tls::TlsError;
  9107. // Test that verify_error_to_string returns empty for success
  9108. std::string success_str = TlsError::verify_error_to_string(0);
  9109. EXPECT_TRUE(success_str.empty());
  9110. // Test that verify_error_to_string returns non-empty for error codes
  9111. // Using a common error code (certificate expired)
  9112. std::string error_str =
  9113. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9114. EXPECT_FALSE(error_str.empty());
  9115. }
  9116. TEST(SessionVerifierTest, CertificateAccepted) {
  9117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9118. ASSERT_TRUE(svr.is_valid());
  9119. svr.Get("/test", [](const Request &, Response &res) {
  9120. res.set_content("ok", "text/plain");
  9121. });
  9122. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9123. auto se = detail::scope_exit([&] {
  9124. svr.stop();
  9125. t.join();
  9126. });
  9127. svr.wait_until_ready();
  9128. SSLClient cli(HOST, PORT);
  9129. cli.enable_server_certificate_verification(false);
  9130. cli.set_connection_timeout(30);
  9131. bool callback_called = false;
  9132. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9133. EXPECT_NE(session, nullptr);
  9134. callback_called = true;
  9135. return SSLVerifierResponse::CertificateAccepted;
  9136. });
  9137. auto res = cli.Get("/test");
  9138. ASSERT_TRUE(res);
  9139. EXPECT_EQ(200, res->status);
  9140. EXPECT_TRUE(callback_called);
  9141. }
  9142. TEST(SessionVerifierTest, CertificateRejected) {
  9143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9144. ASSERT_TRUE(svr.is_valid());
  9145. svr.Get("/test", [](const Request &, Response &res) {
  9146. res.set_content("ok", "text/plain");
  9147. });
  9148. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9149. auto se = detail::scope_exit([&] {
  9150. svr.stop();
  9151. t.join();
  9152. });
  9153. svr.wait_until_ready();
  9154. SSLClient cli(HOST, PORT);
  9155. cli.enable_server_certificate_verification(false);
  9156. cli.set_connection_timeout(30);
  9157. bool callback_called = false;
  9158. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9159. EXPECT_NE(session, nullptr);
  9160. callback_called = true;
  9161. return SSLVerifierResponse::CertificateRejected;
  9162. });
  9163. auto res = cli.Get("/test");
  9164. EXPECT_FALSE(res);
  9165. EXPECT_TRUE(callback_called);
  9166. }
  9167. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9169. ASSERT_TRUE(svr.is_valid());
  9170. svr.Get("/test", [](const Request &, Response &res) {
  9171. res.set_content("ok", "text/plain");
  9172. });
  9173. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9174. auto se = detail::scope_exit([&] {
  9175. svr.stop();
  9176. t.join();
  9177. });
  9178. svr.wait_until_ready();
  9179. // NoDecisionMade with verification disabled should succeed (no default check)
  9180. SSLClient cli(HOST, PORT);
  9181. cli.enable_server_certificate_verification(false);
  9182. cli.set_connection_timeout(30);
  9183. bool callback_called = false;
  9184. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9185. EXPECT_NE(session, nullptr);
  9186. callback_called = true;
  9187. return SSLVerifierResponse::NoDecisionMade;
  9188. });
  9189. auto res = cli.Get("/test");
  9190. ASSERT_TRUE(res);
  9191. EXPECT_EQ(200, res->status);
  9192. EXPECT_TRUE(callback_called);
  9193. }
  9194. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9196. ASSERT_TRUE(svr.is_valid());
  9197. svr.Get("/test", [](const Request &, Response &res) {
  9198. res.set_content("ok", "text/plain");
  9199. });
  9200. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9201. auto se = detail::scope_exit([&] {
  9202. svr.stop();
  9203. t.join();
  9204. });
  9205. svr.wait_until_ready();
  9206. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9207. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9208. // so we only check that the request fails, not whether the callback was
  9209. // called.
  9210. SSLClient cli(HOST, PORT);
  9211. cli.enable_server_certificate_verification(true);
  9212. cli.set_connection_timeout(30);
  9213. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9214. EXPECT_NE(session, nullptr);
  9215. return SSLVerifierResponse::NoDecisionMade;
  9216. });
  9217. auto res = cli.Get("/test");
  9218. EXPECT_FALSE(res);
  9219. }
  9220. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9221. // Test SSL server using PemMemory constructor with client CA certificates
  9222. // Read PEM files
  9223. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9224. read_file(SERVER_CERT_FILE, server_cert_pem);
  9225. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9226. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9227. // Create SSLServer with PemMemory constructor including client CA
  9228. SSLServer::PemMemory server_pem = {
  9229. server_cert_pem.c_str(),
  9230. server_cert_pem.size(),
  9231. server_key_pem.c_str(),
  9232. server_key_pem.size(),
  9233. client_ca_pem.c_str(),
  9234. client_ca_pem.size(),
  9235. nullptr // no password for server key
  9236. };
  9237. SSLServer svr(server_pem);
  9238. ASSERT_TRUE(svr.is_valid());
  9239. // No SSL error should be recorded for valid setup
  9240. EXPECT_EQ(0, svr.ssl_last_error());
  9241. // Set up server endpoints
  9242. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9243. res.set_content("ok", "text/plain");
  9244. });
  9245. // Start server in a thread
  9246. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9247. svr.wait_until_ready();
  9248. // Connect with client certificate (using constructor with paths)
  9249. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9250. cli.enable_server_certificate_verification(false);
  9251. auto res = cli.Get("/test-pem-ca");
  9252. ASSERT_TRUE(res);
  9253. EXPECT_EQ(200, res->status);
  9254. EXPECT_EQ("ok", res->body);
  9255. svr.stop();
  9256. server_thread.join();
  9257. }
  9258. #endif
  9259. #ifdef _WIN32
  9260. TEST(CleanupTest, WSACleanup) {
  9261. int ret = WSACleanup();
  9262. ASSERT_EQ(0, ret);
  9263. }
  9264. #endif
  9265. #ifndef CPPHTTPLIB_SSL_ENABLED
  9266. TEST(NoSSLSupport, SimpleInterface) {
  9267. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9268. }
  9269. #endif
  9270. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9271. TEST(InvalidScheme, SimpleInterface) {
  9272. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9273. }
  9274. #endif
  9275. TEST(NoScheme, SimpleInterface) {
  9276. Client cli("yahoo.com:80");
  9277. ASSERT_TRUE(cli.is_valid());
  9278. }
  9279. TEST(SendAPI, SimpleInterface_Online) {
  9280. Client cli("http://yahoo.com");
  9281. Request req;
  9282. req.method = "GET";
  9283. req.path = "/";
  9284. auto res = cli.send(req);
  9285. ASSERT_TRUE(res);
  9286. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9287. }
  9288. TEST(SendAPI, WithParamsInRequest) {
  9289. Server svr;
  9290. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9291. EXPECT_TRUE(req.has_param("test"));
  9292. EXPECT_EQ("test_value", req.get_param_value("test"));
  9293. });
  9294. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9295. auto se = detail::scope_exit([&] {
  9296. svr.stop();
  9297. t.join();
  9298. ASSERT_FALSE(svr.is_running());
  9299. });
  9300. svr.wait_until_ready();
  9301. Client cli(HOST, PORT);
  9302. {
  9303. Request req;
  9304. req.method = "GET";
  9305. req.path = "/";
  9306. req.params.emplace("test", "test_value");
  9307. auto res = cli.send(req);
  9308. ASSERT_TRUE(res);
  9309. }
  9310. {
  9311. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9312. ASSERT_TRUE(res);
  9313. }
  9314. }
  9315. TEST(ClientImplMethods, GetSocketTest) {
  9316. httplib::Server svr;
  9317. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9318. res.status = StatusCode::OK_200;
  9319. });
  9320. auto port = svr.bind_to_any_port("127.0.0.1");
  9321. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9322. auto se = detail::scope_exit([&] {
  9323. svr.stop();
  9324. thread.join();
  9325. ASSERT_FALSE(svr.is_running());
  9326. });
  9327. svr.wait_until_ready();
  9328. {
  9329. httplib::Client cli("127.0.0.1", port);
  9330. cli.set_keep_alive(true);
  9331. // Use the behavior of cpp-httplib of opening the connection
  9332. // only when the first request happens. If that changes,
  9333. // this test would be obsolete.
  9334. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9335. // This also implicitly tests the server. But other tests would fail much
  9336. // earlier than this one to be considered.
  9337. auto res = cli.Get("/");
  9338. ASSERT_TRUE(res);
  9339. EXPECT_EQ(StatusCode::OK_200, res->status);
  9340. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9341. }
  9342. }
  9343. #ifdef CPPHTTPLIB_SSL_ENABLED
  9344. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9345. Client cli("http://yahoo.com");
  9346. auto res = cli.Get("/");
  9347. ASSERT_TRUE(res);
  9348. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9349. cli.set_follow_location(true);
  9350. res = cli.Get("/");
  9351. ASSERT_TRUE(res);
  9352. EXPECT_EQ(StatusCode::OK_200, res->status);
  9353. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9354. }
  9355. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9356. Client cli("https://yahoo.com");
  9357. auto res = cli.Get("/");
  9358. ASSERT_TRUE(res);
  9359. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9360. cli.set_follow_location(true);
  9361. res = cli.Get("/");
  9362. ASSERT_TRUE(res);
  9363. EXPECT_EQ(StatusCode::OK_200, res->status);
  9364. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9365. }
  9366. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9367. Client cli("https://yahoo.com");
  9368. auto res = cli.Get("/");
  9369. ASSERT_TRUE(res);
  9370. ASSERT_FALSE(!res);
  9371. ASSERT_TRUE(res);
  9372. ASSERT_FALSE(res == nullptr);
  9373. ASSERT_TRUE(res != nullptr);
  9374. EXPECT_EQ(Error::Success, res.error());
  9375. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9376. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9377. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9378. cli.set_follow_location(true);
  9379. res = cli.Get("/");
  9380. ASSERT_TRUE(res);
  9381. EXPECT_EQ(Error::Success, res.error());
  9382. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9383. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9384. EXPECT_EQ(StatusCode::OK_200, res->status);
  9385. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9386. }
  9387. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9388. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9389. Client cli("https://cdnjs.cloudflare.com");
  9390. auto res =
  9391. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9392. ASSERT_TRUE(res);
  9393. EXPECT_EQ(StatusCode::OK_200, res->status);
  9394. EXPECT_EQ(287630U, res->body.size());
  9395. EXPECT_EQ("application/javascript; charset=utf-8",
  9396. res->get_header_value("Content-Type"));
  9397. }
  9398. #endif
  9399. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9400. #undef REDIR_HOST // Silence compiler warning
  9401. #define REDIR_HOST "https://httpbingo.org"
  9402. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9403. Client cli(REDIR_HOST);
  9404. cli.set_follow_location(true);
  9405. auto res =
  9406. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9407. ASSERT_TRUE(res);
  9408. EXPECT_EQ(StatusCode::OK_200, res->status);
  9409. }
  9410. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9411. Client cli(REDIR_HOST);
  9412. cli.set_follow_location(true);
  9413. Params params;
  9414. params.emplace("url", "http://example.com");
  9415. params.emplace("status_code", "302");
  9416. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9417. ASSERT_TRUE(res);
  9418. EXPECT_EQ(StatusCode::OK_200, res->status);
  9419. }
  9420. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9421. Client cli(REDIR_HOST);
  9422. cli.set_follow_location(true);
  9423. Params params;
  9424. params.emplace("url", "http://example.com");
  9425. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9426. ASSERT_TRUE(res);
  9427. EXPECT_EQ(StatusCode::OK_200, res->status);
  9428. }
  9429. TEST(HttpToHttpsRedirectTest, CertFile) {
  9430. auto ssl_port = PORT + 1;
  9431. Server svr;
  9432. ASSERT_TRUE(svr.is_valid());
  9433. svr.Get("/index", [&](const Request &, Response &res) {
  9434. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9435. "/index");
  9436. svr.stop();
  9437. });
  9438. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9439. ASSERT_TRUE(ssl_svr.is_valid());
  9440. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9441. res.set_content("test", "text/plain");
  9442. ssl_svr.stop();
  9443. });
  9444. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9445. thread t2 =
  9446. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9447. auto se = detail::scope_exit([&] {
  9448. t2.join();
  9449. t.join();
  9450. ASSERT_FALSE(svr.is_running());
  9451. });
  9452. svr.wait_until_ready();
  9453. ssl_svr.wait_until_ready();
  9454. Client cli("127.0.0.1", PORT);
  9455. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9456. cli.enable_server_certificate_verification(true);
  9457. cli.set_follow_location(true);
  9458. cli.set_connection_timeout(30);
  9459. auto res = cli.Get("/index");
  9460. ASSERT_TRUE(res);
  9461. ASSERT_EQ(StatusCode::OK_200, res->status);
  9462. }
  9463. TEST(SSLClientRedirectTest, CertFile) {
  9464. auto ssl_port = PORT + 1;
  9465. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9466. ASSERT_TRUE(ssl_svr1.is_valid());
  9467. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9468. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9469. "/index");
  9470. ssl_svr1.stop();
  9471. });
  9472. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9473. ASSERT_TRUE(ssl_svr2.is_valid());
  9474. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9475. res.set_content("test", "text/plain");
  9476. ssl_svr2.stop();
  9477. });
  9478. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9479. thread t2 =
  9480. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9481. auto se = detail::scope_exit([&] {
  9482. t2.join();
  9483. t.join();
  9484. ASSERT_FALSE(ssl_svr1.is_running());
  9485. });
  9486. ssl_svr1.wait_until_ready();
  9487. ssl_svr2.wait_until_ready();
  9488. SSLClient cli("127.0.0.1", PORT);
  9489. std::string cert;
  9490. read_file(SERVER_CERT2_FILE, cert);
  9491. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9492. cli.enable_server_certificate_verification(true);
  9493. cli.set_follow_location(true);
  9494. cli.set_connection_timeout(30);
  9495. auto res = cli.Get("/index");
  9496. ASSERT_TRUE(res);
  9497. ASSERT_EQ(StatusCode::OK_200, res->status);
  9498. }
  9499. #endif
  9500. #ifdef CPPHTTPLIB_SSL_ENABLED
  9501. // Test that set_ca_cert_store() skips system certs (consistent with
  9502. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9503. // should be trusted - system certs should NOT be loaded.
  9504. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9505. // Load a specific cert that is NOT a system CA cert
  9506. std::string cert;
  9507. read_file(SERVER_CERT2_FILE, cert);
  9508. SSLClient cli("google.com");
  9509. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9510. cli.enable_server_certificate_verification(true);
  9511. // This should FAIL because:
  9512. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9513. // 2. System certs should NOT be loaded when custom store is set
  9514. // If system certs WERE loaded, this would succeed
  9515. auto res = cli.Get("/");
  9516. ASSERT_FALSE(res);
  9517. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9518. }
  9519. TEST(MultipartFormDataTest, LargeData) {
  9520. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9521. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9522. const ContentReader &content_reader) {
  9523. if (req.is_multipart_form_data()) {
  9524. std::vector<FormData> items;
  9525. content_reader(
  9526. [&](const FormData &file) {
  9527. items.push_back(file);
  9528. return true;
  9529. },
  9530. [&](const char *data, size_t data_length) {
  9531. items.back().content.append(data, data_length);
  9532. return true;
  9533. });
  9534. EXPECT_TRUE(std::string(items[0].name) == "document");
  9535. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9536. EXPECT_TRUE(items[0].filename == "2MB_data");
  9537. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9538. EXPECT_TRUE(items[1].name == "hello");
  9539. EXPECT_TRUE(items[1].content == "world");
  9540. EXPECT_TRUE(items[1].filename == "");
  9541. EXPECT_TRUE(items[1].content_type == "");
  9542. } else {
  9543. std::string body;
  9544. content_reader([&](const char *data, size_t data_length) {
  9545. body.append(data, data_length);
  9546. return true;
  9547. });
  9548. }
  9549. });
  9550. auto port = svr.bind_to_any_port(HOST);
  9551. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9552. auto se = detail::scope_exit([&] {
  9553. svr.stop();
  9554. t.join();
  9555. ASSERT_FALSE(svr.is_running());
  9556. });
  9557. svr.wait_until_ready();
  9558. {
  9559. std::string data(1024 * 1024 * 2, '.');
  9560. std::stringstream buffer;
  9561. buffer << data;
  9562. SSLClient cli(HOST, port);
  9563. cli.enable_server_certificate_verification(false);
  9564. UploadFormDataItems items{
  9565. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9566. {"hello", "world", "", ""},
  9567. };
  9568. auto res = cli.Post("/post", items);
  9569. ASSERT_TRUE(res);
  9570. ASSERT_EQ(StatusCode::OK_200, res->status);
  9571. }
  9572. }
  9573. TEST(MultipartFormDataTest, DataProviderItems) {
  9574. std::random_device seed_gen;
  9575. std::mt19937 random(seed_gen());
  9576. std::string rand1;
  9577. rand1.resize(1000);
  9578. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9579. std::string rand2;
  9580. rand2.resize(3000);
  9581. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9583. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9584. const ContentReader &content_reader) {
  9585. ASSERT_FALSE(req.is_multipart_form_data());
  9586. std::string body;
  9587. content_reader([&](const char *data, size_t data_length) {
  9588. body.append(data, data_length);
  9589. return true;
  9590. });
  9591. EXPECT_EQ(body, "");
  9592. });
  9593. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9594. const ContentReader &content_reader) {
  9595. ASSERT_TRUE(req.is_multipart_form_data());
  9596. std::vector<FormData> items;
  9597. content_reader(
  9598. [&](const FormData &file) {
  9599. items.push_back(file);
  9600. return true;
  9601. },
  9602. [&](const char *data, size_t data_length) {
  9603. items.back().content.append(data, data_length);
  9604. return true;
  9605. });
  9606. ASSERT_TRUE(items.size() == 2);
  9607. EXPECT_EQ(std::string(items[0].name), "name1");
  9608. EXPECT_EQ(items[0].content, "Testing123");
  9609. EXPECT_EQ(items[0].filename, "filename1");
  9610. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9611. EXPECT_EQ(items[1].name, "name2");
  9612. EXPECT_EQ(items[1].content, "Testing456");
  9613. EXPECT_EQ(items[1].filename, "");
  9614. EXPECT_EQ(items[1].content_type, "");
  9615. });
  9616. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9617. const ContentReader &content_reader) {
  9618. ASSERT_TRUE(req.is_multipart_form_data());
  9619. std::vector<FormData> items;
  9620. content_reader(
  9621. [&](const FormData &file) {
  9622. items.push_back(file);
  9623. return true;
  9624. },
  9625. [&](const char *data, size_t data_length) {
  9626. items.back().content.append(data, data_length);
  9627. return true;
  9628. });
  9629. ASSERT_TRUE(items.size() == 2);
  9630. EXPECT_EQ(items[0].name, "name3");
  9631. EXPECT_EQ(items[0].content, rand1);
  9632. EXPECT_EQ(items[0].filename, "filename3");
  9633. EXPECT_EQ(items[0].content_type, "");
  9634. EXPECT_EQ(items[1].name, "name4");
  9635. EXPECT_EQ(items[1].content, rand2);
  9636. EXPECT_EQ(items[1].filename, "filename4");
  9637. EXPECT_EQ(items[1].content_type, "");
  9638. });
  9639. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9640. const ContentReader &content_reader) {
  9641. ASSERT_TRUE(req.is_multipart_form_data());
  9642. std::vector<FormData> items;
  9643. content_reader(
  9644. [&](const FormData &file) {
  9645. items.push_back(file);
  9646. return true;
  9647. },
  9648. [&](const char *data, size_t data_length) {
  9649. items.back().content.append(data, data_length);
  9650. return true;
  9651. });
  9652. ASSERT_TRUE(items.size() == 4);
  9653. EXPECT_EQ(std::string(items[0].name), "name1");
  9654. EXPECT_EQ(items[0].content, "Testing123");
  9655. EXPECT_EQ(items[0].filename, "filename1");
  9656. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9657. EXPECT_EQ(items[1].name, "name2");
  9658. EXPECT_EQ(items[1].content, "Testing456");
  9659. EXPECT_EQ(items[1].filename, "");
  9660. EXPECT_EQ(items[1].content_type, "");
  9661. EXPECT_EQ(items[2].name, "name3");
  9662. EXPECT_EQ(items[2].content, rand1);
  9663. EXPECT_EQ(items[2].filename, "filename3");
  9664. EXPECT_EQ(items[2].content_type, "");
  9665. EXPECT_EQ(items[3].name, "name4");
  9666. EXPECT_EQ(items[3].content, rand2);
  9667. EXPECT_EQ(items[3].filename, "filename4");
  9668. EXPECT_EQ(items[3].content_type, "");
  9669. });
  9670. auto port = svr.bind_to_any_port("localhost");
  9671. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9672. auto se = detail::scope_exit([&] {
  9673. svr.stop();
  9674. t.join();
  9675. ASSERT_FALSE(svr.is_running());
  9676. });
  9677. svr.wait_until_ready();
  9678. {
  9679. SSLClient cli("localhost", port);
  9680. cli.enable_server_certificate_verification(false);
  9681. UploadFormDataItems items{
  9682. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9683. {"name2", "Testing456", "", ""}, // not a file
  9684. };
  9685. {
  9686. auto res = cli.Post("/post-none", {}, {}, {});
  9687. ASSERT_TRUE(res);
  9688. ASSERT_EQ(StatusCode::OK_200, res->status);
  9689. }
  9690. FormDataProviderItems providers;
  9691. {
  9692. auto res =
  9693. cli.Post("/post-items", {}, items, providers); // empty providers
  9694. ASSERT_TRUE(res);
  9695. ASSERT_EQ(StatusCode::OK_200, res->status);
  9696. }
  9697. providers.push_back({"name3",
  9698. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9699. // test the offset is given correctly at each step
  9700. if (!offset)
  9701. sink.os.write(rand1.data(), 30);
  9702. else if (offset == 30)
  9703. sink.os.write(rand1.data() + 30, 300);
  9704. else if (offset == 330)
  9705. sink.os.write(rand1.data() + 330, 670);
  9706. else if (offset == rand1.size())
  9707. sink.done();
  9708. return true;
  9709. },
  9710. "filename3",
  9711. {}});
  9712. providers.push_back({"name4",
  9713. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9714. // test the offset is given correctly at each step
  9715. if (!offset)
  9716. sink.os.write(rand2.data(), 2000);
  9717. else if (offset == 2000)
  9718. sink.os.write(rand2.data() + 2000, 1);
  9719. else if (offset == 2001)
  9720. sink.os.write(rand2.data() + 2001, 999);
  9721. else if (offset == rand2.size())
  9722. sink.done();
  9723. return true;
  9724. },
  9725. "filename4",
  9726. {}});
  9727. {
  9728. auto res = cli.Post("/post-providers", {}, {}, providers);
  9729. ASSERT_TRUE(res);
  9730. ASSERT_EQ(StatusCode::OK_200, res->status);
  9731. }
  9732. {
  9733. auto res = cli.Post("/post-both", {}, items, providers);
  9734. ASSERT_TRUE(res);
  9735. ASSERT_EQ(StatusCode::OK_200, res->status);
  9736. }
  9737. }
  9738. }
  9739. TEST(MultipartFormDataTest, BadHeader) {
  9740. Server svr;
  9741. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9742. res.set_content("ok", "text/plain");
  9743. });
  9744. thread t = thread([&] { svr.listen(HOST, PORT); });
  9745. auto se = detail::scope_exit([&] {
  9746. svr.stop();
  9747. t.join();
  9748. ASSERT_FALSE(svr.is_running());
  9749. });
  9750. svr.wait_until_ready();
  9751. const std::string body =
  9752. "This is the preamble. It is to be ignored, though it\r\n"
  9753. "is a handy place for composition agents to include an\r\n"
  9754. "explanatory note to non-MIME conformant readers.\r\n"
  9755. "\r\n"
  9756. "\r\n"
  9757. "--simple boundary\r\n"
  9758. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9759. ": BAD...\r\n"
  9760. "\r\n"
  9761. "value1\r\n"
  9762. "--simple boundary\r\n"
  9763. "Content-Disposition: form-data; name=\"field2\"; "
  9764. "filename=\"example.txt\"\r\n"
  9765. "\r\n"
  9766. "value2\r\n"
  9767. "--simple boundary--\r\n"
  9768. "This is the epilogue. It is also to be ignored.\r\n";
  9769. std::string content_type =
  9770. R"(multipart/form-data; boundary="simple boundary")";
  9771. Client cli(HOST, PORT);
  9772. auto res = cli.Post("/post", body, content_type.c_str());
  9773. ASSERT_TRUE(res);
  9774. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9775. }
  9776. TEST(MultipartFormDataTest, WithPreamble) {
  9777. Server svr;
  9778. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9779. res.set_content("ok", "text/plain");
  9780. });
  9781. thread t = thread([&] { svr.listen(HOST, PORT); });
  9782. auto se = detail::scope_exit([&] {
  9783. svr.stop();
  9784. t.join();
  9785. ASSERT_FALSE(svr.is_running());
  9786. });
  9787. svr.wait_until_ready();
  9788. const std::string body =
  9789. "This is the preamble. It is to be ignored, though it\r\n"
  9790. "is a handy place for composition agents to include an\r\n"
  9791. "explanatory note to non-MIME conformant readers.\r\n"
  9792. "\r\n"
  9793. "\r\n"
  9794. "--simple boundary\r\n"
  9795. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9796. "\r\n"
  9797. "value1\r\n"
  9798. "--simple boundary\r\n"
  9799. "Content-Disposition: form-data; name=\"field2\"; "
  9800. "filename=\"example.txt\"\r\n"
  9801. "\r\n"
  9802. "value2\r\n"
  9803. "--simple boundary--\r\n"
  9804. "This is the epilogue. It is also to be ignored.\r\n";
  9805. std::string content_type =
  9806. R"(multipart/form-data; boundary="simple boundary")";
  9807. Client cli(HOST, PORT);
  9808. auto res = cli.Post("/post", body, content_type.c_str());
  9809. ASSERT_TRUE(res);
  9810. EXPECT_EQ(StatusCode::OK_200, res->status);
  9811. }
  9812. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9814. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9815. const ContentReader &content_reader) {
  9816. if (req.is_multipart_form_data()) {
  9817. std::vector<FormData> items;
  9818. content_reader(
  9819. [&](const FormData &file) {
  9820. items.push_back(file);
  9821. return true;
  9822. },
  9823. [&](const char *data, size_t data_length) {
  9824. items.back().content.append(data, data_length);
  9825. return true;
  9826. });
  9827. EXPECT_TRUE(std::string(items[0].name) == "document");
  9828. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9829. EXPECT_TRUE(items[0].filename == "2MB_data");
  9830. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9831. EXPECT_TRUE(items[1].name == "hello");
  9832. EXPECT_TRUE(items[1].content == "world");
  9833. EXPECT_TRUE(items[1].filename == "");
  9834. EXPECT_TRUE(items[1].content_type == "");
  9835. } else {
  9836. std::string body;
  9837. content_reader([&](const char *data, size_t data_length) {
  9838. body.append(data, data_length);
  9839. return true;
  9840. });
  9841. }
  9842. });
  9843. auto port = svr.bind_to_any_port("localhost");
  9844. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9845. auto se = detail::scope_exit([&] {
  9846. svr.stop();
  9847. t.join();
  9848. ASSERT_FALSE(svr.is_running());
  9849. });
  9850. svr.wait_until_ready();
  9851. {
  9852. std::string data(1024 * 1024 * 2, '.');
  9853. std::stringstream buffer;
  9854. buffer << data;
  9855. SSLClient cli("localhost", port);
  9856. cli.enable_server_certificate_verification(false);
  9857. UploadFormDataItems items{
  9858. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9859. {"hello", "world", "", ""},
  9860. };
  9861. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9862. ASSERT_TRUE(res);
  9863. ASSERT_EQ(StatusCode::OK_200, res->status);
  9864. }
  9865. }
  9866. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9867. std::string data(1024 * 1024 * 2, '&');
  9868. std::stringstream buffer;
  9869. buffer << data;
  9870. Client cli("https://localhost:8080");
  9871. UploadFormDataItems items{
  9872. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9873. {"hello", "world", "", ""},
  9874. };
  9875. for (const char &c : " \t\r\n") {
  9876. auto res =
  9877. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9878. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9879. ASSERT_FALSE(res);
  9880. }
  9881. }
  9882. TEST(MultipartFormDataTest, PutFormData) {
  9883. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9884. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9885. const ContentReader &content_reader) {
  9886. if (req.is_multipart_form_data()) {
  9887. std::vector<FormData> items;
  9888. content_reader(
  9889. [&](const FormData &file) {
  9890. items.push_back(file);
  9891. return true;
  9892. },
  9893. [&](const char *data, size_t data_length) {
  9894. items.back().content.append(data, data_length);
  9895. return true;
  9896. });
  9897. EXPECT_TRUE(std::string(items[0].name) == "document");
  9898. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9899. EXPECT_TRUE(items[0].filename == "2MB_data");
  9900. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9901. EXPECT_TRUE(items[1].name == "hello");
  9902. EXPECT_TRUE(items[1].content == "world");
  9903. EXPECT_TRUE(items[1].filename == "");
  9904. EXPECT_TRUE(items[1].content_type == "");
  9905. } else {
  9906. std::string body;
  9907. content_reader([&](const char *data, size_t data_length) {
  9908. body.append(data, data_length);
  9909. return true;
  9910. });
  9911. }
  9912. });
  9913. auto port = svr.bind_to_any_port("localhost");
  9914. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9915. auto se = detail::scope_exit([&] {
  9916. svr.stop();
  9917. t.join();
  9918. ASSERT_FALSE(svr.is_running());
  9919. });
  9920. svr.wait_until_ready();
  9921. {
  9922. std::string data(1024 * 1024 * 2, '&');
  9923. std::stringstream buffer;
  9924. buffer << data;
  9925. SSLClient cli("localhost", port);
  9926. cli.enable_server_certificate_verification(false);
  9927. UploadFormDataItems items{
  9928. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9929. {"hello", "world", "", ""},
  9930. };
  9931. auto res = cli.Put("/put", items);
  9932. ASSERT_TRUE(res);
  9933. ASSERT_EQ(StatusCode::OK_200, res->status);
  9934. }
  9935. }
  9936. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9938. svr.Put("/put_customboundary",
  9939. [&](const Request &req, const Response & /*res*/,
  9940. const ContentReader &content_reader) {
  9941. if (req.is_multipart_form_data()) {
  9942. std::vector<FormData> items;
  9943. content_reader(
  9944. [&](const FormData &file) {
  9945. items.push_back(file);
  9946. return true;
  9947. },
  9948. [&](const char *data, size_t data_length) {
  9949. items.back().content.append(data, data_length);
  9950. return true;
  9951. });
  9952. EXPECT_TRUE(std::string(items[0].name) == "document");
  9953. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9954. EXPECT_TRUE(items[0].filename == "2MB_data");
  9955. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9956. EXPECT_TRUE(items[1].name == "hello");
  9957. EXPECT_TRUE(items[1].content == "world");
  9958. EXPECT_TRUE(items[1].filename == "");
  9959. EXPECT_TRUE(items[1].content_type == "");
  9960. } else {
  9961. std::string body;
  9962. content_reader([&](const char *data, size_t data_length) {
  9963. body.append(data, data_length);
  9964. return true;
  9965. });
  9966. }
  9967. });
  9968. auto port = svr.bind_to_any_port("localhost");
  9969. auto t = std::thread([&]() { svr.listen_after_bind(); });
  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. {
  9977. std::string data(1024 * 1024 * 2, '&');
  9978. std::stringstream buffer;
  9979. buffer << data;
  9980. SSLClient cli("localhost", port);
  9981. cli.enable_server_certificate_verification(false);
  9982. UploadFormDataItems items{
  9983. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9984. {"hello", "world", "", ""},
  9985. };
  9986. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9987. ASSERT_TRUE(res);
  9988. ASSERT_EQ(StatusCode::OK_200, res->status);
  9989. }
  9990. }
  9991. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9992. std::string data(1024 * 1024 * 2, '&');
  9993. std::stringstream buffer;
  9994. buffer << data;
  9995. Client cli("https://localhost:8080");
  9996. cli.enable_server_certificate_verification(false);
  9997. UploadFormDataItems items{
  9998. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9999. {"hello", "world", "", ""},
  10000. };
  10001. for (const char &c : " \t\r\n") {
  10002. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10003. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10004. ASSERT_FALSE(res);
  10005. }
  10006. }
  10007. TEST(MultipartFormDataTest, AlternateFilename) {
  10008. auto handled = false;
  10009. Server svr;
  10010. svr.Post("/test", [&](const Request &req, Response &res) {
  10011. ASSERT_EQ(2u, req.form.files.size());
  10012. ASSERT_EQ(1u, req.form.fields.size());
  10013. // Test files
  10014. const auto &file1 = req.form.get_file("file1");
  10015. ASSERT_EQ("file1", file1.name);
  10016. ASSERT_EQ("A.txt", file1.filename);
  10017. ASSERT_EQ("text/plain", file1.content_type);
  10018. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10019. const auto &file2 = req.form.get_file("file2");
  10020. ASSERT_EQ("file2", file2.name);
  10021. ASSERT_EQ("a.html", file2.filename);
  10022. ASSERT_EQ("text/html", file2.content_type);
  10023. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10024. file2.content);
  10025. // Test text field
  10026. const auto &text = req.form.get_field("text");
  10027. ASSERT_EQ("text default", text);
  10028. res.set_content("ok", "text/plain");
  10029. handled = true;
  10030. });
  10031. thread t = thread([&] { svr.listen(HOST, PORT); });
  10032. auto se = detail::scope_exit([&] {
  10033. svr.stop();
  10034. t.join();
  10035. ASSERT_FALSE(svr.is_running());
  10036. ASSERT_TRUE(handled);
  10037. });
  10038. svr.wait_until_ready();
  10039. auto req = "POST /test HTTP/1.1\r\n"
  10040. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10041. "Content-Length: 399\r\n"
  10042. "\r\n"
  10043. "----------\r\n"
  10044. "Content-Disposition: form-data; name=\"text\"\r\n"
  10045. "\r\n"
  10046. "text default\r\n"
  10047. "----------\r\n"
  10048. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10049. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10050. "Content-Type: text/plain\r\n"
  10051. "\r\n"
  10052. "Content of a.txt.\r\n"
  10053. "\r\n"
  10054. "----------\r\n"
  10055. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10056. "\"a.html\"\r\n"
  10057. "Content-Type: text/html\r\n"
  10058. "\r\n"
  10059. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10060. "\r\n"
  10061. "------------\r\n";
  10062. ASSERT_TRUE(send_request(1, req));
  10063. }
  10064. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10065. auto handled = false;
  10066. Server svr;
  10067. svr.Post("/test", [&](const Request &req, Response &res) {
  10068. // Case-insensitive "utf-8''" prefix with a long value
  10069. const auto &file = req.form.get_file("file1");
  10070. ASSERT_EQ("file1", file.name);
  10071. // 8000 chars exercises both the Content-Disposition parser and the
  10072. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10073. // Prior to the fix, std::regex_match on this header would cause O(N)
  10074. // stack recursion in libstdc++, leading to SIGSEGV.
  10075. std::string expected_filename(8000, 'A');
  10076. ASSERT_EQ(expected_filename, file.filename);
  10077. res.set_content("ok", "text/plain");
  10078. handled = true;
  10079. });
  10080. thread t = thread([&] { svr.listen(HOST, PORT); });
  10081. auto se = detail::scope_exit([&] {
  10082. svr.stop();
  10083. t.join();
  10084. ASSERT_FALSE(svr.is_running());
  10085. ASSERT_TRUE(handled);
  10086. });
  10087. svr.wait_until_ready();
  10088. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10089. // Regression test for GHSA-qq6v-r583-3h69
  10090. std::string long_filename(8000, 'A');
  10091. std::string body = "----------\r\n"
  10092. "Content-Disposition: form-data; name=\"file1\"; "
  10093. "filename*=\"Utf-8''" +
  10094. long_filename +
  10095. "\"\r\n"
  10096. "\r\n"
  10097. "hello\r\n"
  10098. "------------\r\n";
  10099. auto req = "POST /test HTTP/1.1\r\n"
  10100. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10101. "Content-Length: " +
  10102. std::to_string(body.size()) + "\r\n\r\n" + body;
  10103. ASSERT_TRUE(send_request(1, req));
  10104. }
  10105. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10106. auto handled = false;
  10107. Server svr;
  10108. svr.Post("/test", [&](const Request &req, Response &) {
  10109. ASSERT_EQ(2u, req.form.fields.size());
  10110. const auto &text1 = req.form.get_field("text1");
  10111. ASSERT_EQ("text1", text1);
  10112. const auto &text2 = req.form.get_field("text2");
  10113. ASSERT_EQ("text2", text2);
  10114. handled = true;
  10115. });
  10116. thread t = thread([&] { svr.listen(HOST, PORT); });
  10117. auto se = detail::scope_exit([&] {
  10118. svr.stop();
  10119. t.join();
  10120. ASSERT_FALSE(svr.is_running());
  10121. ASSERT_TRUE(handled);
  10122. });
  10123. svr.wait_until_ready();
  10124. auto req = "POST /test HTTP/1.1\r\n"
  10125. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10126. "Content-Length: 146\r\n"
  10127. "\r\n----------\r\n"
  10128. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10129. "\r\n"
  10130. "text1"
  10131. "\r\n----------\r\n"
  10132. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10133. "\r\n"
  10134. "text2"
  10135. "\r\n------------";
  10136. std::string response;
  10137. ASSERT_TRUE(send_request(1, req, &response));
  10138. ASSERT_EQ("200", response.substr(9, 3));
  10139. }
  10140. TEST(MultipartFormDataTest, ContentLength) {
  10141. auto handled = false;
  10142. Server svr;
  10143. svr.Post("/test", [&](const Request &req, Response &) {
  10144. ASSERT_EQ(2u, req.form.fields.size());
  10145. const auto &text1 = req.form.get_field("text1");
  10146. ASSERT_EQ("text1", text1);
  10147. const auto &text2 = req.form.get_field("text2");
  10148. ASSERT_EQ("text2", text2);
  10149. handled = true;
  10150. });
  10151. thread t = thread([&] { svr.listen(HOST, PORT); });
  10152. auto se = detail::scope_exit([&] {
  10153. svr.stop();
  10154. t.join();
  10155. ASSERT_FALSE(svr.is_running());
  10156. ASSERT_TRUE(handled);
  10157. });
  10158. svr.wait_until_ready();
  10159. auto req = "POST /test HTTP/1.1\r\n"
  10160. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10161. "Content-Length: 167\r\n"
  10162. "\r\n----------\r\n"
  10163. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10164. "Content-Length: 5\r\n"
  10165. "\r\n"
  10166. "text1"
  10167. "\r\n----------\r\n"
  10168. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10169. "\r\n"
  10170. "text2"
  10171. "\r\n------------\r\n";
  10172. std::string response;
  10173. ASSERT_TRUE(send_request(1, req, &response));
  10174. ASSERT_EQ("200", response.substr(9, 3));
  10175. }
  10176. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10177. auto handled = false;
  10178. Server svr;
  10179. svr.Post("/test", [&](const Request &req, Response &) {
  10180. ASSERT_EQ(2u, req.form.fields.size());
  10181. const auto &text1 = req.form.get_field("text1");
  10182. ASSERT_EQ("text1", text1);
  10183. // TODO: Add header access for text fields if needed
  10184. const auto &text2 = req.form.get_field("text2");
  10185. ASSERT_EQ("text2", text2);
  10186. // TODO: Header access for text fields needs to be implemented
  10187. // auto &headers = it->second.headers;
  10188. // ASSERT_EQ(3U, headers.size());
  10189. // auto custom_header = headers.find("x-whatever");
  10190. // ASSERT_TRUE(custom_header != headers.end());
  10191. // ASSERT_NE("customvalue", custom_header->second);
  10192. // ASSERT_EQ("CustomValue", custom_header->second);
  10193. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10194. handled = true;
  10195. });
  10196. thread t = thread([&] { svr.listen(HOST, PORT); });
  10197. auto se = detail::scope_exit([&] {
  10198. svr.stop();
  10199. t.join();
  10200. ASSERT_FALSE(svr.is_running());
  10201. ASSERT_TRUE(handled);
  10202. });
  10203. svr.wait_until_ready();
  10204. auto req = "POST /test HTTP/1.1\r\n"
  10205. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10206. "Content-Length: 232\r\n"
  10207. "\r\n----------\r\n"
  10208. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10209. "Content-Length: 5\r\n"
  10210. "X-Test: 1\r\n"
  10211. "\r\n"
  10212. "text1"
  10213. "\r\n----------\r\n"
  10214. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10215. "Content-Type: text/plain\r\n"
  10216. "X-Whatever: CustomValue\r\n"
  10217. "\r\n"
  10218. "text2"
  10219. "\r\n------------\r\n"
  10220. "That should be disregarded. Not even read";
  10221. std::string response;
  10222. ASSERT_TRUE(send_request(1, req, &response));
  10223. ASSERT_EQ("200", response.substr(9, 3));
  10224. }
  10225. TEST(MultipartFormDataTest, LargeHeader) {
  10226. auto handled = false;
  10227. Server svr;
  10228. svr.Post("/test", [&](const Request &req, Response &) {
  10229. ASSERT_EQ(1u, req.form.fields.size());
  10230. const auto &text = req.form.get_field("name1");
  10231. ASSERT_EQ("text1", text);
  10232. handled = true;
  10233. });
  10234. thread t = thread([&] { svr.listen(HOST, PORT); });
  10235. auto se = detail::scope_exit([&] {
  10236. svr.stop();
  10237. t.join();
  10238. ASSERT_FALSE(svr.is_running());
  10239. ASSERT_TRUE(handled);
  10240. });
  10241. svr.wait_until_ready();
  10242. auto boundary = std::string("cpp-httplib-multipart-data");
  10243. std::string content = "--" + boundary +
  10244. "\r\n"
  10245. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10246. "\r\n"
  10247. "text1\r\n"
  10248. "--" +
  10249. boundary + "--\r\n";
  10250. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10251. "Content-Type: multipart/form-data;boundary=" +
  10252. boundary +
  10253. "\r\n"
  10254. "Content-Length: " +
  10255. std::to_string(content.size()) +
  10256. "\r\n"
  10257. "Dummy-Header: ";
  10258. std::string header_suffix = "\r\n"
  10259. "\r\n";
  10260. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10261. size_t header_dummy_size =
  10262. read_buff_size -
  10263. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10264. auto header_dummy = std::string(header_dummy_size, '@');
  10265. auto req = header_prefix + header_dummy + header_suffix + content;
  10266. std::string response;
  10267. ASSERT_TRUE(send_request(1, req, &response));
  10268. ASSERT_EQ("200", response.substr(9, 3));
  10269. }
  10270. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10271. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10272. // (not chunked Transfer-Encoding) after the streaming refactor.
  10273. auto handled = false;
  10274. Server svr;
  10275. svr.Post("/upload", [&](const Request &req, Response &res) {
  10276. auto cl_it = req.headers.find("Content-Length");
  10277. EXPECT_TRUE(cl_it != req.headers.end());
  10278. auto te_it = req.headers.find("Transfer-Encoding");
  10279. EXPECT_TRUE(te_it == req.headers.end());
  10280. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10281. res.set_content("ok", "text/plain");
  10282. handled = true;
  10283. });
  10284. auto port = svr.bind_to_any_port(HOST);
  10285. auto t = thread([&] { svr.listen_after_bind(); });
  10286. auto se = detail::scope_exit([&] {
  10287. svr.stop();
  10288. t.join();
  10289. ASSERT_FALSE(svr.is_running());
  10290. ASSERT_TRUE(handled);
  10291. });
  10292. svr.wait_until_ready();
  10293. UploadFormDataItems items = {
  10294. {"field1", "hello", "", "text/plain"},
  10295. {"file1", "world", "test.txt", "application/octet-stream"},
  10296. };
  10297. Client cli(HOST, port);
  10298. auto res = cli.Post("/upload", {}, items);
  10299. ASSERT_TRUE(res);
  10300. EXPECT_EQ(StatusCode::OK_200, res->status);
  10301. }
  10302. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10303. // Verify that make_multipart_content_provider coalesces many small segments
  10304. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10305. constexpr size_t kItemCount = 1000;
  10306. UploadFormDataItems items;
  10307. items.reserve(kItemCount);
  10308. for (size_t i = 0; i < kItemCount; i++) {
  10309. items.push_back(
  10310. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10311. }
  10312. const std::string boundary = "----test-boundary";
  10313. auto content_length = detail::get_multipart_content_length(items, boundary);
  10314. auto provider = detail::make_multipart_content_provider(items, boundary);
  10315. // Drive the provider the same way write_content_with_progress does
  10316. size_t write_count = 0;
  10317. size_t total_bytes = 0;
  10318. DataSink sink;
  10319. size_t offset = 0;
  10320. sink.write = [&](const char *d, size_t l) -> bool {
  10321. (void)d;
  10322. write_count++;
  10323. total_bytes += l;
  10324. offset += l;
  10325. return true;
  10326. };
  10327. sink.is_writable = []() -> bool { return true; };
  10328. while (offset < content_length) {
  10329. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10330. }
  10331. EXPECT_EQ(content_length, total_bytes);
  10332. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10333. // With buffering into 64KB blocks, write_count should be much smaller.
  10334. auto segment_count = 3 * kItemCount + 1;
  10335. EXPECT_LT(write_count, segment_count / 10);
  10336. }
  10337. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10338. // Integration test: send many UploadFormDataItems and verify the server
  10339. // receives all of them correctly (#2410).
  10340. constexpr size_t kItemCount = 500;
  10341. auto handled = false;
  10342. Server svr;
  10343. svr.Post("/upload", [&](const Request &req, Response &res) {
  10344. EXPECT_EQ(kItemCount, req.form.fields.size());
  10345. for (size_t i = 0; i < kItemCount; i++) {
  10346. auto key = "field" + std::to_string(i);
  10347. auto val = "value" + std::to_string(i);
  10348. auto it = req.form.fields.find(key);
  10349. if (it != req.form.fields.end()) {
  10350. EXPECT_EQ(val, it->second.content);
  10351. } else {
  10352. ADD_FAILURE() << "Missing field: " << key;
  10353. }
  10354. }
  10355. res.set_content("ok", "text/plain");
  10356. handled = true;
  10357. });
  10358. auto port = svr.bind_to_any_port(HOST);
  10359. auto t = thread([&] { svr.listen_after_bind(); });
  10360. auto se = detail::scope_exit([&] {
  10361. svr.stop();
  10362. t.join();
  10363. ASSERT_FALSE(svr.is_running());
  10364. ASSERT_TRUE(handled);
  10365. });
  10366. svr.wait_until_ready();
  10367. UploadFormDataItems items;
  10368. items.reserve(kItemCount);
  10369. for (size_t i = 0; i < kItemCount; i++) {
  10370. items.push_back(
  10371. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10372. }
  10373. Client cli(HOST, port);
  10374. auto res = cli.Post("/upload", items);
  10375. ASSERT_TRUE(res);
  10376. EXPECT_EQ(StatusCode::OK_200, res->status);
  10377. }
  10378. TEST(MultipartFormDataTest, MakeFileProvider) {
  10379. // Verify make_file_provider sends a file's contents correctly.
  10380. const std::string file_content(4096, 'Z');
  10381. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10382. {
  10383. std::ofstream ofs(tmp_path, std::ios::binary);
  10384. ofs.write(file_content.data(),
  10385. static_cast<std::streamsize>(file_content.size()));
  10386. }
  10387. auto handled = false;
  10388. Server svr;
  10389. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10390. const ContentReader &content_reader) {
  10391. ASSERT_TRUE(req.is_multipart_form_data());
  10392. std::vector<FormData> items;
  10393. content_reader(
  10394. [&](const FormData &file) {
  10395. items.push_back(file);
  10396. return true;
  10397. },
  10398. [&](const char *data, size_t data_length) {
  10399. items.back().content.append(data, data_length);
  10400. return true;
  10401. });
  10402. ASSERT_EQ(1u, items.size());
  10403. EXPECT_EQ("myfile", items[0].name);
  10404. EXPECT_EQ("data.bin", items[0].filename);
  10405. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10406. EXPECT_EQ(file_content, items[0].content);
  10407. handled = true;
  10408. });
  10409. auto port = svr.bind_to_any_port(HOST);
  10410. auto t = thread([&] { svr.listen_after_bind(); });
  10411. auto se = detail::scope_exit([&] {
  10412. svr.stop();
  10413. t.join();
  10414. ASSERT_FALSE(svr.is_running());
  10415. ASSERT_TRUE(handled);
  10416. std::remove(tmp_path.c_str());
  10417. });
  10418. svr.wait_until_ready();
  10419. FormDataProviderItems providers;
  10420. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10421. "application/octet-stream"));
  10422. Client cli(HOST, port);
  10423. auto res = cli.Post("/upload", {}, {}, providers);
  10424. ASSERT_TRUE(res);
  10425. EXPECT_EQ(StatusCode::OK_200, res->status);
  10426. }
  10427. TEST(MakeFileBodyTest, Basic) {
  10428. const std::string file_content(4096, 'Z');
  10429. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10430. {
  10431. std::ofstream ofs(tmp_path, std::ios::binary);
  10432. ofs.write(file_content.data(),
  10433. static_cast<std::streamsize>(file_content.size()));
  10434. }
  10435. auto handled = false;
  10436. Server svr;
  10437. svr.Post("/upload", [&](const Request &req, Response &res) {
  10438. EXPECT_EQ(file_content, req.body);
  10439. handled = true;
  10440. res.status = StatusCode::OK_200;
  10441. });
  10442. auto port = svr.bind_to_any_port(HOST);
  10443. auto t = thread([&] { svr.listen_after_bind(); });
  10444. auto se = detail::scope_exit([&] {
  10445. svr.stop();
  10446. t.join();
  10447. ASSERT_FALSE(svr.is_running());
  10448. ASSERT_TRUE(handled);
  10449. std::remove(tmp_path.c_str());
  10450. });
  10451. svr.wait_until_ready();
  10452. auto fb = make_file_body(tmp_path);
  10453. ASSERT_GT(fb.first, 0u);
  10454. Client cli(HOST, port);
  10455. auto res =
  10456. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10457. ASSERT_TRUE(res);
  10458. EXPECT_EQ(StatusCode::OK_200, res->status);
  10459. }
  10460. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10461. static constexpr unsigned int number_of_tasks{1000000};
  10462. std::atomic_uint count{0};
  10463. std::unique_ptr<TaskQueue> task_queue{
  10464. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10465. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10466. auto queued = task_queue->enqueue(
  10467. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10468. EXPECT_TRUE(queued);
  10469. }
  10470. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10471. task_queue->shutdown();
  10472. #else
  10473. EXPECT_NO_THROW(task_queue->shutdown());
  10474. #endif
  10475. EXPECT_EQ(number_of_tasks, count.load());
  10476. }
  10477. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10478. static constexpr unsigned int number_of_tasks{1000000};
  10479. static constexpr unsigned int qlimit{2};
  10480. unsigned int queued_count{0};
  10481. std::atomic_uint count{0};
  10482. std::unique_ptr<TaskQueue> task_queue{
  10483. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10484. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10485. if (task_queue->enqueue(
  10486. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10487. queued_count++;
  10488. }
  10489. }
  10490. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10491. task_queue->shutdown();
  10492. #else
  10493. EXPECT_NO_THROW(task_queue->shutdown());
  10494. #endif
  10495. EXPECT_EQ(queued_count, count.load());
  10496. EXPECT_TRUE(queued_count <= number_of_tasks);
  10497. EXPECT_TRUE(queued_count >= qlimit);
  10498. }
  10499. TEST(TaskQueueTest, MaxQueuedRequests) {
  10500. static constexpr unsigned int qlimit{3};
  10501. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10502. std::condition_variable sem_cv;
  10503. std::mutex sem_mtx;
  10504. int credits = 0;
  10505. bool queued;
  10506. /* Fill up the queue with tasks that will block until we give them credits to
  10507. * complete. */
  10508. for (unsigned int n = 0; n <= qlimit;) {
  10509. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10510. std::unique_lock<std::mutex> lock(sem_mtx);
  10511. while (credits <= 0) {
  10512. sem_cv.wait(lock);
  10513. }
  10514. /* Consume the credit and signal the test code if they are all gone. */
  10515. if (--credits == 0) { sem_cv.notify_one(); }
  10516. });
  10517. if (n < qlimit) {
  10518. /* The first qlimit enqueues must succeed. */
  10519. EXPECT_TRUE(queued);
  10520. } else {
  10521. /* The last one will succeed only when the worker thread
  10522. * starts and dequeues the first blocking task. Although
  10523. * not necessary for the correctness of this test, we sleep for
  10524. * a short while to avoid busy waiting. */
  10525. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10526. }
  10527. if (queued) { n++; }
  10528. }
  10529. /* Further enqueues must fail since the queue is full. */
  10530. for (auto i = 0; i < 4; i++) {
  10531. queued = task_queue->enqueue([] {});
  10532. EXPECT_FALSE(queued);
  10533. }
  10534. /* Give the credits to allow the previous tasks to complete. */
  10535. {
  10536. std::unique_lock<std::mutex> lock(sem_mtx);
  10537. credits += qlimit + 1;
  10538. }
  10539. sem_cv.notify_all();
  10540. /* Wait for all the credits to be consumed. */
  10541. {
  10542. std::unique_lock<std::mutex> lock(sem_mtx);
  10543. while (credits > 0) {
  10544. sem_cv.wait(lock);
  10545. }
  10546. }
  10547. /* Check that we are able again to enqueue at least qlimit tasks. */
  10548. for (unsigned int i = 0; i < qlimit; i++) {
  10549. queued = task_queue->enqueue([] {});
  10550. EXPECT_TRUE(queued);
  10551. }
  10552. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10553. task_queue->shutdown();
  10554. #else
  10555. EXPECT_NO_THROW(task_queue->shutdown());
  10556. #endif
  10557. }
  10558. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10559. Server svr;
  10560. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10561. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10562. });
  10563. svr.Get("/hello", [](const Request &req, Response &res) {
  10564. res.set_content(req.get_param_value("key"), "text/plain");
  10565. });
  10566. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10567. auto se = detail::scope_exit([&] {
  10568. svr.stop();
  10569. thread.join();
  10570. ASSERT_FALSE(svr.is_running());
  10571. });
  10572. svr.wait_until_ready();
  10573. {
  10574. Client cli(HOST, PORT);
  10575. cli.set_follow_location(true);
  10576. auto res = cli.Get("/");
  10577. ASSERT_TRUE(res);
  10578. EXPECT_EQ(StatusCode::OK_200, res->status);
  10579. EXPECT_EQ("val&key2=val2", res->body);
  10580. }
  10581. }
  10582. #endif
  10583. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10584. Server svr;
  10585. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10586. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10587. });
  10588. svr.Get("/hello", [](const Request &req, Response &res) {
  10589. res.set_content(req.get_param_value("key"), "text/plain");
  10590. });
  10591. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10592. auto se = detail::scope_exit([&] {
  10593. svr.stop();
  10594. thread.join();
  10595. ASSERT_FALSE(svr.is_running());
  10596. });
  10597. svr.wait_until_ready();
  10598. {
  10599. Client cli(HOST, PORT);
  10600. cli.set_follow_location(true);
  10601. auto res = cli.Get("/");
  10602. ASSERT_TRUE(res);
  10603. EXPECT_EQ(StatusCode::OK_200, res->status);
  10604. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10605. }
  10606. }
  10607. TEST(RedirectTest, RedirectWithPlusInPath) {
  10608. Server svr;
  10609. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10610. res.set_redirect("/a+b");
  10611. });
  10612. // Route pattern uses regex; escape + as \\+
  10613. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10614. res.set_content(req.path, "text/plain");
  10615. });
  10616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10617. auto se = detail::scope_exit([&] {
  10618. svr.stop();
  10619. thread.join();
  10620. ASSERT_FALSE(svr.is_running());
  10621. });
  10622. svr.wait_until_ready();
  10623. {
  10624. Client cli(HOST, PORT);
  10625. cli.set_follow_location(true);
  10626. auto res = cli.Get("/");
  10627. ASSERT_TRUE(res);
  10628. EXPECT_EQ(StatusCode::OK_200, res->status);
  10629. EXPECT_EQ("/a+b", res->body);
  10630. }
  10631. }
  10632. #ifdef CPPHTTPLIB_SSL_ENABLED
  10633. TEST(RedirectTest, Issue2185_Online) {
  10634. SSLClient client("github.com");
  10635. client.set_follow_location(true);
  10636. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10637. "Coollab-Windows.zip");
  10638. ASSERT_TRUE(res);
  10639. EXPECT_EQ(StatusCode::OK_200, res->status);
  10640. EXPECT_EQ(9920427U, res->body.size());
  10641. }
  10642. #endif
  10643. TEST(VulnerabilityTest, CRLFInjection) {
  10644. Server svr;
  10645. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10646. res.set_content("Hello 1", "text/plain");
  10647. });
  10648. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10649. res.set_content("Hello 2", "text/plain");
  10650. });
  10651. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10652. res.set_content("Hello 3", "text/plain");
  10653. });
  10654. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10655. res.set_content("Hello 4", "text/plain");
  10656. });
  10657. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10658. for (const auto &x : req.headers) {
  10659. auto key = x.first;
  10660. EXPECT_STRNE("evil", key.c_str());
  10661. }
  10662. });
  10663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10664. auto se = detail::scope_exit([&] {
  10665. svr.stop();
  10666. thread.join();
  10667. ASSERT_FALSE(svr.is_running());
  10668. });
  10669. svr.wait_until_ready();
  10670. {
  10671. Client cli(HOST, PORT);
  10672. cli.Post("/test1", "A=B",
  10673. "application/x-www-form-urlencoded\r\nevil: hello1");
  10674. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10675. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10676. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10677. }
  10678. }
  10679. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10680. auto server_thread = std::thread([] {
  10681. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10682. default_socket_options(srv);
  10683. sockaddr_in addr{};
  10684. addr.sin_family = AF_INET;
  10685. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10686. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10687. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10688. ::listen(srv, 1);
  10689. sockaddr_in cli_addr{};
  10690. socklen_t cli_len = sizeof(cli_addr);
  10691. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10692. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10693. std::string buf_all;
  10694. char buf[2048];
  10695. ssize_t n;
  10696. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10697. buf_all.append(buf, static_cast<size_t>(n));
  10698. size_t pos;
  10699. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10700. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10701. auto e = request_block.find("\r\n");
  10702. if (e != std::string::npos) {
  10703. auto request_line = request_block.substr(0, e);
  10704. std::string msg =
  10705. "CRLF injection detected in request line: '" + request_line + "'";
  10706. EXPECT_FALSE(true) << msg;
  10707. }
  10708. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10709. ::send(cli,
  10710. #ifdef _WIN32
  10711. static_cast<const char *>(resp.c_str()),
  10712. static_cast<int>(resp.size()),
  10713. #else
  10714. resp.c_str(), resp.size(),
  10715. #endif
  10716. 0);
  10717. buf_all.erase(0, pos + 4);
  10718. }
  10719. }
  10720. detail::close_socket(cli);
  10721. detail::close_socket(srv);
  10722. });
  10723. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10724. auto cli = Client("127.0.0.1", PORT + 1);
  10725. auto headers = Headers{
  10726. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10727. {"Connection", "keep-alive"}};
  10728. auto res = cli.Get("/hi", headers);
  10729. EXPECT_FALSE(res);
  10730. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10731. server_thread.join();
  10732. }
  10733. TEST(PathParamsTest, StaticMatch) {
  10734. const auto pattern = "/users/all";
  10735. detail::PathParamsMatcher matcher(pattern);
  10736. Request request;
  10737. request.path = "/users/all";
  10738. ASSERT_TRUE(matcher.match(request));
  10739. std::unordered_map<std::string, std::string> expected_params = {};
  10740. EXPECT_EQ(request.path_params, expected_params);
  10741. }
  10742. TEST(PathParamsTest, StaticMismatch) {
  10743. const auto pattern = "/users/all";
  10744. detail::PathParamsMatcher matcher(pattern);
  10745. Request request;
  10746. request.path = "/users/1";
  10747. ASSERT_FALSE(matcher.match(request));
  10748. }
  10749. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10750. const auto pattern = "/users/:id/subscriptions";
  10751. detail::PathParamsMatcher matcher(pattern);
  10752. Request request;
  10753. request.path = "/users/42/subscriptions";
  10754. ASSERT_TRUE(matcher.match(request));
  10755. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10756. EXPECT_EQ(request.path_params, expected_params);
  10757. }
  10758. TEST(PathParamsTest, SingleParamInTheEnd) {
  10759. const auto pattern = "/users/:id";
  10760. detail::PathParamsMatcher matcher(pattern);
  10761. Request request;
  10762. request.path = "/users/24";
  10763. ASSERT_TRUE(matcher.match(request));
  10764. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10765. EXPECT_EQ(request.path_params, expected_params);
  10766. }
  10767. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10768. const auto pattern = "/users/:id/";
  10769. detail::PathParamsMatcher matcher(pattern);
  10770. Request request;
  10771. request.path = "/users/42/";
  10772. ASSERT_TRUE(matcher.match(request));
  10773. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10774. EXPECT_EQ(request.path_params, expected_params);
  10775. }
  10776. TEST(PathParamsTest, EmptyParam) {
  10777. const auto pattern = "/users/:id/";
  10778. detail::PathParamsMatcher matcher(pattern);
  10779. Request request;
  10780. request.path = "/users//";
  10781. ASSERT_TRUE(matcher.match(request));
  10782. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10783. EXPECT_EQ(request.path_params, expected_params);
  10784. }
  10785. TEST(PathParamsTest, FragmentMismatch) {
  10786. const auto pattern = "/users/:id/";
  10787. detail::PathParamsMatcher matcher(pattern);
  10788. Request request;
  10789. request.path = "/admins/24/";
  10790. ASSERT_FALSE(matcher.match(request));
  10791. }
  10792. TEST(PathParamsTest, ExtraFragments) {
  10793. const auto pattern = "/users/:id";
  10794. detail::PathParamsMatcher matcher(pattern);
  10795. Request request;
  10796. request.path = "/users/42/subscriptions";
  10797. ASSERT_FALSE(matcher.match(request));
  10798. }
  10799. TEST(PathParamsTest, MissingTrailingParam) {
  10800. const auto pattern = "/users/:id";
  10801. detail::PathParamsMatcher matcher(pattern);
  10802. Request request;
  10803. request.path = "/users";
  10804. ASSERT_FALSE(matcher.match(request));
  10805. }
  10806. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10807. const auto pattern = "/users/:id/subscriptions";
  10808. detail::PathParamsMatcher matcher(pattern);
  10809. Request request;
  10810. request.path = "/users/subscriptions";
  10811. ASSERT_FALSE(matcher.match(request));
  10812. }
  10813. TEST(PathParamsTest, MultipleParams) {
  10814. const auto pattern = "/users/:userid/subscriptions/:subid";
  10815. detail::PathParamsMatcher matcher(pattern);
  10816. Request request;
  10817. request.path = "/users/42/subscriptions/2";
  10818. ASSERT_TRUE(matcher.match(request));
  10819. std::unordered_map<std::string, std::string> expected_params = {
  10820. {"userid", "42"}, {"subid", "2"}};
  10821. EXPECT_EQ(request.path_params, expected_params);
  10822. }
  10823. TEST(PathParamsTest, SequenceOfParams) {
  10824. const auto pattern = "/values/:x/:y/:z";
  10825. detail::PathParamsMatcher matcher(pattern);
  10826. Request request;
  10827. request.path = "/values/1/2/3";
  10828. ASSERT_TRUE(matcher.match(request));
  10829. std::unordered_map<std::string, std::string> expected_params = {
  10830. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10831. EXPECT_EQ(request.path_params, expected_params);
  10832. }
  10833. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10834. const auto pattern = "/prefix:suffix";
  10835. detail::PathParamsMatcher matcher(pattern);
  10836. Request request;
  10837. request.path = "/prefix:suffix";
  10838. ASSERT_TRUE(matcher.match(request));
  10839. const std::unordered_map<std::string, std::string> expected_params = {};
  10840. EXPECT_EQ(request.path_params, expected_params);
  10841. }
  10842. TEST(ParseUrlTest, VariousPatterns) {
  10843. {
  10844. detail::UrlComponents uc;
  10845. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  10846. EXPECT_EQ("http", uc.scheme);
  10847. EXPECT_EQ("example.com", uc.host);
  10848. EXPECT_EQ("8080", uc.port);
  10849. EXPECT_EQ("/path", uc.path);
  10850. EXPECT_EQ("?q=1", uc.query);
  10851. }
  10852. {
  10853. detail::UrlComponents uc;
  10854. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  10855. EXPECT_EQ("https", uc.scheme);
  10856. EXPECT_EQ("example.com", uc.host);
  10857. EXPECT_TRUE(uc.port.empty());
  10858. EXPECT_EQ("/path", uc.path);
  10859. }
  10860. {
  10861. detail::UrlComponents uc;
  10862. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  10863. EXPECT_EQ("::1", uc.host);
  10864. EXPECT_EQ("8080", uc.port);
  10865. EXPECT_EQ("/path", uc.path);
  10866. }
  10867. {
  10868. detail::UrlComponents uc;
  10869. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  10870. }
  10871. {
  10872. detail::UrlComponents uc;
  10873. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  10874. EXPECT_TRUE(uc.scheme.empty());
  10875. EXPECT_EQ("example.com", uc.host);
  10876. EXPECT_EQ("/path", uc.path);
  10877. EXPECT_EQ("?q=1", uc.query);
  10878. }
  10879. {
  10880. detail::UrlComponents uc;
  10881. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  10882. EXPECT_TRUE(uc.host.empty());
  10883. EXPECT_EQ("/path", uc.path);
  10884. EXPECT_EQ("?q=1", uc.query);
  10885. }
  10886. {
  10887. detail::UrlComponents uc;
  10888. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  10889. EXPECT_EQ("example.com", uc.host);
  10890. EXPECT_EQ("8080", uc.port);
  10891. }
  10892. {
  10893. // Unix socket path — must not be parsed as host
  10894. detail::UrlComponents uc;
  10895. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  10896. EXPECT_TRUE(uc.host.empty());
  10897. }
  10898. {
  10899. detail::UrlComponents uc;
  10900. ASSERT_TRUE(detail::parse_url("", uc));
  10901. EXPECT_TRUE(uc.host.empty());
  10902. EXPECT_TRUE(uc.path.empty());
  10903. }
  10904. {
  10905. detail::UrlComponents uc;
  10906. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  10907. }
  10908. {
  10909. detail::UrlComponents uc;
  10910. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  10911. }
  10912. {
  10913. // Accepted by parse_url; callers restrict to http/https
  10914. detail::UrlComponents uc;
  10915. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  10916. EXPECT_EQ("ftp", uc.scheme);
  10917. }
  10918. {
  10919. detail::UrlComponents uc;
  10920. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  10921. }
  10922. {
  10923. detail::UrlComponents uc;
  10924. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  10925. }
  10926. }
  10927. TEST(ParseUrlTest, FragmentHandling) {
  10928. {
  10929. detail::UrlComponents uc;
  10930. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  10931. EXPECT_EQ("/path", uc.path);
  10932. EXPECT_TRUE(uc.query.empty());
  10933. }
  10934. {
  10935. detail::UrlComponents uc;
  10936. ASSERT_TRUE(detail::parse_url("#frag", uc));
  10937. EXPECT_TRUE(uc.path.empty());
  10938. EXPECT_TRUE(uc.query.empty());
  10939. }
  10940. }
  10941. TEST(ParseUrlTest, UserinfoHandling) {
  10942. // Userinfo with @ but no colon — host includes @
  10943. detail::UrlComponents uc;
  10944. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  10945. EXPECT_EQ("user@host.com", uc.host);
  10946. EXPECT_EQ("/path", uc.path);
  10947. }
  10948. TEST(ParseUrlTest, IPv6EdgeCases) {
  10949. {
  10950. detail::UrlComponents uc;
  10951. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  10952. EXPECT_TRUE(uc.scheme.empty());
  10953. EXPECT_EQ("::1", uc.host);
  10954. EXPECT_EQ("8080", uc.port);
  10955. }
  10956. {
  10957. // Zone ID '%25' is not in [a-fA-F0-9:]
  10958. detail::UrlComponents uc;
  10959. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  10960. }
  10961. }
  10962. TEST(ParseUrlTest, SchemeEdgeCases) {
  10963. {
  10964. detail::UrlComponents uc;
  10965. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  10966. }
  10967. {
  10968. detail::UrlComponents uc;
  10969. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  10970. }
  10971. {
  10972. detail::UrlComponents uc;
  10973. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  10974. }
  10975. }
  10976. TEST(ParseUrlTest, PortEdgeCases) {
  10977. {
  10978. detail::UrlComponents uc;
  10979. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  10980. EXPECT_TRUE(uc.port.empty());
  10981. EXPECT_EQ("/path", uc.path);
  10982. }
  10983. {
  10984. // parse_url accepts any port string; validation is done by parse_port
  10985. detail::UrlComponents uc;
  10986. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  10987. EXPECT_EQ("abc", uc.port);
  10988. }
  10989. }
  10990. TEST(ParseUrlTest, WebSocketPatterns) {
  10991. {
  10992. detail::UrlComponents uc;
  10993. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  10994. EXPECT_EQ("ws", uc.scheme);
  10995. EXPECT_EQ("echo.example.com", uc.host);
  10996. EXPECT_EQ("8080", uc.port);
  10997. EXPECT_EQ("/ws", uc.path);
  10998. }
  10999. {
  11000. detail::UrlComponents uc;
  11001. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11002. EXPECT_EQ("wss", uc.scheme);
  11003. EXPECT_EQ("echo.example.com", uc.host);
  11004. EXPECT_TRUE(uc.port.empty());
  11005. EXPECT_EQ("/ws", uc.path);
  11006. }
  11007. }
  11008. TEST(ParseUrlTest, QueryOnly) {
  11009. detail::UrlComponents uc;
  11010. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11011. EXPECT_TRUE(uc.host.empty());
  11012. EXPECT_TRUE(uc.path.empty());
  11013. EXPECT_EQ("?q=1&r=2", uc.query);
  11014. }
  11015. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11016. detail::UrlComponents uc;
  11017. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11018. EXPECT_TRUE(uc.scheme.empty());
  11019. EXPECT_EQ("example.com", uc.host);
  11020. EXPECT_EQ("443", uc.port);
  11021. EXPECT_EQ("/path", uc.path);
  11022. }
  11023. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11024. // If ipv6 regex working, regex match codepath is taken.
  11025. // else port will default to 80 in Client impl
  11026. int clientImplMagicPort = 80;
  11027. int port = 4321;
  11028. // above ports must be different to avoid false negative
  11029. EXPECT_NE(clientImplMagicPort, port);
  11030. std::string ipV6TestURL = "http://[ff06::c3]";
  11031. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11032. CLIENT_PRIVATE_KEY_FILE);
  11033. EXPECT_EQ(cli.port(), port);
  11034. }
  11035. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11036. auto file_path = "./www/dir/index.html";
  11037. auto dir_path = "./www/dir";
  11038. detail::FileStat stat_file(file_path);
  11039. EXPECT_TRUE(stat_file.is_file());
  11040. EXPECT_FALSE(stat_file.is_dir());
  11041. detail::FileStat stat_dir(dir_path);
  11042. EXPECT_FALSE(stat_dir.is_file());
  11043. EXPECT_TRUE(stat_dir.is_dir());
  11044. }
  11045. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11046. // IPv4 with default HTTP port (80)
  11047. EXPECT_EQ("example.com",
  11048. detail::make_host_and_port_string("example.com", 80, false));
  11049. // IPv4 with default HTTPS port (443)
  11050. EXPECT_EQ("example.com",
  11051. detail::make_host_and_port_string("example.com", 443, true));
  11052. // IPv4 with non-default HTTP port
  11053. EXPECT_EQ("example.com:8080",
  11054. detail::make_host_and_port_string("example.com", 8080, false));
  11055. // IPv4 with non-default HTTPS port
  11056. EXPECT_EQ("example.com:8443",
  11057. detail::make_host_and_port_string("example.com", 8443, true));
  11058. // IPv6 with default HTTP port (80)
  11059. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11060. // IPv6 with default HTTPS port (443)
  11061. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11062. // IPv6 with non-default HTTP port
  11063. EXPECT_EQ("[::1]:8080",
  11064. detail::make_host_and_port_string("::1", 8080, false));
  11065. // IPv6 with non-default HTTPS port
  11066. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11067. // IPv6 full address with default port
  11068. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11069. detail::make_host_and_port_string(
  11070. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11071. // IPv6 full address with non-default port
  11072. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11073. detail::make_host_and_port_string(
  11074. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11075. // IPv6 localhost with non-default port
  11076. EXPECT_EQ("[::1]:3000",
  11077. detail::make_host_and_port_string("::1", 3000, false));
  11078. // IPv6 with zone ID (link-local address) with default port
  11079. EXPECT_EQ("[fe80::1%eth0]",
  11080. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11081. // IPv6 with zone ID (link-local address) with non-default port
  11082. EXPECT_EQ("[fe80::1%eth0]:8080",
  11083. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11084. // Edge case: Port 443 with is_ssl=false (should add port)
  11085. EXPECT_EQ("example.com:443",
  11086. detail::make_host_and_port_string("example.com", 443, false));
  11087. // Edge case: Port 80 with is_ssl=true (should add port)
  11088. EXPECT_EQ("example.com:80",
  11089. detail::make_host_and_port_string("example.com", 80, true));
  11090. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11091. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11092. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11093. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11094. // Security fix: Already bracketed IPv6 should not get double brackets
  11095. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11096. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11097. EXPECT_EQ("[::1]:8080",
  11098. detail::make_host_and_port_string("[::1]", 8080, false));
  11099. EXPECT_EQ("[2001:db8::1]:8080",
  11100. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11101. EXPECT_EQ("[fe80::1%eth0]",
  11102. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11103. EXPECT_EQ("[fe80::1%eth0]:8080",
  11104. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11105. // Edge case: Empty host (should return as-is)
  11106. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11107. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11108. // This is a known limitation but shouldn't crash
  11109. EXPECT_EQ("[host:name]",
  11110. detail::make_host_and_port_string("host:name", 80, false));
  11111. // Port number edge cases (no validation, but should not crash)
  11112. EXPECT_EQ("example.com:0",
  11113. detail::make_host_and_port_string("example.com", 0, false));
  11114. EXPECT_EQ("example.com:-1",
  11115. detail::make_host_and_port_string("example.com", -1, false));
  11116. EXPECT_EQ("example.com:65535",
  11117. detail::make_host_and_port_string("example.com", 65535, false));
  11118. EXPECT_EQ("example.com:65536",
  11119. detail::make_host_and_port_string("example.com", 65536, false));
  11120. }
  11121. #ifdef CPPHTTPLIB_SSL_ENABLED
  11122. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11123. httplib::SSLClient cli("roblox.com", 443);
  11124. cli.set_follow_location(true);
  11125. auto res = cli.Get("/");
  11126. ASSERT_TRUE(res);
  11127. EXPECT_EQ(StatusCode::OK_200, res->status);
  11128. }
  11129. #endif
  11130. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11131. Server svr;
  11132. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11133. EXPECT_EQ(res.status, 400);
  11134. });
  11135. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11136. auto se = detail::scope_exit([&] {
  11137. svr.stop();
  11138. thread.join();
  11139. ASSERT_FALSE(svr.is_running());
  11140. });
  11141. svr.wait_until_ready();
  11142. Client cli(HOST, PORT);
  11143. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11144. }
  11145. TEST(InvalidHeaderCharsTest, is_field_name) {
  11146. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11147. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11148. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11149. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11150. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11151. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11152. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11153. EXPECT_FALSE(detail::fields::is_field_name(""));
  11154. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11155. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11156. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11157. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11158. }
  11159. TEST(InvalidHeaderCharsTest, is_field_value) {
  11160. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11161. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11162. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11163. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11164. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11165. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11166. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11167. EXPECT_TRUE(detail::fields::is_field_value(""));
  11168. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11169. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11170. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11171. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11172. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11173. }
  11174. TEST(InvalidHeaderCharsTest, OnServer) {
  11175. Server svr;
  11176. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11177. std::string header = "Not Set";
  11178. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11179. res.set_header(header, "value");
  11180. res.set_content("Page Content Page Content", "text/plain");
  11181. });
  11182. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11183. std::string header = "Not Set";
  11184. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11185. res.set_header("X-Test", header);
  11186. res.set_content("Page Content Page Content", "text/plain");
  11187. });
  11188. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11189. auto se = detail::scope_exit([&] {
  11190. svr.stop();
  11191. thread.join();
  11192. ASSERT_FALSE(svr.is_running());
  11193. });
  11194. svr.wait_until_ready();
  11195. Client cli(HOST, PORT);
  11196. {
  11197. auto res = cli.Get(
  11198. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11199. ASSERT_TRUE(res);
  11200. EXPECT_EQ("Page Content Page Content", res->body);
  11201. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11202. }
  11203. {
  11204. auto res = cli.Get(
  11205. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11206. ASSERT_TRUE(res);
  11207. EXPECT_EQ("Page Content Page Content", res->body);
  11208. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11209. }
  11210. }
  11211. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11212. auto handled = false;
  11213. Server svr;
  11214. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11215. thread t = thread([&] { svr.listen(HOST, PORT); });
  11216. auto se = detail::scope_exit([&] {
  11217. svr.stop();
  11218. t.join();
  11219. ASSERT_FALSE(svr.is_running());
  11220. ASSERT_FALSE(handled);
  11221. });
  11222. svr.wait_until_ready();
  11223. auto req = "POST /test HTTP/1.1\r\n"
  11224. "Content-Length: x\r\n"
  11225. "\r\n";
  11226. std::string response;
  11227. ASSERT_TRUE(send_request(1, req, &response));
  11228. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11229. response.substr(0, response.find("\r\n")));
  11230. }
  11231. #ifndef _WIN32
  11232. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11233. static constexpr char reject[] = "Unauthorized";
  11234. static constexpr char accept[] = "Upload accepted";
  11235. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11236. Server svr;
  11237. svr.set_expect_100_continue_handler(
  11238. [](const Request & /*req*/, Response &res) {
  11239. res.status = StatusCode::Unauthorized_401;
  11240. res.set_content(reject, "text/plain");
  11241. return res.status;
  11242. });
  11243. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11244. res.set_content(accept, "text/plain");
  11245. });
  11246. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11247. auto se = detail::scope_exit([&] {
  11248. svr.stop();
  11249. thread.join();
  11250. ASSERT_FALSE(svr.is_running());
  11251. });
  11252. svr.wait_until_ready();
  11253. {
  11254. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11255. curl_easy_init(), &curl_easy_cleanup};
  11256. ASSERT_NE(curl, nullptr);
  11257. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11258. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11259. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11260. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11261. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11262. &curl_slist_free_all};
  11263. ASSERT_NE(list, nullptr);
  11264. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11265. struct read_data {
  11266. size_t read_size;
  11267. size_t total_size;
  11268. } data = {0, total_size};
  11269. using read_callback_t =
  11270. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11271. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11272. void *userdata) -> size_t {
  11273. read_data *d = (read_data *)userdata;
  11274. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11275. std::fill_n(ptr, size * nmemb, 'A');
  11276. d->read_size += size * nmemb;
  11277. return size * nmemb;
  11278. };
  11279. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11280. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11281. std::vector<char> buffer;
  11282. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11283. using write_callback_t =
  11284. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11285. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11286. void *userdata) -> size_t {
  11287. std::vector<char> *buf = (std::vector<char> *)userdata;
  11288. buf->reserve(buf->size() + size * nmemb + 1);
  11289. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11290. return size * nmemb;
  11291. };
  11292. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11293. {
  11294. const auto res = curl_easy_perform(curl.get());
  11295. ASSERT_EQ(res, CURLE_OK);
  11296. }
  11297. {
  11298. auto response_code = long{};
  11299. const auto res =
  11300. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11301. ASSERT_EQ(res, CURLE_OK);
  11302. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11303. }
  11304. {
  11305. auto dl = curl_off_t{};
  11306. const auto res =
  11307. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11308. ASSERT_EQ(res, CURLE_OK);
  11309. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11310. }
  11311. {
  11312. buffer.push_back('\0');
  11313. ASSERT_STRCASEEQ(buffer.data(), reject);
  11314. }
  11315. }
  11316. }
  11317. #endif
  11318. template <typename S, typename C>
  11319. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11320. svr.Get("/stream", [&](const Request &, Response &res) {
  11321. auto data = new std::string("01234567890123456789");
  11322. res.set_content_provider(
  11323. data->size(), "text/plain",
  11324. [&, data](size_t offset, size_t length, DataSink &sink) {
  11325. const size_t DATA_CHUNK_SIZE = 4;
  11326. const auto &d = *data;
  11327. std::this_thread::sleep_for(std::chrono::seconds(1));
  11328. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11329. return true;
  11330. },
  11331. [data](bool success) {
  11332. EXPECT_FALSE(success);
  11333. delete data;
  11334. });
  11335. });
  11336. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11337. auto i = new size_t(0);
  11338. res.set_content_provider(
  11339. "text/plain",
  11340. [i](size_t, DataSink &sink) {
  11341. if (*i < 5) {
  11342. std::this_thread::sleep_for(std::chrono::seconds(1));
  11343. sink.write("abcd", 4);
  11344. (*i)++;
  11345. } else {
  11346. sink.done();
  11347. }
  11348. return true;
  11349. },
  11350. [i](bool success) {
  11351. EXPECT_FALSE(success);
  11352. delete i;
  11353. });
  11354. });
  11355. svr.Get("/chunked", [&](const Request &, Response &res) {
  11356. auto i = new size_t(0);
  11357. res.set_chunked_content_provider(
  11358. "text/plain",
  11359. [i](size_t, DataSink &sink) {
  11360. if (*i < 5) {
  11361. std::this_thread::sleep_for(std::chrono::seconds(1));
  11362. sink.os << "abcd";
  11363. (*i)++;
  11364. } else {
  11365. sink.done();
  11366. }
  11367. return true;
  11368. },
  11369. [i](bool success) {
  11370. EXPECT_FALSE(success);
  11371. delete i;
  11372. });
  11373. });
  11374. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11375. auto se = detail::scope_exit([&] {
  11376. svr.stop();
  11377. listen_thread.join();
  11378. ASSERT_FALSE(svr.is_running());
  11379. });
  11380. svr.wait_until_ready();
  11381. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11382. {
  11383. auto start = std::chrono::steady_clock::now();
  11384. auto res = cli.Get("/stream");
  11385. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11386. std::chrono::steady_clock::now() - start)
  11387. .count();
  11388. ASSERT_FALSE(res);
  11389. EXPECT_EQ(Error::Read, res.error());
  11390. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11391. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11392. }
  11393. {
  11394. auto start = std::chrono::steady_clock::now();
  11395. auto res = cli.Get("/stream_without_length");
  11396. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11397. std::chrono::steady_clock::now() - start)
  11398. .count();
  11399. ASSERT_FALSE(res);
  11400. EXPECT_EQ(Error::Read, res.error());
  11401. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11402. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11403. }
  11404. {
  11405. auto start = std::chrono::steady_clock::now();
  11406. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11407. EXPECT_EQ("abcd", string(data, data_length));
  11408. return true;
  11409. });
  11410. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11411. std::chrono::steady_clock::now() - start)
  11412. .count();
  11413. ASSERT_FALSE(res);
  11414. EXPECT_EQ(Error::Read, res.error());
  11415. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11416. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11417. }
  11418. }
  11419. TEST(MaxTimeoutTest, ContentStream) {
  11420. time_t timeout = 2000;
  11421. time_t threshold = 200;
  11422. Server svr;
  11423. Client cli("localhost", PORT);
  11424. max_timeout_test(svr, cli, timeout, threshold);
  11425. }
  11426. #ifdef CPPHTTPLIB_SSL_ENABLED
  11427. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11428. time_t timeout = 2000;
  11429. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11431. SSLClient cli("localhost", PORT);
  11432. cli.enable_server_certificate_verification(false);
  11433. max_timeout_test(svr, cli, timeout, threshold);
  11434. }
  11435. #endif
  11436. class EventDispatcher {
  11437. public:
  11438. EventDispatcher() {}
  11439. bool wait_event(DataSink *sink) {
  11440. unique_lock<mutex> lk(m_);
  11441. int id = id_;
  11442. // Wait with timeout to prevent hanging if client disconnects
  11443. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11444. [&] { return cid_ == id; })) {
  11445. return false; // Timeout occurred
  11446. }
  11447. sink->write(message_.data(), message_.size());
  11448. return true;
  11449. }
  11450. void send_event(const string &message) {
  11451. lock_guard<mutex> lk(m_);
  11452. cid_ = id_++;
  11453. message_ = message;
  11454. cv_.notify_all();
  11455. }
  11456. private:
  11457. mutex m_;
  11458. condition_variable cv_;
  11459. atomic_int id_{0};
  11460. atomic_int cid_{-1};
  11461. string message_;
  11462. };
  11463. TEST(ClientInThreadTest, Issue2068) {
  11464. EventDispatcher ed;
  11465. Server svr;
  11466. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11467. res.set_chunked_content_provider("text/event-stream",
  11468. [&](size_t /*offset*/, DataSink &sink) {
  11469. return ed.wait_event(&sink);
  11470. });
  11471. });
  11472. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11473. svr.wait_until_ready();
  11474. thread event_thread([&] {
  11475. int id = 0;
  11476. while (svr.is_running()) {
  11477. this_thread::sleep_for(chrono::milliseconds(500));
  11478. std::stringstream ss;
  11479. ss << "data: " << id << "\n\n";
  11480. ed.send_event(ss.str());
  11481. id++;
  11482. }
  11483. });
  11484. auto se = detail::scope_exit([&] {
  11485. svr.stop();
  11486. listen_thread.join();
  11487. event_thread.join();
  11488. ASSERT_FALSE(svr.is_running());
  11489. });
  11490. {
  11491. auto client = detail::make_unique<Client>(HOST, PORT);
  11492. client->set_read_timeout(std::chrono::minutes(10));
  11493. std::atomic<bool> stop{false};
  11494. std::thread t([&] {
  11495. client->Get("/event1",
  11496. [&](const char *, size_t) -> bool { return !stop; });
  11497. });
  11498. std::this_thread::sleep_for(std::chrono::seconds(2));
  11499. stop = true;
  11500. client->stop();
  11501. t.join();
  11502. // Reset client after thread has finished
  11503. client.reset();
  11504. }
  11505. }
  11506. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11507. auto handled = false;
  11508. Server svr;
  11509. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11510. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11511. auto se = detail::scope_exit([&] {
  11512. svr.stop();
  11513. t.join();
  11514. ASSERT_FALSE(svr.is_running());
  11515. ASSERT_FALSE(handled);
  11516. });
  11517. svr.wait_until_ready();
  11518. // Two Content-Length headers with different values — must be rejected
  11519. auto req = "POST /test HTTP/1.1\r\n"
  11520. "Content-Length: 5\r\n"
  11521. "Content-Length: 10\r\n"
  11522. "\r\n"
  11523. "hello";
  11524. std::string response;
  11525. ASSERT_TRUE(send_request(1, req, &response));
  11526. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11527. response.substr(0, response.find("\r\n")));
  11528. }
  11529. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11530. auto handled = false;
  11531. Server svr;
  11532. svr.Post("/test", [&](const Request &, Response &res) {
  11533. handled = true;
  11534. res.set_content("ok", "text/plain");
  11535. });
  11536. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11537. auto se = detail::scope_exit([&] {
  11538. svr.stop();
  11539. t.join();
  11540. ASSERT_FALSE(svr.is_running());
  11541. ASSERT_TRUE(handled);
  11542. });
  11543. svr.wait_until_ready();
  11544. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11545. auto req = "POST /test HTTP/1.1\r\n"
  11546. "Content-Length: 5\r\n"
  11547. "Content-Length: 5\r\n"
  11548. "\r\n"
  11549. "hello";
  11550. std::string response;
  11551. ASSERT_TRUE(send_request(1, req, &response));
  11552. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11553. }
  11554. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11555. Server svr;
  11556. svr.Get("/", [](const Request &req, Response &res) {
  11557. EXPECT_EQ(2U, req.trailers.size());
  11558. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11559. // Denied
  11560. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11561. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11562. // Accepted
  11563. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11564. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11565. EXPECT_TRUE(req.has_trailer("X-World"));
  11566. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11567. res.set_content("ok", "text/plain");
  11568. });
  11569. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11570. auto se = detail::scope_exit([&] {
  11571. svr.stop();
  11572. t.join();
  11573. ASSERT_FALSE(svr.is_running());
  11574. });
  11575. svr.wait_until_ready();
  11576. const std::string req = "GET / HTTP/1.1\r\n"
  11577. "Transfer-Encoding: chunked\r\n"
  11578. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11579. "\r\n"
  11580. "0\r\n"
  11581. "Content-Length: 10\r\n"
  11582. "Host: internal.local\r\n"
  11583. "Content-Type: malicious/content\r\n"
  11584. "Cookie: any\r\n"
  11585. "Set-Cookie: any\r\n"
  11586. "X-Forwarded-For: attacker.com\r\n"
  11587. "X-Real-Ip: 1.1.1.1\r\n"
  11588. "X-Hello: hello\r\n"
  11589. "X-World: world\r\n"
  11590. "\r\n";
  11591. std::string res;
  11592. ASSERT_TRUE(send_request(1, req, &res));
  11593. }
  11594. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11595. Server svr;
  11596. std::string observed_remote_addr;
  11597. std::string observed_xff;
  11598. svr.Get("/ip", [&](const Request &req, Response &res) {
  11599. observed_remote_addr = req.remote_addr;
  11600. observed_xff = req.get_header_value("X-Forwarded-For");
  11601. res.set_content("ok", "text/plain");
  11602. });
  11603. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11604. auto se = detail::scope_exit([&] {
  11605. svr.stop();
  11606. t.join();
  11607. ASSERT_FALSE(svr.is_running());
  11608. });
  11609. svr.wait_until_ready();
  11610. Client cli(HOST, PORT);
  11611. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11612. ASSERT_TRUE(res);
  11613. EXPECT_EQ(StatusCode::OK_200, res->status);
  11614. EXPECT_EQ(observed_xff, "203.0.113.66");
  11615. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11616. observed_remote_addr == "127.0.0.1");
  11617. }
  11618. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11619. Server svr;
  11620. svr.set_trusted_proxies({"203.0.113.66"});
  11621. std::string observed_remote_addr;
  11622. std::string observed_xff;
  11623. svr.Get("/ip", [&](const Request &req, Response &res) {
  11624. observed_remote_addr = req.remote_addr;
  11625. observed_xff = req.get_header_value("X-Forwarded-For");
  11626. res.set_content("ok", "text/plain");
  11627. });
  11628. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11629. auto se = detail::scope_exit([&] {
  11630. svr.stop();
  11631. t.join();
  11632. ASSERT_FALSE(svr.is_running());
  11633. });
  11634. svr.wait_until_ready();
  11635. Client cli(HOST, PORT);
  11636. auto res = cli.Get("/ip");
  11637. ASSERT_TRUE(res);
  11638. EXPECT_EQ(StatusCode::OK_200, res->status);
  11639. EXPECT_EQ(observed_xff, "");
  11640. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11641. observed_remote_addr == "127.0.0.1");
  11642. }
  11643. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11644. Server svr;
  11645. svr.set_trusted_proxies({"203.0.113.66"});
  11646. std::string observed_remote_addr;
  11647. std::string observed_xff;
  11648. svr.Get("/ip", [&](const Request &req, Response &res) {
  11649. observed_remote_addr = req.remote_addr;
  11650. observed_xff = req.get_header_value("X-Forwarded-For");
  11651. res.set_content("ok", "text/plain");
  11652. });
  11653. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11654. auto se = detail::scope_exit([&] {
  11655. svr.stop();
  11656. t.join();
  11657. ASSERT_FALSE(svr.is_running());
  11658. });
  11659. svr.wait_until_ready();
  11660. Client cli(HOST, PORT);
  11661. auto res =
  11662. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11663. ASSERT_TRUE(res);
  11664. EXPECT_EQ(StatusCode::OK_200, res->status);
  11665. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11666. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11667. }
  11668. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11669. Server svr;
  11670. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11671. std::string observed_remote_addr;
  11672. std::string observed_xff;
  11673. svr.Get("/ip", [&](const Request &req, Response &res) {
  11674. observed_remote_addr = req.remote_addr;
  11675. observed_xff = req.get_header_value("X-Forwarded-For");
  11676. res.set_content("ok", "text/plain");
  11677. });
  11678. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11679. auto se = detail::scope_exit([&] {
  11680. svr.stop();
  11681. t.join();
  11682. ASSERT_FALSE(svr.is_running());
  11683. });
  11684. svr.wait_until_ready();
  11685. Client cli(HOST, PORT);
  11686. auto res = cli.Get(
  11687. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11688. ASSERT_TRUE(res);
  11689. EXPECT_EQ(StatusCode::OK_200, res->status);
  11690. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11691. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11692. }
  11693. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11694. Server svr;
  11695. svr.set_trusted_proxies({"192.0.2.45"});
  11696. std::string observed_remote_addr;
  11697. std::string observed_xff;
  11698. svr.Get("/ip", [&](const Request &req, Response &res) {
  11699. observed_remote_addr = req.remote_addr;
  11700. observed_xff = req.get_header_value("X-Forwarded-For");
  11701. res.set_content("ok", "text/plain");
  11702. });
  11703. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11704. auto se = detail::scope_exit([&] {
  11705. svr.stop();
  11706. t.join();
  11707. ASSERT_FALSE(svr.is_running());
  11708. });
  11709. svr.wait_until_ready();
  11710. Client cli(HOST, PORT);
  11711. auto res =
  11712. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11713. ASSERT_TRUE(res);
  11714. EXPECT_EQ(StatusCode::OK_200, res->status);
  11715. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11716. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11717. }
  11718. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11719. Server svr;
  11720. svr.set_trusted_proxies({"192.0.2.45"});
  11721. std::string observed_remote_addr;
  11722. std::string observed_xff;
  11723. svr.Get("/ip", [&](const Request &req, Response &res) {
  11724. observed_remote_addr = req.remote_addr;
  11725. observed_xff = req.get_header_value("X-Forwarded-For");
  11726. res.set_content("ok", "text/plain");
  11727. });
  11728. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11729. auto se = detail::scope_exit([&] {
  11730. svr.stop();
  11731. t.join();
  11732. ASSERT_FALSE(svr.is_running());
  11733. });
  11734. svr.wait_until_ready();
  11735. Client cli(HOST, PORT);
  11736. auto res = cli.Get(
  11737. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11738. ASSERT_TRUE(res);
  11739. EXPECT_EQ(StatusCode::OK_200, res->status);
  11740. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11741. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11742. }
  11743. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11744. Server svr;
  11745. svr.set_trusted_proxies({"192.0.2.45"});
  11746. std::string observed_remote_addr;
  11747. std::string observed_xff;
  11748. svr.Get("/ip", [&](const Request &req, Response &res) {
  11749. observed_remote_addr = req.remote_addr;
  11750. observed_xff = req.get_header_value("X-Forwarded-For");
  11751. res.set_content("ok", "text/plain");
  11752. });
  11753. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11754. auto se = detail::scope_exit([&] {
  11755. svr.stop();
  11756. t.join();
  11757. ASSERT_FALSE(svr.is_running());
  11758. });
  11759. svr.wait_until_ready();
  11760. std::string raw_req =
  11761. "GET /ip HTTP/1.1\r\n"
  11762. "Host: localhost\r\n"
  11763. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11764. "Connection: close\r\n"
  11765. "\r\n";
  11766. std::string out;
  11767. ASSERT_TRUE(send_request(5, raw_req, &out));
  11768. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11769. // Header parser trims surrounding whitespace of the header value
  11770. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11771. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11772. }
  11773. #ifndef _WIN32
  11774. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11775. Server svr;
  11776. svr.Post("/post", [&](const Request &req, Response &res) {
  11777. res.set_content(req.body, "text/plain");
  11778. });
  11779. svr.Put("/put", [&](const Request &req, Response &res) {
  11780. res.set_content(req.body, "text/plain");
  11781. });
  11782. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11783. res.set_content(req.body, "text/plain");
  11784. });
  11785. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11786. res.set_content(req.body, "text/plain");
  11787. });
  11788. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11789. auto se = detail::scope_exit([&] {
  11790. svr.stop();
  11791. t.join();
  11792. ASSERT_FALSE(svr.is_running());
  11793. });
  11794. svr.wait_until_ready();
  11795. std::string resp;
  11796. // POST without Content-Length
  11797. ASSERT_TRUE(send_request(5,
  11798. "POST /post HTTP/1.1\r\n"
  11799. "Host: localhost\r\n"
  11800. "Connection: close\r\n"
  11801. "\r\n",
  11802. &resp));
  11803. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11804. // PUT without Content-Length
  11805. resp.clear();
  11806. ASSERT_TRUE(send_request(5,
  11807. "PUT /put HTTP/1.1\r\n"
  11808. "Host: localhost\r\n"
  11809. "Connection: close\r\n"
  11810. "\r\n",
  11811. &resp));
  11812. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11813. // PATCH without Content-Length
  11814. resp.clear();
  11815. ASSERT_TRUE(send_request(5,
  11816. "PATCH /patch HTTP/1.1\r\n"
  11817. "Host: localhost\r\n"
  11818. "Connection: close\r\n"
  11819. "\r\n",
  11820. &resp));
  11821. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11822. // DELETE without Content-Length
  11823. resp.clear();
  11824. ASSERT_TRUE(send_request(5,
  11825. "DELETE /delete HTTP/1.1\r\n"
  11826. "Host: localhost\r\n"
  11827. "Connection: close\r\n"
  11828. "\r\n",
  11829. &resp));
  11830. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11831. }
  11832. #endif
  11833. //==============================================================================
  11834. // open_stream() Tests
  11835. //==============================================================================
  11836. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11837. std::string result;
  11838. char buf[8192];
  11839. ssize_t n;
  11840. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11841. result.append(buf, static_cast<size_t>(n));
  11842. }
  11843. return result;
  11844. }
  11845. // Mock stream for unit tests
  11846. class MockStream : public Stream {
  11847. public:
  11848. std::string data;
  11849. size_t pos = 0;
  11850. ssize_t error_after = -1; // -1 = no error
  11851. explicit MockStream(const std::string &d, ssize_t err = -1)
  11852. : data(d), error_after(err) {}
  11853. bool is_readable() const override { return true; }
  11854. bool wait_readable() const override { return true; }
  11855. bool wait_writable() const override { return true; }
  11856. ssize_t read(char *ptr, size_t size) override {
  11857. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11858. if (pos >= data.size()) return 0;
  11859. size_t limit =
  11860. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11861. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11862. std::memcpy(ptr, data.data() + pos, to_read);
  11863. pos += to_read;
  11864. return static_cast<ssize_t>(to_read);
  11865. }
  11866. ssize_t write(const char *, size_t) override { return -1; }
  11867. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11868. ip = "127.0.0.1";
  11869. port = 0;
  11870. }
  11871. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11872. ip = "127.0.0.1";
  11873. port = 0;
  11874. }
  11875. socket_t socket() const override { return INVALID_SOCKET; }
  11876. time_t duration() const override { return 0; }
  11877. };
  11878. TEST(StreamHandleTest, Basic) {
  11879. ClientImpl::StreamHandle handle;
  11880. EXPECT_FALSE(handle.is_valid());
  11881. handle.response = detail::make_unique<Response>();
  11882. handle.error = Error::Connection;
  11883. EXPECT_FALSE(handle.is_valid());
  11884. handle.error = Error::Success;
  11885. EXPECT_TRUE(handle.is_valid());
  11886. }
  11887. TEST(BodyReaderTest, Basic) {
  11888. MockStream stream("Hello, World!");
  11889. detail::BodyReader reader;
  11890. reader.stream = &stream;
  11891. reader.content_length = 13;
  11892. char buf[32];
  11893. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11894. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11895. EXPECT_TRUE(reader.eof);
  11896. }
  11897. TEST(BodyReaderTest, NoStream) {
  11898. detail::BodyReader reader;
  11899. char buf[32];
  11900. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11901. EXPECT_EQ(Error::Connection, reader.last_error);
  11902. }
  11903. TEST(BodyReaderTest, Error) {
  11904. MockStream stream("Hello, World!", 5);
  11905. detail::BodyReader reader;
  11906. reader.stream = &stream;
  11907. reader.content_length = 13;
  11908. char buf[32];
  11909. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11910. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11911. EXPECT_EQ(Error::Read, reader.last_error);
  11912. }
  11913. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11914. // Mock-based StreamHandle tests relying on private internals are removed.
  11915. class OpenStreamTest : public ::testing::Test {
  11916. protected:
  11917. void SetUp() override {
  11918. svr_.Get("/hello", [](const Request &, Response &res) {
  11919. res.set_content("Hello World!", "text/plain");
  11920. });
  11921. svr_.Get("/large", [](const Request &, Response &res) {
  11922. res.set_content(std::string(10000, 'X'), "text/plain");
  11923. });
  11924. svr_.Get("/chunked", [](const Request &, Response &res) {
  11925. res.set_chunked_content_provider("text/plain",
  11926. [](size_t offset, DataSink &sink) {
  11927. if (offset < 15) {
  11928. sink.write("chunk", 5);
  11929. return true;
  11930. }
  11931. sink.done();
  11932. return true;
  11933. });
  11934. });
  11935. svr_.Get("/compressible", [](const Request &, Response &res) {
  11936. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11937. DataSink &sink) {
  11938. if (offset < 100 * 1024) {
  11939. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11940. sink.write(chunk.data(), chunk.size());
  11941. return true;
  11942. }
  11943. sink.done();
  11944. return true;
  11945. });
  11946. });
  11947. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11948. [](const Request & /*req*/, Response &res) {
  11949. auto i = new int(0);
  11950. res.set_header("Trailer", "Content-Length, X-Allowed");
  11951. res.set_chunked_content_provider(
  11952. "text/plain",
  11953. [i](size_t /*offset*/, DataSink &sink) {
  11954. switch (*i) {
  11955. case 0: sink.os << "123"; break;
  11956. case 1: sink.os << "456"; break;
  11957. case 2: sink.os << "789"; break;
  11958. case 3: {
  11959. sink.done_with_trailer(
  11960. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11961. } break;
  11962. }
  11963. (*i)++;
  11964. return true;
  11965. },
  11966. [i](bool success) {
  11967. EXPECT_TRUE(success);
  11968. delete i;
  11969. });
  11970. });
  11971. // Echo headers endpoint for header-related tests
  11972. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11973. std::string body;
  11974. for (const auto &h : req.headers) {
  11975. body.append(h.first);
  11976. body.push_back(':');
  11977. body.append(h.second);
  11978. body.push_back('\n');
  11979. }
  11980. res.set_content(body, "text/plain");
  11981. });
  11982. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11983. std::string body;
  11984. for (const auto &h : req.headers) {
  11985. body.append(h.first);
  11986. body.push_back(':');
  11987. body.append(h.second);
  11988. body.push_back('\n');
  11989. }
  11990. res.set_content(body, "text/plain");
  11991. });
  11992. port_ = svr_.bind_to_any_port("127.0.0.1");
  11993. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11994. svr_.wait_until_ready();
  11995. }
  11996. void TearDown() override {
  11997. svr_.stop();
  11998. if (thread_.joinable()) thread_.join();
  11999. }
  12000. Server svr_;
  12001. std::thread thread_;
  12002. int port_ = 0;
  12003. };
  12004. TEST_F(OpenStreamTest, Basic) {
  12005. Client cli("127.0.0.1", port_);
  12006. auto handle = cli.open_stream("GET", "/hello");
  12007. EXPECT_TRUE(handle.is_valid());
  12008. EXPECT_EQ("Hello World!", read_all(handle));
  12009. }
  12010. TEST_F(OpenStreamTest, SmallBuffer) {
  12011. Client cli("127.0.0.1", port_);
  12012. auto handle = cli.open_stream("GET", "/hello");
  12013. std::string result;
  12014. char buf[4];
  12015. ssize_t n;
  12016. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12017. result.append(buf, static_cast<size_t>(n));
  12018. EXPECT_EQ("Hello World!", result);
  12019. }
  12020. TEST_F(OpenStreamTest, DefaultHeaders) {
  12021. Client cli("127.0.0.1", port_);
  12022. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12023. {
  12024. auto handle = cli.open_stream("GET", "/echo-headers");
  12025. ASSERT_TRUE(handle.is_valid());
  12026. auto body = read_all(handle);
  12027. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12028. std::string::npos);
  12029. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12030. std::string::npos);
  12031. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12032. }
  12033. // open_stream POST with body and no explicit content_type should NOT add
  12034. // text/plain Content-Type (behavior differs from non-streaming path), but
  12035. // should include Content-Length
  12036. {
  12037. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12038. ASSERT_TRUE(handle.is_valid());
  12039. auto body = read_all(handle);
  12040. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12041. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12042. }
  12043. // open_stream POST with explicit Content-Type should preserve it
  12044. {
  12045. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12046. {{"Content-Type", "application/custom"}},
  12047. "{}", "application/custom");
  12048. ASSERT_TRUE(handle.is_valid());
  12049. auto body = read_all(handle);
  12050. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12051. }
  12052. // User-specified User-Agent must not be overwritten for stream API
  12053. {
  12054. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12055. {{"User-Agent", "MyAgent/1.2"}});
  12056. ASSERT_TRUE(handle.is_valid());
  12057. auto body = read_all(handle);
  12058. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12059. }
  12060. }
  12061. TEST_F(OpenStreamTest, Large) {
  12062. Client cli("127.0.0.1", port_);
  12063. auto handle = cli.open_stream("GET", "/large");
  12064. EXPECT_EQ(10000u, read_all(handle).size());
  12065. }
  12066. TEST_F(OpenStreamTest, ConnectionError) {
  12067. Client cli("127.0.0.1", 9999);
  12068. auto handle = cli.open_stream("GET", "/hello");
  12069. EXPECT_FALSE(handle.is_valid());
  12070. }
  12071. TEST_F(OpenStreamTest, Chunked) {
  12072. Client cli("127.0.0.1", port_);
  12073. auto handle = cli.open_stream("GET", "/chunked");
  12074. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12075. "Transfer-Encoding") == "chunked");
  12076. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12077. }
  12078. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12079. Client cli("127.0.0.1", port_);
  12080. auto handle =
  12081. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12082. ASSERT_TRUE(handle.is_valid());
  12083. // Consume body to allow trailers to be received/parsed
  12084. auto body = read_all(handle);
  12085. // Explicitly parse trailers (ensure trailers are available for assertion)
  12086. handle.parse_trailers_if_needed();
  12087. EXPECT_EQ(std::string("123456789"), body);
  12088. // The response should include a Trailer header declaring both names
  12089. ASSERT_TRUE(handle.response);
  12090. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12091. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12092. handle.response->get_header_value("Trailer"));
  12093. // Prohibited trailer must not be present
  12094. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12095. // Allowed trailer should be present
  12096. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12097. EXPECT_EQ(std::string("yes"),
  12098. handle.response->get_trailer_value("X-Allowed"));
  12099. // Verify trailers are NOT present as regular headers
  12100. EXPECT_EQ(std::string(""),
  12101. handle.response->get_header_value("Content-Length"));
  12102. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12103. }
  12104. static std::thread serve_single_response(std::promise<int> &port_promise,
  12105. const std::string &response) {
  12106. return std::thread([&port_promise, response] {
  12107. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12108. default_socket_options(srv);
  12109. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12110. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12111. sockaddr_in addr{};
  12112. addr.sin_family = AF_INET;
  12113. addr.sin_port = htons(0); // Let OS assign a free port
  12114. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12115. int opt = 1;
  12116. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12117. #ifdef _WIN32
  12118. reinterpret_cast<const char *>(&opt),
  12119. #else
  12120. &opt,
  12121. #endif
  12122. sizeof(opt));
  12123. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12124. ::listen(srv, 1) != 0) {
  12125. port_promise.set_value(-1);
  12126. detail::close_socket(srv);
  12127. return;
  12128. }
  12129. socklen_t addr_len = sizeof(addr);
  12130. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12131. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12132. sockaddr_in cli_addr{};
  12133. socklen_t cli_len = sizeof(cli_addr);
  12134. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12135. if (cli != INVALID_SOCKET) {
  12136. // Read the complete HTTP request (until the blank line that terminates
  12137. // headers) before sending the response. If the server closes the socket
  12138. // while the client's request data is still unread in the kernel receive
  12139. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12140. // connection on both sides: it discards the client's receive buffer
  12141. // (which already holds our response) and causes any in-progress write on
  12142. // the client to fail with ECONNRESET. Reading all request data first
  12143. // ensures close() emits a graceful FIN.
  12144. {
  12145. char rbuf[256];
  12146. std::string req;
  12147. while (req.find("\r\n\r\n") == std::string::npos) {
  12148. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12149. if (n <= 0) { break; }
  12150. req.append(rbuf, static_cast<size_t>(n));
  12151. }
  12152. }
  12153. ::send(cli,
  12154. #ifdef _WIN32
  12155. static_cast<const char *>(response.c_str()),
  12156. static_cast<int>(response.size()),
  12157. #else
  12158. response.c_str(), response.size(),
  12159. #endif
  12160. 0);
  12161. detail::close_socket(cli);
  12162. }
  12163. detail::close_socket(srv);
  12164. });
  12165. }
  12166. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12167. #ifndef _WIN32
  12168. signal(SIGPIPE, SIG_IGN);
  12169. #endif
  12170. std::promise<int> port_promise;
  12171. auto port_future = port_promise.get_future();
  12172. auto server_thread =
  12173. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12174. "Content-Type: text/plain\r\n"
  12175. "Content-Length: not-a-number\r\n"
  12176. "Connection: close\r\n"
  12177. "\r\n"
  12178. "hello");
  12179. auto port = port_future.get();
  12180. ASSERT_GT(port, 0);
  12181. Client cli("127.0.0.1", port);
  12182. auto handle = cli.open_stream("GET", "/");
  12183. EXPECT_FALSE(handle.is_valid());
  12184. server_thread.join();
  12185. }
  12186. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12187. #ifndef _WIN32
  12188. signal(SIGPIPE, SIG_IGN);
  12189. #endif
  12190. std::promise<int> port_promise;
  12191. auto port_future = port_promise.get_future();
  12192. auto server_thread = serve_single_response(
  12193. port_promise, "HTTP/1.1 200 OK\r\n"
  12194. "Content-Type: text/plain\r\n"
  12195. "Content-Length: 99999999999999999999999999\r\n"
  12196. "Connection: close\r\n"
  12197. "\r\n"
  12198. "hello");
  12199. auto port = port_future.get();
  12200. ASSERT_GT(port, 0);
  12201. // Before the fix, std::stoull would throw std::out_of_range here and
  12202. // crash the process. After the fix, strtoull silently clamps to
  12203. // ULLONG_MAX so the stream opens without crashing. The important thing
  12204. // is that the process does NOT terminate.
  12205. Client cli("127.0.0.1", port);
  12206. auto handle = cli.open_stream("GET", "/");
  12207. EXPECT_TRUE(handle.is_valid());
  12208. server_thread.join();
  12209. }
  12210. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12211. TEST_F(OpenStreamTest, Gzip) {
  12212. Client cli("127.0.0.1", port_);
  12213. auto handle = cli.open_stream("GET", "/compressible", {},
  12214. {{"Accept-Encoding", "gzip"}});
  12215. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12216. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12217. }
  12218. #endif
  12219. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12220. TEST_F(OpenStreamTest, Brotli) {
  12221. Client cli("127.0.0.1", port_);
  12222. auto handle =
  12223. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12224. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12225. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12226. }
  12227. #endif
  12228. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12229. TEST_F(OpenStreamTest, Zstd) {
  12230. Client cli("127.0.0.1", port_);
  12231. auto handle = cli.open_stream("GET", "/compressible", {},
  12232. {{"Accept-Encoding", "zstd"}});
  12233. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12234. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12235. }
  12236. #endif
  12237. #ifdef CPPHTTPLIB_SSL_ENABLED
  12238. class SSLOpenStreamTest : public ::testing::Test {
  12239. protected:
  12240. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12241. void SetUp() override {
  12242. svr_.Get("/hello", [](const Request &, Response &res) {
  12243. res.set_content("Hello SSL World!", "text/plain");
  12244. });
  12245. svr_.Get("/chunked", [](const Request &, Response &res) {
  12246. res.set_chunked_content_provider("text/plain",
  12247. [](size_t offset, DataSink &sink) {
  12248. if (offset < 15) {
  12249. sink.write("chunk", 5);
  12250. return true;
  12251. }
  12252. sink.done();
  12253. return true;
  12254. });
  12255. });
  12256. svr_.Post("/echo", [](const Request &req, Response &res) {
  12257. res.set_content(req.body, req.get_header_value("Content-Type"));
  12258. });
  12259. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12260. std::string body = req.body;
  12261. res.set_chunked_content_provider(
  12262. "text/plain", [body](size_t offset, DataSink &sink) {
  12263. if (offset < body.size()) {
  12264. sink.write(body.data() + offset, body.size() - offset);
  12265. }
  12266. sink.done();
  12267. return true;
  12268. });
  12269. });
  12270. port_ = svr_.bind_to_any_port("127.0.0.1");
  12271. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12272. svr_.wait_until_ready();
  12273. }
  12274. void TearDown() override {
  12275. svr_.stop();
  12276. if (thread_.joinable()) thread_.join();
  12277. }
  12278. SSLServer svr_;
  12279. std::thread thread_;
  12280. int port_ = 0;
  12281. };
  12282. TEST_F(SSLOpenStreamTest, Basic) {
  12283. SSLClient cli("127.0.0.1", port_);
  12284. cli.enable_server_certificate_verification(false);
  12285. auto handle = cli.open_stream("GET", "/hello");
  12286. ASSERT_TRUE(handle.is_valid());
  12287. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12288. }
  12289. TEST_F(SSLOpenStreamTest, Chunked) {
  12290. SSLClient cli("127.0.0.1", port_);
  12291. cli.enable_server_certificate_verification(false);
  12292. auto handle = cli.open_stream("GET", "/chunked");
  12293. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12294. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12295. "Transfer-Encoding") == "chunked");
  12296. auto body = read_all(handle);
  12297. EXPECT_EQ("chunkchunkchunk", body);
  12298. }
  12299. TEST_F(SSLOpenStreamTest, Post) {
  12300. SSLClient cli("127.0.0.1", port_);
  12301. cli.enable_server_certificate_verification(false);
  12302. auto handle =
  12303. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12304. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12305. EXPECT_EQ(200, handle.response->status);
  12306. auto body = read_all(handle);
  12307. EXPECT_EQ("Hello SSL POST", body);
  12308. }
  12309. TEST_F(SSLOpenStreamTest, PostChunked) {
  12310. SSLClient cli("127.0.0.1", port_);
  12311. cli.enable_server_certificate_verification(false);
  12312. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12313. "Chunked SSL Data", "text/plain");
  12314. ASSERT_TRUE(handle.is_valid());
  12315. EXPECT_EQ(200, handle.response->status);
  12316. auto body = read_all(handle);
  12317. EXPECT_EQ("Chunked SSL Data", body);
  12318. }
  12319. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12320. // Content-Length is terminated by the server closing the connection. When the
  12321. // SSL peer sends a close_notify after the body, the client must treat it as a
  12322. // clean EOF and return a successful response rather than an error.
  12323. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12325. ASSERT_TRUE(svr.is_valid());
  12326. svr.set_keep_alive_max_count(1);
  12327. const std::string expected_body = "Hello from connection-close response!";
  12328. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12329. res.set_content_provider("text/plain",
  12330. [&](size_t offset, DataSink &sink) -> bool {
  12331. if (offset < expected_body.size()) {
  12332. sink.write(expected_body.data() + offset,
  12333. expected_body.size() - offset);
  12334. }
  12335. sink.done();
  12336. return true;
  12337. });
  12338. });
  12339. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12340. auto se = detail::scope_exit([&] {
  12341. svr.stop();
  12342. listen_thread.join();
  12343. ASSERT_FALSE(svr.is_running());
  12344. });
  12345. svr.wait_until_ready();
  12346. SSLClient cli(HOST, PORT);
  12347. cli.enable_server_certificate_verification(false);
  12348. auto res = cli.Get("/no-content-length");
  12349. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12350. EXPECT_EQ(StatusCode::OK_200, res->status);
  12351. EXPECT_EQ(expected_body, res->body);
  12352. }
  12353. #endif // CPPHTTPLIB_SSL_ENABLED
  12354. //==============================================================================
  12355. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12356. // results for various scenarios.
  12357. //==============================================================================
  12358. TEST(ParityTest, GetVsOpenStream) {
  12359. Server svr;
  12360. const std::string path = "/parity";
  12361. const std::string content = "Parity test content: hello world";
  12362. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12363. res.set_content(content, "text/plain");
  12364. });
  12365. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12366. auto se = detail::scope_exit([&] {
  12367. svr.stop();
  12368. t.join();
  12369. ASSERT_FALSE(svr.is_running());
  12370. });
  12371. svr.wait_until_ready();
  12372. Client cli(HOST, PORT);
  12373. // Non-stream path
  12374. auto r1 = cli.Get(path);
  12375. ASSERT_TRUE(r1);
  12376. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12377. // Stream path
  12378. auto h = cli.open_stream("GET", path);
  12379. ASSERT_TRUE(h.is_valid());
  12380. EXPECT_EQ(r1->body, read_all(h));
  12381. }
  12382. // Helper to compress data with provided compressor type T
  12383. template <typename Compressor>
  12384. static std::string compress_payload_for_parity(const std::string &in) {
  12385. std::string out;
  12386. Compressor compressor;
  12387. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12388. [&](const char *data, size_t n) {
  12389. out.append(data, n);
  12390. return true;
  12391. });
  12392. EXPECT_TRUE(ok);
  12393. return out;
  12394. }
  12395. // Helper function for compression parity tests
  12396. template <typename Compressor>
  12397. static void test_compression_parity(const std::string &original,
  12398. const std::string &path,
  12399. const std::string &encoding) {
  12400. const std::string compressed =
  12401. compress_payload_for_parity<Compressor>(original);
  12402. Server svr;
  12403. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12404. res.set_content(compressed, "application/octet-stream");
  12405. res.set_header("Content-Encoding", encoding);
  12406. });
  12407. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12408. auto se = detail::scope_exit([&] {
  12409. svr.stop();
  12410. t.join();
  12411. ASSERT_FALSE(svr.is_running());
  12412. });
  12413. svr.wait_until_ready();
  12414. Client cli(HOST, PORT);
  12415. // Non-streaming
  12416. {
  12417. auto res = cli.Get(path);
  12418. ASSERT_TRUE(res);
  12419. EXPECT_EQ(StatusCode::OK_200, res->status);
  12420. EXPECT_EQ(original, res->body);
  12421. }
  12422. // Streaming
  12423. {
  12424. auto h = cli.open_stream("GET", path);
  12425. ASSERT_TRUE(h.is_valid());
  12426. EXPECT_EQ(original, read_all(h));
  12427. }
  12428. }
  12429. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12430. TEST(ParityTest, Gzip) {
  12431. test_compression_parity<detail::gzip_compressor>(
  12432. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12433. }
  12434. #endif
  12435. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12436. TEST(ParityTest, Brotli) {
  12437. test_compression_parity<detail::brotli_compressor>(
  12438. "Hello, brotli parity test payload", "/parity-br", "br");
  12439. }
  12440. #endif
  12441. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12442. TEST(ParityTest, Zstd) {
  12443. test_compression_parity<detail::zstd_compressor>(
  12444. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12445. }
  12446. #endif
  12447. //==============================================================================
  12448. // New Stream API Tests
  12449. //==============================================================================
  12450. inline std::string read_body(httplib::stream::Result &result) {
  12451. std::string body;
  12452. while (result.next()) {
  12453. body.append(result.data(), result.size());
  12454. }
  12455. return body;
  12456. }
  12457. TEST(ClientConnectionTest, Basic) {
  12458. httplib::ClientConnection conn;
  12459. EXPECT_FALSE(conn.is_open());
  12460. conn.sock = 1;
  12461. EXPECT_TRUE(conn.is_open());
  12462. httplib::ClientConnection conn2(std::move(conn));
  12463. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12464. conn2.sock = INVALID_SOCKET;
  12465. }
  12466. // Unified test server for all stream::* tests
  12467. class StreamApiTest : public ::testing::Test {
  12468. protected:
  12469. void SetUp() override {
  12470. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12471. res.set_content("Hello World!", "text/plain");
  12472. });
  12473. svr_.Get("/echo-params",
  12474. [](const httplib::Request &req, httplib::Response &res) {
  12475. std::string r;
  12476. for (const auto &p : req.params) {
  12477. if (!r.empty()) r += "&";
  12478. r += p.first + "=" + p.second;
  12479. }
  12480. res.set_content(r, "text/plain");
  12481. });
  12482. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12483. res.set_content(req.body, req.get_header_value("Content-Type"));
  12484. });
  12485. svr_.Post("/echo-headers",
  12486. [](const httplib::Request &req, httplib::Response &res) {
  12487. std::string r;
  12488. for (const auto &h : req.headers)
  12489. r += h.first + ": " + h.second + "\n";
  12490. res.set_content(r, "text/plain");
  12491. });
  12492. svr_.Post("/echo-params",
  12493. [](const httplib::Request &req, httplib::Response &res) {
  12494. std::string r = "params:";
  12495. for (const auto &p : req.params)
  12496. r += p.first + "=" + p.second + ";";
  12497. res.set_content(r + " body:" + req.body, "text/plain");
  12498. });
  12499. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12500. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12501. });
  12502. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12503. res.set_content("PUT:" + req.body, "text/plain");
  12504. });
  12505. svr_.Patch("/echo",
  12506. [](const httplib::Request &req, httplib::Response &res) {
  12507. res.set_content("PATCH:" + req.body, "text/plain");
  12508. });
  12509. svr_.Delete(
  12510. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12511. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12512. "text/plain");
  12513. });
  12514. svr_.Get("/head-test",
  12515. [](const httplib::Request &, httplib::Response &res) {
  12516. res.set_content("body for HEAD", "text/plain");
  12517. });
  12518. svr_.Options("/options",
  12519. [](const httplib::Request &, httplib::Response &res) {
  12520. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12521. });
  12522. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12523. svr_.wait_until_ready();
  12524. }
  12525. void TearDown() override {
  12526. svr_.stop();
  12527. if (thread_.joinable()) thread_.join();
  12528. }
  12529. httplib::Server svr_;
  12530. std::thread thread_;
  12531. };
  12532. // stream::Get tests
  12533. TEST_F(StreamApiTest, GetBasic) {
  12534. httplib::Client cli(HOST, PORT);
  12535. auto result = httplib::stream::Get(cli, "/hello");
  12536. ASSERT_TRUE(result.is_valid());
  12537. EXPECT_EQ(200, result.status());
  12538. EXPECT_EQ("Hello World!", read_body(result));
  12539. }
  12540. TEST_F(StreamApiTest, GetWithParams) {
  12541. httplib::Client cli(HOST, PORT);
  12542. httplib::Params params{{"foo", "bar"}};
  12543. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12544. ASSERT_TRUE(result.is_valid());
  12545. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12546. }
  12547. TEST_F(StreamApiTest, GetConnectionError) {
  12548. httplib::Client cli(HOST, 9999);
  12549. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12550. }
  12551. TEST_F(StreamApiTest, Get404) {
  12552. httplib::Client cli(HOST, PORT);
  12553. auto result = httplib::stream::Get(cli, "/nonexistent");
  12554. EXPECT_TRUE(result.is_valid());
  12555. EXPECT_EQ(404, result.status());
  12556. }
  12557. // stream::Post tests
  12558. TEST_F(StreamApiTest, PostBasic) {
  12559. httplib::Client cli(HOST, PORT);
  12560. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12561. "application/json");
  12562. ASSERT_TRUE(result.is_valid());
  12563. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12564. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12565. }
  12566. TEST_F(StreamApiTest, PostWithHeaders) {
  12567. httplib::Client cli(HOST, PORT);
  12568. httplib::Headers headers{{"X-Custom", "value"}};
  12569. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12570. "text/plain");
  12571. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12572. }
  12573. TEST_F(StreamApiTest, PostWithParams) {
  12574. httplib::Client cli(HOST, PORT);
  12575. httplib::Params params{{"k", "v"}};
  12576. auto result =
  12577. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12578. auto body = read_body(result);
  12579. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12580. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12581. }
  12582. TEST_F(StreamApiTest, PostLarge) {
  12583. httplib::Client cli(HOST, PORT);
  12584. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12585. size_t total = 0;
  12586. while (result.next()) {
  12587. total += result.size();
  12588. }
  12589. EXPECT_EQ(100u * 1024u, total);
  12590. }
  12591. // stream::Put/Patch tests
  12592. TEST_F(StreamApiTest, PutAndPatch) {
  12593. httplib::Client cli(HOST, PORT);
  12594. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12595. EXPECT_EQ("PUT:test", read_body(put));
  12596. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12597. EXPECT_EQ("PATCH:test", read_body(patch));
  12598. }
  12599. // stream::Delete tests
  12600. TEST_F(StreamApiTest, Delete) {
  12601. httplib::Client cli(HOST, PORT);
  12602. auto del1 = httplib::stream::Delete(cli, "/resource");
  12603. EXPECT_EQ("Deleted", read_body(del1));
  12604. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12605. EXPECT_EQ("Deleted:data", read_body(del2));
  12606. }
  12607. // stream::Head/Options tests
  12608. TEST_F(StreamApiTest, HeadAndOptions) {
  12609. httplib::Client cli(HOST, PORT);
  12610. auto head = httplib::stream::Head(cli, "/head-test");
  12611. EXPECT_TRUE(head.is_valid());
  12612. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12613. auto opts = httplib::stream::Options(cli, "/options");
  12614. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12615. }
  12616. // SSL stream::* tests
  12617. #ifdef CPPHTTPLIB_SSL_ENABLED
  12618. class SSLStreamApiTest : public ::testing::Test {
  12619. protected:
  12620. void SetUp() override {
  12621. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12622. res.set_content("Hello SSL!", "text/plain");
  12623. });
  12624. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12625. res.set_content(req.body, "text/plain");
  12626. });
  12627. port_ = svr_.bind_to_any_port("127.0.0.1");
  12628. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12629. svr_.wait_until_ready();
  12630. }
  12631. void TearDown() override {
  12632. svr_.stop();
  12633. if (thread_.joinable()) thread_.join();
  12634. }
  12635. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12636. std::thread thread_;
  12637. int port_ = 0;
  12638. };
  12639. TEST_F(SSLStreamApiTest, GetAndPost) {
  12640. httplib::SSLClient cli("127.0.0.1", port_);
  12641. cli.enable_server_certificate_verification(false);
  12642. auto get = httplib::stream::Get(cli, "/hello");
  12643. EXPECT_EQ("Hello SSL!", read_body(get));
  12644. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12645. EXPECT_EQ("test", read_body(post));
  12646. }
  12647. #endif
  12648. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12649. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12650. // BodyReader
  12651. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12652. // Test that read timeout during streaming is detected
  12653. // Use a large content-length response where server delays mid-stream
  12654. Server svr;
  12655. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12656. // Send a large response with delay in the middle
  12657. res.set_content_provider(
  12658. 1000, // content_length
  12659. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12660. if (offset < 100) {
  12661. // Send first 100 bytes immediately
  12662. std::string data(100, 'A');
  12663. sink.write(data.c_str(), data.size());
  12664. return true;
  12665. }
  12666. // Then delay longer than client timeout
  12667. std::this_thread::sleep_for(std::chrono::seconds(3));
  12668. std::string data(900, 'B');
  12669. sink.write(data.c_str(), data.size());
  12670. return true;
  12671. });
  12672. });
  12673. auto port = 8091;
  12674. std::thread t([&]() { svr.listen("localhost", port); });
  12675. svr.wait_until_ready();
  12676. Client cli("localhost", port);
  12677. cli.set_read_timeout(1, 0); // 1 second timeout
  12678. auto handle = cli.open_stream("GET", "/slow-stream");
  12679. ASSERT_TRUE(handle.is_valid());
  12680. char buf[256];
  12681. ssize_t total = 0;
  12682. ssize_t n;
  12683. bool got_error = false;
  12684. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12685. total += n;
  12686. }
  12687. if (n < 0) {
  12688. got_error = true;
  12689. // Should be timeout or read error
  12690. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12691. handle.get_read_error() == Error::Read)
  12692. << "Actual error: " << to_string(handle.get_read_error());
  12693. }
  12694. // Either we got an error, or we got less data than expected
  12695. EXPECT_TRUE(got_error || total < 1000)
  12696. << "Expected timeout but got all " << total << " bytes";
  12697. svr.stop();
  12698. t.join();
  12699. }
  12700. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12701. // Test connection closed detection via BodyReader
  12702. Server svr;
  12703. std::atomic<bool> close_now{false};
  12704. svr.Get("/will-close", [&](const Request &, Response &res) {
  12705. res.set_content_provider(
  12706. 10000, // Large content_length that we won't fully send
  12707. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12708. if (offset < 100) {
  12709. std::string data(100, 'X');
  12710. sink.write(data.c_str(), data.size());
  12711. return true;
  12712. }
  12713. // Wait for signal then abort
  12714. while (!close_now) {
  12715. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12716. }
  12717. return false; // Abort - server will close connection
  12718. });
  12719. });
  12720. auto port = 8092;
  12721. std::thread t([&]() { svr.listen("localhost", port); });
  12722. svr.wait_until_ready();
  12723. Client cli("localhost", port);
  12724. auto handle = cli.open_stream("GET", "/will-close");
  12725. ASSERT_TRUE(handle.is_valid());
  12726. char buf[256];
  12727. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12728. EXPECT_GT(n, 0) << "First read should succeed";
  12729. // Signal server to close
  12730. close_now = true;
  12731. // Keep reading until error or EOF
  12732. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12733. // Keep reading
  12734. }
  12735. // Should get an error since content_length wasn't satisfied
  12736. if (n < 0) {
  12737. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12738. handle.get_read_error() == Error::Read)
  12739. << "Actual error: " << to_string(handle.get_read_error());
  12740. }
  12741. svr.stop();
  12742. t.join();
  12743. }
  12744. #ifdef CPPHTTPLIB_SSL_ENABLED
  12745. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12746. // Test that read timeout during SSL streaming is detected
  12747. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12748. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12749. res.set_content_provider(
  12750. 1000, "text/plain",
  12751. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12752. if (offset < 100) {
  12753. std::string data(100, 'A');
  12754. sink.write(data.c_str(), data.size());
  12755. return true;
  12756. }
  12757. std::this_thread::sleep_for(std::chrono::seconds(3));
  12758. std::string data(900, 'B');
  12759. sink.write(data.c_str(), data.size());
  12760. return true;
  12761. });
  12762. });
  12763. auto port = 8093;
  12764. std::thread t([&]() { svr.listen("localhost", port); });
  12765. svr.wait_until_ready();
  12766. SSLClient cli("localhost", port);
  12767. cli.enable_server_certificate_verification(false);
  12768. cli.set_read_timeout(1, 0); // 1 second timeout
  12769. auto handle = cli.open_stream("GET", "/slow-stream");
  12770. ASSERT_TRUE(handle.is_valid());
  12771. char buf[256];
  12772. ssize_t total = 0;
  12773. ssize_t n;
  12774. bool got_error = false;
  12775. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12776. total += n;
  12777. }
  12778. if (n < 0) {
  12779. got_error = true;
  12780. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12781. handle.get_read_error() == Error::Read)
  12782. << "Actual error: " << to_string(handle.get_read_error());
  12783. }
  12784. EXPECT_TRUE(got_error || total < 1000)
  12785. << "Expected timeout but got all " << total << " bytes";
  12786. svr.stop();
  12787. t.join();
  12788. }
  12789. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12790. // Test SSL connection closed detection
  12791. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12792. std::atomic<bool> close_now{false};
  12793. svr.Get("/will-close", [&](const Request &, Response &res) {
  12794. res.set_content_provider(
  12795. 10000, "text/plain",
  12796. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12797. if (offset < 100) {
  12798. std::string data(100, 'X');
  12799. sink.write(data.c_str(), data.size());
  12800. return true;
  12801. }
  12802. while (!close_now) {
  12803. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12804. }
  12805. return false;
  12806. });
  12807. });
  12808. auto port = 8094;
  12809. std::thread t([&]() { svr.listen("localhost", port); });
  12810. svr.wait_until_ready();
  12811. SSLClient cli("localhost", port);
  12812. cli.enable_server_certificate_verification(false);
  12813. auto handle = cli.open_stream("GET", "/will-close");
  12814. ASSERT_TRUE(handle.is_valid());
  12815. char buf[256];
  12816. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12817. EXPECT_GT(n, 0);
  12818. // Signal server to close
  12819. close_now = true;
  12820. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12821. // Keep reading
  12822. }
  12823. if (n < 0) {
  12824. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12825. handle.get_read_error() == Error::Read)
  12826. << "Actual error: " << to_string(handle.get_read_error());
  12827. }
  12828. svr.stop();
  12829. t.join();
  12830. }
  12831. #endif
  12832. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12833. using namespace httplib;
  12834. // Create a test file
  12835. const char *fname = "etag_testfile.txt";
  12836. const char *content = "etag-content";
  12837. {
  12838. std::ofstream ofs(fname);
  12839. ofs << content;
  12840. ASSERT_TRUE(ofs.good());
  12841. }
  12842. Server svr;
  12843. svr.set_mount_point("/static", ".");
  12844. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12845. svr.wait_until_ready();
  12846. Client cli(HOST, PORT);
  12847. // First request: should get 200 with ETag header
  12848. auto res1 = cli.Get("/static/etag_testfile.txt");
  12849. ASSERT_TRUE(res1);
  12850. ASSERT_EQ(200, res1->status);
  12851. ASSERT_TRUE(res1->has_header("ETag"));
  12852. std::string etag = res1->get_header_value("ETag");
  12853. EXPECT_FALSE(etag.empty());
  12854. // Verify ETag format: W/"hex-hex"
  12855. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12856. EXPECT_EQ('W', etag[0]);
  12857. EXPECT_EQ('/', etag[1]);
  12858. EXPECT_EQ('"', etag[2]);
  12859. EXPECT_EQ('"', etag.back());
  12860. // Exact match: expect 304 Not Modified
  12861. Headers h2 = {{"If-None-Match", etag}};
  12862. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12863. ASSERT_TRUE(res2);
  12864. EXPECT_EQ(304, res2->status);
  12865. // Wildcard match: expect 304 Not Modified
  12866. Headers h3 = {{"If-None-Match", "*"}};
  12867. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12868. ASSERT_TRUE(res3);
  12869. EXPECT_EQ(304, res3->status);
  12870. // Non-matching ETag: expect 200
  12871. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12872. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12873. ASSERT_TRUE(res4);
  12874. EXPECT_EQ(200, res4->status);
  12875. // Multiple ETags with one matching: expect 304
  12876. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12877. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12878. ASSERT_TRUE(res5);
  12879. EXPECT_EQ(304, res5->status);
  12880. svr.stop();
  12881. t.join();
  12882. std::remove(fname);
  12883. }
  12884. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12885. using namespace httplib;
  12886. Server svr;
  12887. svr.set_mount_point("/static", ".");
  12888. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12889. svr.wait_until_ready();
  12890. Client cli(HOST, PORT);
  12891. // Send If-None-Match: * to a non-existent file
  12892. Headers h = {{"If-None-Match", "*"}};
  12893. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12894. ASSERT_TRUE(res);
  12895. EXPECT_EQ(404, res->status);
  12896. svr.stop();
  12897. t.join();
  12898. }
  12899. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12900. using namespace httplib;
  12901. // Create a test file
  12902. const char *fname = "etag_boundary_testfile.txt";
  12903. const char *content = "boundary-test";
  12904. {
  12905. std::ofstream ofs(fname);
  12906. ofs << content;
  12907. ASSERT_TRUE(ofs.good());
  12908. }
  12909. Server svr;
  12910. svr.set_mount_point("/static", ".");
  12911. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12912. svr.wait_until_ready();
  12913. Client cli(HOST, PORT);
  12914. // Get the actual ETag
  12915. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12916. ASSERT_TRUE(res1);
  12917. ASSERT_EQ(200, res1->status);
  12918. ASSERT_TRUE(res1->has_header("ETag"));
  12919. std::string etag = res1->get_header_value("ETag");
  12920. // Test 1: Very long ETag value (longer than actual ETag)
  12921. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12922. Headers h1 = {{"If-None-Match", "W/"
  12923. "\"very-long-etag-value-that-is-much-longer-"
  12924. "than-the-actual-etag-value\""}};
  12925. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12926. ASSERT_TRUE(res2);
  12927. EXPECT_EQ(200, res2->status); // Should not match
  12928. // Test 2: Long string followed by wildcard
  12929. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12930. // string)
  12931. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12932. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12933. ASSERT_TRUE(res3);
  12934. EXPECT_EQ(304, res3->status); // Should match on "*"
  12935. // Test 3: Wildcard followed by long string
  12936. // Should match on "*" immediately and return 304
  12937. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12938. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12939. ASSERT_TRUE(res4);
  12940. EXPECT_EQ(304, res4->status); // Should match on "*"
  12941. // Test 4: Multiple long non-matching values
  12942. // Should NOT match and return 200 (test that all comparisons are safe)
  12943. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12944. "W/\"second-long-non-matching-value\", "
  12945. "W/\"third-long-non-matching-value\""}};
  12946. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12947. ASSERT_TRUE(res5);
  12948. EXPECT_EQ(200, res5->status); // Should not match
  12949. // Test 5: Single character that is not "*" (edge case)
  12950. Headers h5 = {{"If-None-Match", "X"}};
  12951. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12952. ASSERT_TRUE(res6);
  12953. EXPECT_EQ(200, res6->status); // Should not match
  12954. svr.stop();
  12955. t.join();
  12956. std::remove(fname);
  12957. }
  12958. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12959. using namespace httplib;
  12960. // Create a test file
  12961. const char *fname = "ims_testfile.txt";
  12962. const char *content = "if-modified-since-test";
  12963. {
  12964. std::ofstream ofs(fname);
  12965. ofs << content;
  12966. ASSERT_TRUE(ofs.good());
  12967. }
  12968. Server svr;
  12969. svr.set_mount_point("/static", ".");
  12970. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12971. svr.wait_until_ready();
  12972. Client cli(HOST, PORT);
  12973. // First request: should get 200 with Last-Modified header
  12974. auto res1 = cli.Get("/static/ims_testfile.txt");
  12975. ASSERT_TRUE(res1);
  12976. ASSERT_EQ(200, res1->status);
  12977. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12978. std::string last_modified = res1->get_header_value("Last-Modified");
  12979. EXPECT_FALSE(last_modified.empty());
  12980. // If-Modified-Since with same time: expect 304
  12981. Headers h2 = {{"If-Modified-Since", last_modified}};
  12982. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12983. ASSERT_TRUE(res2);
  12984. EXPECT_EQ(304, res2->status);
  12985. // If-Modified-Since with future time: expect 304
  12986. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12987. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12988. ASSERT_TRUE(res3);
  12989. EXPECT_EQ(304, res3->status);
  12990. // If-Modified-Since with past time: expect 200
  12991. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12992. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12993. ASSERT_TRUE(res4);
  12994. EXPECT_EQ(200, res4->status);
  12995. // If-None-Match takes precedence over If-Modified-Since
  12996. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12997. ASSERT_TRUE(res1->has_header("ETag"));
  12998. std::string etag = res1->get_header_value("ETag");
  12999. Headers h5 = {{"If-None-Match", etag},
  13000. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13001. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13002. ASSERT_TRUE(res5);
  13003. EXPECT_EQ(304, res5->status);
  13004. svr.stop();
  13005. t.join();
  13006. std::remove(fname);
  13007. }
  13008. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13009. using namespace httplib;
  13010. Server svr;
  13011. // Endpoint that returns compressible content
  13012. svr.Get("/compressible", [](const Request &, Response &res) {
  13013. // Return a large enough body to trigger compression
  13014. std::string body(1000, 'a');
  13015. res.set_content(body, "text/plain");
  13016. });
  13017. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13018. svr.wait_until_ready();
  13019. Client cli(HOST, PORT);
  13020. // Request with gzip support: should get Vary header when compressed
  13021. cli.set_compress(true);
  13022. auto res1 = cli.Get("/compressible");
  13023. ASSERT_TRUE(res1);
  13024. EXPECT_EQ(200, res1->status);
  13025. // If Content-Encoding is set, Vary should also be set
  13026. if (res1->has_header("Content-Encoding")) {
  13027. EXPECT_TRUE(res1->has_header("Vary"));
  13028. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13029. }
  13030. // Request without Accept-Encoding header: should not have compression
  13031. Headers h_no_compress;
  13032. auto res2 = cli.Get("/compressible", h_no_compress);
  13033. ASSERT_TRUE(res2);
  13034. EXPECT_EQ(200, res2->status);
  13035. // Verify Vary header is present when compression is applied
  13036. // (the exact behavior depends on server configuration)
  13037. svr.stop();
  13038. t.join();
  13039. }
  13040. TEST(ETagTest, IfRangeWithETag) {
  13041. using namespace httplib;
  13042. // Create a test file with known content
  13043. const char *fname = "if_range_testfile.txt";
  13044. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13045. {
  13046. std::ofstream ofs(fname);
  13047. ofs << content;
  13048. ASSERT_TRUE(ofs.good());
  13049. }
  13050. Server svr;
  13051. svr.set_mount_point("/static", ".");
  13052. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13053. svr.wait_until_ready();
  13054. Client cli(HOST, PORT);
  13055. // First request: get ETag
  13056. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13057. ASSERT_TRUE(res1);
  13058. ASSERT_EQ(200, res1->status);
  13059. ASSERT_TRUE(res1->has_header("ETag"));
  13060. std::string etag = res1->get_header_value("ETag");
  13061. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13062. // Since our server generates weak ETags (W/"..."), If-Range with our
  13063. // ETag should NOT result in partial content - it should return full content.
  13064. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13065. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13066. ASSERT_TRUE(res2);
  13067. // Weak ETag in If-Range -> full content (200), not partial (206)
  13068. EXPECT_EQ(200, res2->status);
  13069. EXPECT_EQ(content, res2->body);
  13070. EXPECT_FALSE(res2->has_header("Content-Range"));
  13071. // Range request with non-matching If-Range (ETag): should get 200 (full
  13072. // content)
  13073. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13074. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13075. ASSERT_TRUE(res3);
  13076. EXPECT_EQ(200, res3->status);
  13077. EXPECT_EQ(content, res3->body);
  13078. EXPECT_FALSE(res3->has_header("Content-Range"));
  13079. // Range request with strong ETag (hypothetical - our server doesn't generate
  13080. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13081. // should return full content)
  13082. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13083. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13084. ASSERT_TRUE(res4);
  13085. EXPECT_EQ(200, res4->status);
  13086. EXPECT_EQ(content, res4->body);
  13087. EXPECT_FALSE(res4->has_header("Content-Range"));
  13088. svr.stop();
  13089. t.join();
  13090. std::remove(fname);
  13091. }
  13092. TEST(ETagTest, IfRangeWithDate) {
  13093. using namespace httplib;
  13094. // Create a test file
  13095. const char *fname = "if_range_date_testfile.txt";
  13096. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13097. {
  13098. std::ofstream ofs(fname);
  13099. ofs << content;
  13100. ASSERT_TRUE(ofs.good());
  13101. }
  13102. Server svr;
  13103. svr.set_mount_point("/static", ".");
  13104. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13105. svr.wait_until_ready();
  13106. Client cli(HOST, PORT);
  13107. // First request: get Last-Modified
  13108. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13109. ASSERT_TRUE(res1);
  13110. ASSERT_EQ(200, res1->status);
  13111. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13112. std::string last_modified = res1->get_header_value("Last-Modified");
  13113. // Range request with matching If-Range (date): should get 206
  13114. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13115. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13116. ASSERT_TRUE(res2);
  13117. EXPECT_EQ(206, res2->status);
  13118. EXPECT_EQ("FGHIJ", res2->body);
  13119. // Range request with old If-Range date: should get 200 (full content)
  13120. Headers h3 = {{"Range", "bytes=5-9"},
  13121. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13122. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13123. ASSERT_TRUE(res3);
  13124. EXPECT_EQ(200, res3->status);
  13125. EXPECT_EQ(content, res3->body);
  13126. // Range request with future If-Range date: should get 206
  13127. Headers h4 = {{"Range", "bytes=0-4"},
  13128. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13129. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13130. ASSERT_TRUE(res4);
  13131. EXPECT_EQ(206, res4->status);
  13132. EXPECT_EQ("ABCDE", res4->body);
  13133. svr.stop();
  13134. t.join();
  13135. std::remove(fname);
  13136. }
  13137. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13138. using namespace httplib;
  13139. const char *fname = "etag_malformed.txt";
  13140. const char *content = "malformed-etag";
  13141. {
  13142. std::ofstream ofs(fname);
  13143. ofs << content;
  13144. ASSERT_TRUE(ofs.good());
  13145. }
  13146. Server svr;
  13147. svr.set_mount_point("/static", ".");
  13148. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13149. svr.wait_until_ready();
  13150. Client cli(HOST, PORT);
  13151. // baseline: should get 200 and an ETag
  13152. auto res1 = cli.Get("/static/etag_malformed.txt");
  13153. ASSERT_TRUE(res1);
  13154. ASSERT_EQ(200, res1->status);
  13155. ASSERT_TRUE(res1->has_header("ETag"));
  13156. // Malformed ETag value (missing quotes) should be treated as non-matching
  13157. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13158. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13159. ASSERT_TRUE(res_bad);
  13160. EXPECT_EQ(200, res_bad->status);
  13161. // Whitespace-only header value should be considered invalid / non-matching
  13162. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13163. "Host: localhost\r\n"
  13164. "If-None-Match: \r\n"
  13165. "Connection: close\r\n"
  13166. "\r\n";
  13167. std::string out;
  13168. ASSERT_TRUE(send_request(5, raw_req, &out));
  13169. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13170. svr.stop();
  13171. t.join();
  13172. std::remove(fname);
  13173. }
  13174. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13175. using namespace httplib;
  13176. const char *fname = "ims_invalid_format.txt";
  13177. const char *content = "ims-bad-format";
  13178. {
  13179. std::ofstream ofs(fname);
  13180. ofs << content;
  13181. ASSERT_TRUE(ofs.good());
  13182. }
  13183. Server svr;
  13184. svr.set_mount_point("/static", ".");
  13185. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13186. svr.wait_until_ready();
  13187. Client cli(HOST, PORT);
  13188. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13189. ASSERT_TRUE(res1);
  13190. ASSERT_EQ(200, res1->status);
  13191. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13192. // If-Modified-Since with invalid format should not result in 304
  13193. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13194. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13195. ASSERT_TRUE(res_bad);
  13196. EXPECT_EQ(200, res_bad->status);
  13197. // If-Range with invalid date format should be treated as mismatch -> full
  13198. // content (200)
  13199. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13200. {"If-Range", "invalid-date"}};
  13201. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13202. ASSERT_TRUE(res_ifrange);
  13203. EXPECT_EQ(200, res_ifrange->status);
  13204. svr.stop();
  13205. t.join();
  13206. std::remove(fname);
  13207. }
  13208. TEST(ETagTest, IfRangeWithMalformedETag) {
  13209. using namespace httplib;
  13210. const char *fname = "ifrange_malformed.txt";
  13211. const std::string content = "0123456789";
  13212. {
  13213. std::ofstream ofs(fname);
  13214. ofs << content;
  13215. ASSERT_TRUE(ofs.good());
  13216. }
  13217. Server svr;
  13218. svr.set_mount_point("/static", ".");
  13219. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13220. svr.wait_until_ready();
  13221. Client cli(HOST, PORT);
  13222. // First request: get ETag
  13223. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13224. ASSERT_TRUE(res1);
  13225. ASSERT_EQ(200, res1->status);
  13226. ASSERT_TRUE(res1->has_header("ETag"));
  13227. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13228. // full content (200)
  13229. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13230. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13231. ASSERT_TRUE(res2);
  13232. EXPECT_EQ(200, res2->status);
  13233. EXPECT_EQ(content, res2->body);
  13234. svr.stop();
  13235. t.join();
  13236. std::remove(fname);
  13237. }
  13238. TEST(ETagTest, ExtremeLargeDateValues) {
  13239. using namespace httplib;
  13240. const char *fname = "ims_extreme_date.txt";
  13241. const char *content = "ims-extreme-date";
  13242. {
  13243. std::ofstream ofs(fname);
  13244. ofs << content;
  13245. ASSERT_TRUE(ofs.good());
  13246. }
  13247. Server svr;
  13248. svr.set_mount_point("/static", ".");
  13249. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13250. svr.wait_until_ready();
  13251. Client cli(HOST, PORT);
  13252. auto res1 = cli.Get(std::string("/static/") + fname);
  13253. ASSERT_TRUE(res1);
  13254. ASSERT_EQ(200, res1->status);
  13255. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13256. // Extremely large year that may overflow date parsing routines.
  13257. Headers h_large_date = {
  13258. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13259. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13260. ASSERT_TRUE(res_bad);
  13261. // Expect server to treat this as invalid/mismatch and return full content
  13262. EXPECT_EQ(200, res_bad->status);
  13263. // If-Range with extremely large date should be treated as mismatch -> full
  13264. // content (200)
  13265. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13266. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13267. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13268. ASSERT_TRUE(res_ifrange);
  13269. EXPECT_EQ(200, res_ifrange->status);
  13270. svr.stop();
  13271. t.join();
  13272. std::remove(fname);
  13273. }
  13274. TEST(ETagTest, NegativeFileModificationTime) {
  13275. using namespace httplib;
  13276. const char *fname = "ims_negative_mtime.txt";
  13277. const std::string content = "negative-mtime";
  13278. {
  13279. std::ofstream ofs(fname);
  13280. ofs << content;
  13281. ASSERT_TRUE(ofs.good());
  13282. }
  13283. // Try to set file mtime to a negative value. This may fail on some
  13284. // platforms/filesystems; if it fails, the test will still verify server
  13285. // behaves safely by performing a regular conditional request.
  13286. #if defined(__APPLE__) || defined(__linux__)
  13287. bool set_negative = false;
  13288. do {
  13289. struct timeval times[2];
  13290. // access time: now
  13291. times[0].tv_sec = time(nullptr);
  13292. times[0].tv_usec = 0;
  13293. // modification time: negative (e.g., -1)
  13294. times[1].tv_sec = -1;
  13295. times[1].tv_usec = 0;
  13296. if (utimes(fname, times) == 0) { set_negative = true; }
  13297. } while (0);
  13298. #else
  13299. bool set_negative = false;
  13300. #endif
  13301. Server svr;
  13302. svr.set_mount_point("/static", ".");
  13303. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13304. svr.wait_until_ready();
  13305. Client cli(HOST, PORT);
  13306. auto res1 = cli.Get(std::string("/static/") + fname);
  13307. ASSERT_TRUE(res1);
  13308. ASSERT_EQ(200, res1->status);
  13309. bool has_last_modified = res1->has_header("Last-Modified");
  13310. std::string last_modified;
  13311. if (has_last_modified) {
  13312. last_modified = res1->get_header_value("Last-Modified");
  13313. }
  13314. if (set_negative) {
  13315. // If we successfully set a negative mtime, ensure server returns a
  13316. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13317. // with an old date and ensure server handles it without crash.
  13318. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13319. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13320. ASSERT_TRUE(res2);
  13321. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13322. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13323. } else {
  13324. // Could not set negative mtime on this platform; fall back to verifying
  13325. // that normal invalid/malformed dates are treated safely (non-304).
  13326. Headers h_bad_date = {
  13327. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13328. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13329. ASSERT_TRUE(res_bad);
  13330. EXPECT_EQ(200, res_bad->status);
  13331. }
  13332. svr.stop();
  13333. t.join();
  13334. std::remove(fname);
  13335. }
  13336. //==============================================================================
  13337. // SSE Parsing Tests
  13338. //==============================================================================
  13339. class SSEParsingTest : public ::testing::Test {
  13340. protected:
  13341. // Test helper that mimics SSE parsing behavior
  13342. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13343. int &retry_ms) {
  13344. // Blank line signals end of event
  13345. if (line.empty() || line == "\r") { return true; }
  13346. // Lines starting with ':' are comments (ignored)
  13347. if (!line.empty() && line[0] == ':') { return false; }
  13348. // Find the colon separator
  13349. auto colon_pos = line.find(':');
  13350. if (colon_pos == std::string::npos) {
  13351. // Line with no colon is treated as field name with empty value
  13352. return false;
  13353. }
  13354. std::string field = line.substr(0, colon_pos);
  13355. std::string value;
  13356. // Value starts after colon, skip optional single space
  13357. if (colon_pos + 1 < line.size()) {
  13358. size_t value_start = colon_pos + 1;
  13359. if (line[value_start] == ' ') { value_start++; }
  13360. value = line.substr(value_start);
  13361. // Remove trailing \r if present
  13362. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13363. }
  13364. // Handle known fields
  13365. if (field == "event") {
  13366. msg.event = value;
  13367. } else if (field == "data") {
  13368. // Multiple data lines are concatenated with newlines
  13369. if (!msg.data.empty()) { msg.data += "\n"; }
  13370. msg.data += value;
  13371. } else if (field == "id") {
  13372. // Empty id is valid (clears the last event ID)
  13373. msg.id = value;
  13374. } else if (field == "retry") {
  13375. // Parse retry interval in milliseconds
  13376. {
  13377. int v = 0;
  13378. auto res =
  13379. detail::from_chars(value.data(), value.data() + value.size(), v);
  13380. if (res.ec == std::errc{}) { retry_ms = v; }
  13381. }
  13382. }
  13383. // Unknown fields are ignored per SSE spec
  13384. return false;
  13385. }
  13386. };
  13387. // Test: Single-line data
  13388. TEST_F(SSEParsingTest, SingleLineData) {
  13389. sse::SSEMessage msg;
  13390. int retry_ms = 3000;
  13391. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13392. EXPECT_EQ(msg.data, "hello");
  13393. EXPECT_EQ(msg.event, "message");
  13394. // Blank line ends event
  13395. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13396. }
  13397. // Test: Multi-line data
  13398. TEST_F(SSEParsingTest, MultiLineData) {
  13399. sse::SSEMessage msg;
  13400. int retry_ms = 3000;
  13401. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13402. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13403. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13404. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13405. }
  13406. // Test: Custom event types
  13407. TEST_F(SSEParsingTest, CustomEventType) {
  13408. sse::SSEMessage msg;
  13409. int retry_ms = 3000;
  13410. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13411. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13412. EXPECT_EQ(msg.event, "update");
  13413. EXPECT_EQ(msg.data, "payload");
  13414. }
  13415. // Test: Event ID handling
  13416. TEST_F(SSEParsingTest, EventIdHandling) {
  13417. sse::SSEMessage msg;
  13418. int retry_ms = 3000;
  13419. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13420. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13421. EXPECT_EQ(msg.id, "12345");
  13422. }
  13423. // Test: Empty event ID (clears last event ID)
  13424. TEST_F(SSEParsingTest, EmptyEventId) {
  13425. sse::SSEMessage msg;
  13426. msg.id = "previous";
  13427. int retry_ms = 3000;
  13428. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13429. EXPECT_EQ(msg.id, "");
  13430. }
  13431. // Test: Retry field parsing
  13432. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13433. sse::SSEMessage msg;
  13434. int retry_ms = 3000;
  13435. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13436. EXPECT_EQ(retry_ms, 5000);
  13437. }
  13438. // Test: Invalid retry value
  13439. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13440. sse::SSEMessage msg;
  13441. int retry_ms = 3000;
  13442. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13443. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13444. }
  13445. // Test: Comments (lines starting with :)
  13446. TEST_F(SSEParsingTest, CommentsIgnored) {
  13447. sse::SSEMessage msg;
  13448. int retry_ms = 3000;
  13449. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13450. EXPECT_EQ(msg.data, "");
  13451. EXPECT_EQ(msg.event, "message");
  13452. }
  13453. // Test: Colon in value
  13454. TEST_F(SSEParsingTest, ColonInValue) {
  13455. sse::SSEMessage msg;
  13456. int retry_ms = 3000;
  13457. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13458. EXPECT_EQ(msg.data, "hello:world:test");
  13459. }
  13460. // Test: Line with no colon (field name only)
  13461. TEST_F(SSEParsingTest, FieldNameOnly) {
  13462. sse::SSEMessage msg;
  13463. int retry_ms = 3000;
  13464. // According to SSE spec, this is treated as field name with empty value
  13465. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13466. // Since we don't recognize "data" without colon, data should be empty
  13467. EXPECT_EQ(msg.data, "");
  13468. }
  13469. // Test: Trailing \r handling
  13470. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13471. sse::SSEMessage msg;
  13472. int retry_ms = 3000;
  13473. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13474. EXPECT_EQ(msg.data, "hello");
  13475. }
  13476. // Test: Unknown fields ignored
  13477. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13478. sse::SSEMessage msg;
  13479. int retry_ms = 3000;
  13480. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13481. EXPECT_EQ(msg.data, "");
  13482. EXPECT_EQ(msg.event, "message");
  13483. }
  13484. // Test: Space after colon is optional
  13485. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13486. sse::SSEMessage msg1, msg2;
  13487. int retry_ms = 3000;
  13488. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13489. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13490. EXPECT_EQ(msg1.data, "hello");
  13491. EXPECT_EQ(msg2.data, "hello");
  13492. }
  13493. // Test: SSEMessage clear
  13494. TEST_F(SSEParsingTest, MessageClear) {
  13495. sse::SSEMessage msg;
  13496. msg.event = "custom";
  13497. msg.data = "some data";
  13498. msg.id = "123";
  13499. msg.clear();
  13500. EXPECT_EQ(msg.event, "message");
  13501. EXPECT_EQ(msg.data, "");
  13502. EXPECT_EQ(msg.id, "");
  13503. }
  13504. // Test: Complete event parsing
  13505. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13506. sse::SSEMessage msg;
  13507. int retry_ms = 3000;
  13508. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13509. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13510. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13511. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13512. // Blank line ends event
  13513. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13514. EXPECT_EQ(msg.event, "notification");
  13515. EXPECT_EQ(msg.id, "evt-42");
  13516. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13517. EXPECT_EQ(retry_ms, 1000);
  13518. }
  13519. //==============================================================================
  13520. // Integration Tests with Server
  13521. //==============================================================================
  13522. class SSEIntegrationTest : public ::testing::Test {
  13523. protected:
  13524. void SetUp() override {
  13525. stop_server_.store(false);
  13526. events_.clear();
  13527. server_ = httplib::detail::make_unique<Server>();
  13528. setup_server();
  13529. start_server();
  13530. }
  13531. void TearDown() override {
  13532. stop_server_.store(true);
  13533. event_cv_.notify_all();
  13534. server_->stop();
  13535. if (server_thread_.joinable()) { server_thread_.join(); }
  13536. }
  13537. void setup_server() {
  13538. // Simple SSE endpoint
  13539. server_->Get("/events", [this](const Request &req, Response &res) {
  13540. auto last_id = req.get_header_value("Last-Event-ID");
  13541. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13542. res.set_chunked_content_provider(
  13543. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13544. std::unique_lock<std::mutex> lock(event_mutex_);
  13545. if (event_cv_.wait_for(
  13546. lock, std::chrono::milliseconds(200), [this] {
  13547. return !events_.empty() || stop_server_.load();
  13548. })) {
  13549. if (stop_server_.load()) { return false; }
  13550. if (!events_.empty()) {
  13551. std::string event = events_.front();
  13552. events_.erase(events_.begin());
  13553. sink.write(event.data(), event.size());
  13554. return true;
  13555. }
  13556. }
  13557. return !stop_server_.load();
  13558. });
  13559. });
  13560. // Endpoint that returns error
  13561. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13562. res.status = 500;
  13563. res.set_content("Internal Server Error", "text/plain");
  13564. });
  13565. // Endpoint for custom event types
  13566. server_->Get("/custom-events", [](const Request &, Response &res) {
  13567. res.set_chunked_content_provider(
  13568. "text/event-stream", [](size_t offset, DataSink &sink) {
  13569. if (offset == 0) {
  13570. std::string event = "event: update\ndata: updated\n\n"
  13571. "event: delete\ndata: deleted\n\n";
  13572. sink.write(event.data(), event.size());
  13573. }
  13574. return false; // End stream after sending
  13575. });
  13576. });
  13577. }
  13578. void start_server() {
  13579. port_ = server_->bind_to_any_port(HOST);
  13580. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13581. // Wait for server to start
  13582. while (!server_->is_running()) {
  13583. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13584. }
  13585. }
  13586. int get_port() const { return port_; }
  13587. void send_event(const std::string &event) {
  13588. std::lock_guard<std::mutex> lock(event_mutex_);
  13589. events_.push_back(event);
  13590. event_cv_.notify_all();
  13591. }
  13592. std::unique_ptr<Server> server_;
  13593. std::thread server_thread_;
  13594. std::mutex event_mutex_;
  13595. std::condition_variable event_cv_;
  13596. std::vector<std::string> events_;
  13597. std::atomic<bool> stop_server_{false};
  13598. std::string last_received_event_id_;
  13599. int port_ = 0;
  13600. };
  13601. // Test: Successful connection and on_open callback
  13602. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13603. // Add a simple endpoint that sends one event and closes
  13604. server_->Get("/simple-event", [](const Request &, Response &res) {
  13605. res.set_chunked_content_provider(
  13606. "text/event-stream", [](size_t offset, DataSink &sink) {
  13607. if (offset == 0) {
  13608. std::string event = "data: hello\n\n";
  13609. sink.write(event.data(), event.size());
  13610. }
  13611. return false; // Close stream after sending
  13612. });
  13613. });
  13614. Client client("localhost", get_port());
  13615. sse::SSEClient sse(client, "/simple-event");
  13616. std::atomic<bool> open_called{false};
  13617. std::atomic<bool> message_received{false};
  13618. sse.on_open([&open_called]() { open_called.store(true); });
  13619. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13620. if (msg.data == "hello") { message_received.store(true); }
  13621. });
  13622. sse.set_reconnect_interval(100);
  13623. sse.set_max_reconnect_attempts(1);
  13624. // Start async
  13625. sse.start_async();
  13626. // Wait for message to be processed
  13627. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13628. sse.stop();
  13629. EXPECT_TRUE(open_called.load());
  13630. EXPECT_TRUE(message_received.load());
  13631. }
  13632. // Test: on_message callback
  13633. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13634. // Endpoint that sends multiple events then closes
  13635. server_->Get("/multi-event", [](const Request &, Response &res) {
  13636. res.set_chunked_content_provider(
  13637. "text/event-stream", [](size_t offset, DataSink &sink) {
  13638. if (offset == 0) {
  13639. std::string events = "data: message1\n\ndata: message2\n\n";
  13640. sink.write(events.data(), events.size());
  13641. }
  13642. return false;
  13643. });
  13644. });
  13645. Client client("localhost", get_port());
  13646. sse::SSEClient sse(client, "/multi-event");
  13647. std::vector<std::string> received_messages;
  13648. std::mutex messages_mutex;
  13649. sse.on_message([&](const sse::SSEMessage &msg) {
  13650. std::lock_guard<std::mutex> lock(messages_mutex);
  13651. received_messages.push_back(msg.data);
  13652. });
  13653. sse.set_reconnect_interval(100);
  13654. sse.set_max_reconnect_attempts(1);
  13655. sse.start_async();
  13656. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13657. sse.stop();
  13658. std::lock_guard<std::mutex> lock(messages_mutex);
  13659. EXPECT_GE(received_messages.size(), 2u);
  13660. if (received_messages.size() >= 2) {
  13661. EXPECT_EQ(received_messages[0], "message1");
  13662. EXPECT_EQ(received_messages[1], "message2");
  13663. }
  13664. }
  13665. // Test: on_event for specific types
  13666. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13667. Client client("localhost", get_port());
  13668. sse::SSEClient sse(client, "/custom-events");
  13669. std::atomic<bool> update_received{false};
  13670. std::atomic<bool> delete_received{false};
  13671. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13672. if (msg.data == "updated") { update_received.store(true); }
  13673. });
  13674. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13675. if (msg.data == "deleted") { delete_received.store(true); }
  13676. });
  13677. sse.set_max_reconnect_attempts(1);
  13678. sse.start_async();
  13679. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13680. sse.stop();
  13681. EXPECT_TRUE(update_received.load());
  13682. EXPECT_TRUE(delete_received.load());
  13683. }
  13684. // Test: on_error callback on connection failure
  13685. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13686. // Connect to a non-existent port
  13687. Client client("localhost", 59999);
  13688. sse::SSEClient sse(client, "/events");
  13689. std::atomic<bool> error_called{false};
  13690. Error received_error = Error::Success;
  13691. sse.on_error([&](Error err) {
  13692. error_called.store(true);
  13693. received_error = err;
  13694. });
  13695. sse.set_reconnect_interval(50);
  13696. sse.set_max_reconnect_attempts(1);
  13697. sse.start_async();
  13698. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13699. sse.stop();
  13700. EXPECT_TRUE(error_called.load());
  13701. EXPECT_NE(received_error, Error::Success);
  13702. }
  13703. // Test: Last-Event-ID header sent on reconnect
  13704. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13705. // Endpoint that sends event with ID
  13706. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13707. res.set_chunked_content_provider(
  13708. "text/event-stream", [](size_t offset, DataSink &sink) {
  13709. if (offset == 0) {
  13710. std::string event = "id: evt-123\ndata: test\n\n";
  13711. sink.write(event.data(), event.size());
  13712. }
  13713. return false;
  13714. });
  13715. });
  13716. Client client("localhost", get_port());
  13717. sse::SSEClient sse(client, "/event-with-id");
  13718. std::atomic<bool> id_received{false};
  13719. sse.on_message([&](const sse::SSEMessage &msg) {
  13720. if (!msg.id.empty()) { id_received.store(true); }
  13721. });
  13722. sse.set_reconnect_interval(100);
  13723. sse.set_max_reconnect_attempts(1);
  13724. sse.start_async();
  13725. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13726. sse.stop();
  13727. EXPECT_TRUE(id_received.load());
  13728. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13729. }
  13730. // Test: Manual stop
  13731. TEST_F(SSEIntegrationTest, ManualStop) {
  13732. // Endpoint that sends one event and stays open briefly
  13733. std::atomic<bool> handler_running{true};
  13734. server_->Get("/stay-open", [&handler_running](const Request &,
  13735. Response &res) {
  13736. res.set_chunked_content_provider(
  13737. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13738. if (offset == 0) {
  13739. std::string event = "data: connected\n\n";
  13740. sink.write(event.data(), event.size());
  13741. }
  13742. // Keep connection open while handler_running is true
  13743. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13744. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13745. }
  13746. return false;
  13747. });
  13748. });
  13749. Client client("localhost", get_port());
  13750. sse::SSEClient sse(client, "/stay-open");
  13751. std::atomic<bool> connected{false};
  13752. sse.on_open([&connected]() { connected.store(true); });
  13753. sse.set_reconnect_interval(100);
  13754. sse.set_max_reconnect_attempts(1);
  13755. sse.start_async();
  13756. // Wait for connection to establish
  13757. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13758. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13759. }
  13760. EXPECT_TRUE(connected.load());
  13761. EXPECT_TRUE(sse.is_connected());
  13762. // Signal handler to stop
  13763. handler_running.store(false);
  13764. // Stop SSE client
  13765. sse.stop();
  13766. EXPECT_FALSE(sse.is_connected());
  13767. }
  13768. // Test: SSEClient with custom headers
  13769. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13770. // Setup a server endpoint that checks for custom header
  13771. std::atomic<bool> header_received{false};
  13772. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13773. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13774. header_received.store(true);
  13775. }
  13776. res.set_chunked_content_provider("text/event-stream",
  13777. [](size_t, DataSink &) { return false; });
  13778. });
  13779. Client client("localhost", get_port());
  13780. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13781. sse::SSEClient sse(client, "/header-check", headers);
  13782. sse.set_max_reconnect_attempts(1);
  13783. sse.start_async();
  13784. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13785. sse.stop();
  13786. EXPECT_TRUE(header_received.load());
  13787. }
  13788. // Test: Reconnect interval configuration
  13789. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13790. Client client("localhost", get_port());
  13791. sse::SSEClient sse(client, "/events");
  13792. auto &result = sse.set_reconnect_interval(500);
  13793. // Builder pattern should return reference to self
  13794. EXPECT_EQ(&result, &sse);
  13795. }
  13796. // Test: Max reconnect attempts
  13797. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13798. // Connect to non-existent port to force reconnects
  13799. Client client("localhost", 59998);
  13800. sse::SSEClient sse(client, "/events");
  13801. std::atomic<int> error_count{0};
  13802. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13803. sse.set_reconnect_interval(50);
  13804. sse.set_max_reconnect_attempts(2);
  13805. auto start = std::chrono::steady_clock::now();
  13806. sse.start(); // Blocking call
  13807. auto end = std::chrono::steady_clock::now();
  13808. // Should have stopped after 2 failed attempts
  13809. EXPECT_GE(error_count.load(), 2);
  13810. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13811. auto duration =
  13812. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13813. #ifdef _WIN32
  13814. // Windows is much slower for socket connection failures
  13815. EXPECT_LT(duration.count(), 7000);
  13816. #else
  13817. EXPECT_LT(duration.count(), 1000);
  13818. #endif
  13819. }
  13820. // Test: Multi-line data in integration
  13821. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13822. // Endpoint with multi-line data
  13823. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13824. res.set_chunked_content_provider(
  13825. "text/event-stream", [](size_t offset, DataSink &sink) {
  13826. if (offset == 0) {
  13827. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13828. sink.write(event.data(), event.size());
  13829. }
  13830. return false;
  13831. });
  13832. });
  13833. Client client("localhost", get_port());
  13834. sse::SSEClient sse(client, "/multiline-data");
  13835. std::string received_data;
  13836. std::mutex data_mutex;
  13837. sse.on_message([&](const sse::SSEMessage &msg) {
  13838. std::lock_guard<std::mutex> lock(data_mutex);
  13839. received_data = msg.data;
  13840. });
  13841. sse.set_reconnect_interval(100);
  13842. sse.set_max_reconnect_attempts(1);
  13843. sse.start_async();
  13844. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13845. sse.stop();
  13846. std::lock_guard<std::mutex> lock(data_mutex);
  13847. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13848. }
  13849. // Test: Auto-reconnect after server disconnection
  13850. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13851. std::atomic<int> connection_count{0};
  13852. std::atomic<int> message_count{0};
  13853. // Endpoint that sends one event and closes, forcing reconnect
  13854. server_->Get("/reconnect-test",
  13855. [&connection_count](const Request &, Response &res) {
  13856. connection_count.fetch_add(1);
  13857. res.set_chunked_content_provider(
  13858. "text/event-stream", [](size_t offset, DataSink &sink) {
  13859. if (offset == 0) {
  13860. std::string event = "data: hello\n\n";
  13861. sink.write(event.data(), event.size());
  13862. }
  13863. return false; // Close connection after sending
  13864. });
  13865. });
  13866. Client client("localhost", get_port());
  13867. sse::SSEClient sse(client, "/reconnect-test");
  13868. sse.on_message([&message_count](const sse::SSEMessage &) {
  13869. message_count.fetch_add(1);
  13870. });
  13871. sse.set_reconnect_interval(100);
  13872. sse.set_max_reconnect_attempts(3);
  13873. sse.start_async();
  13874. // Wait long enough for multiple reconnects
  13875. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13876. sse.stop();
  13877. // Should have connected multiple times (initial + reconnects)
  13878. EXPECT_GE(connection_count.load(), 2);
  13879. // Should have received messages from multiple connections
  13880. EXPECT_GE(message_count.load(), 2);
  13881. }
  13882. // Test: Last-Event-ID sent on reconnect
  13883. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13884. std::atomic<int> connection_count{0};
  13885. std::vector<std::string> received_last_event_ids;
  13886. std::mutex id_mutex;
  13887. // Endpoint that checks Last-Event-ID header and sends event with ID
  13888. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13889. int conn = connection_count.fetch_add(1);
  13890. // Capture the Last-Event-ID header from each connection
  13891. {
  13892. std::lock_guard<std::mutex> lock(id_mutex);
  13893. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13894. }
  13895. res.set_chunked_content_provider(
  13896. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13897. if (offset == 0) {
  13898. std::string event =
  13899. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13900. sink.write(event.data(), event.size());
  13901. }
  13902. return false;
  13903. });
  13904. });
  13905. Client client("localhost", get_port());
  13906. sse::SSEClient sse(client, "/reconnect-with-id");
  13907. sse.set_reconnect_interval(100);
  13908. sse.set_max_reconnect_attempts(3);
  13909. sse.start_async();
  13910. // Wait for at least 2 connections
  13911. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13912. sse.stop();
  13913. // Verify behavior
  13914. std::lock_guard<std::mutex> lock(id_mutex);
  13915. EXPECT_GE(received_last_event_ids.size(), 2u);
  13916. // First connection should have no Last-Event-ID
  13917. if (!received_last_event_ids.empty()) {
  13918. EXPECT_EQ(received_last_event_ids[0], "");
  13919. }
  13920. // Second connection should have Last-Event-ID from first connection
  13921. if (received_last_event_ids.size() >= 2) {
  13922. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13923. }
  13924. }
  13925. // Test: set_headers updates headers used on reconnect
  13926. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13927. std::vector<std::string> received_tokens;
  13928. std::mutex token_mutex;
  13929. // Endpoint that captures Authorization header
  13930. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13931. {
  13932. std::lock_guard<std::mutex> lock(token_mutex);
  13933. received_tokens.push_back(req.get_header_value("Authorization"));
  13934. }
  13935. res.set_chunked_content_provider(
  13936. "text/event-stream", [](size_t offset, DataSink &sink) {
  13937. if (offset == 0) {
  13938. std::string event = "data: hello\n\n";
  13939. sink.write(event.data(), event.size());
  13940. }
  13941. return false; // Close connection to trigger reconnect
  13942. });
  13943. });
  13944. Client client("localhost", get_port());
  13945. Headers headers = {{"Authorization", "Bearer old-token"}};
  13946. sse::SSEClient sse(client, "/auth-check", headers);
  13947. // Update headers on each successful connection
  13948. sse.on_open(
  13949. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13950. sse.set_reconnect_interval(100);
  13951. sse.set_max_reconnect_attempts(3);
  13952. sse.start_async();
  13953. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13954. sse.stop();
  13955. std::lock_guard<std::mutex> lock(token_mutex);
  13956. ASSERT_GE(received_tokens.size(), 2u);
  13957. // First connection uses original header
  13958. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13959. // Second connection uses updated header from set_headers
  13960. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13961. }
  13962. // Test: 401 allows reconnection (so on_error can refresh headers)
  13963. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13964. std::atomic<int> connection_count{0};
  13965. // Endpoint: returns 401 on first attempt, 200 on second
  13966. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13967. int conn = connection_count.fetch_add(1);
  13968. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13969. res.status = StatusCode::Unauthorized_401;
  13970. res.set_content("Unauthorized", "text/plain");
  13971. return;
  13972. }
  13973. res.set_chunked_content_provider(
  13974. "text/event-stream", [](size_t offset, DataSink &sink) {
  13975. if (offset == 0) {
  13976. std::string event = "data: authenticated\n\n";
  13977. sink.write(event.data(), event.size());
  13978. }
  13979. return false;
  13980. });
  13981. });
  13982. Client client("localhost", get_port());
  13983. Headers headers = {{"Authorization", "Bearer expired"}};
  13984. sse::SSEClient sse(client, "/auth-retry", headers);
  13985. std::atomic<bool> message_received{false};
  13986. // Refresh token on error
  13987. sse.on_error(
  13988. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13989. sse.on_message([&](const sse::SSEMessage &msg) {
  13990. if (msg.data == "authenticated") { message_received.store(true); }
  13991. });
  13992. sse.set_reconnect_interval(100);
  13993. sse.set_max_reconnect_attempts(3);
  13994. sse.start_async();
  13995. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13996. sse.stop();
  13997. // Should have reconnected after 401 and succeeded with new token
  13998. EXPECT_GE(connection_count.load(), 2);
  13999. EXPECT_TRUE(message_received.load());
  14000. }
  14001. TEST(Issue2318Test, EmptyHostString) {
  14002. {
  14003. httplib::Client cli_empty("", PORT);
  14004. auto res = cli_empty.Get("/");
  14005. ASSERT_FALSE(res);
  14006. EXPECT_EQ(httplib::Error::Connection, res.error());
  14007. }
  14008. {
  14009. httplib::Client cli(" ", PORT);
  14010. auto res = cli.Get("/");
  14011. ASSERT_FALSE(res);
  14012. EXPECT_EQ(httplib::Error::Connection, res.error());
  14013. }
  14014. }
  14015. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14016. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14017. Server svr;
  14018. // Set a small payload limit (1KB)
  14019. svr.set_payload_max_length(1024);
  14020. svr.Post("/test", [&](const Request &req, Response &res) {
  14021. res.set_content("Body size: " + std::to_string(req.body.size()),
  14022. "text/plain");
  14023. });
  14024. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14025. auto se = detail::scope_exit([&] {
  14026. svr.stop();
  14027. listen_thread.join();
  14028. });
  14029. svr.wait_until_ready();
  14030. // Create data that compresses well but exceeds limit when decompressed
  14031. // 8KB of repeated null bytes compresses to a very small size
  14032. std::string original_data(8 * 1024, '\0');
  14033. // Compress the data using gzip
  14034. std::string compressed_data;
  14035. detail::gzip_compressor compressor;
  14036. compressor.compress(original_data.data(), original_data.size(), true,
  14037. [&](const char *data, size_t size) {
  14038. compressed_data.append(data, size);
  14039. return true;
  14040. });
  14041. // Verify compression worked (compressed should be much smaller)
  14042. ASSERT_LT(compressed_data.size(), original_data.size());
  14043. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14044. // Send compressed data with Content-Encoding: gzip
  14045. Client cli(HOST, PORT);
  14046. Headers headers = {{"Content-Encoding", "gzip"}};
  14047. auto res =
  14048. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14049. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14050. ASSERT_TRUE(res);
  14051. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14052. }
  14053. #endif
  14054. // ============================================================================
  14055. // OpenSSL-Specific Tests
  14056. // ============================================================================
  14057. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14058. X509 *readCertificate(const std::string &strFileName) {
  14059. std::ifstream inStream(strFileName);
  14060. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14061. std::istreambuf_iterator<char>());
  14062. if (strCertPEM.empty()) return (nullptr);
  14063. BIO *pbCert = BIO_new(BIO_s_mem());
  14064. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14065. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14066. BIO_free(pbCert);
  14067. return (pCert);
  14068. }
  14069. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14070. std::ifstream inStream(strFileName);
  14071. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14072. std::istreambuf_iterator<char>());
  14073. if (strPrivateKeyPEM.empty()) return (nullptr);
  14074. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14075. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14076. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14077. BIO_free(pbPrivKey);
  14078. return (pPrivateKey);
  14079. }
  14080. TEST(BindServerTest, UpdateCerts) {
  14081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14082. int port = svr.bind_to_any_port("0.0.0.0");
  14083. ASSERT_TRUE(svr.is_valid());
  14084. ASSERT_TRUE(port > 0);
  14085. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14086. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14087. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14088. ASSERT_TRUE(cert != nullptr);
  14089. ASSERT_TRUE(ca_cert != nullptr);
  14090. ASSERT_TRUE(key != nullptr);
  14091. X509_STORE *cert_store = X509_STORE_new();
  14092. X509_STORE_add_cert(cert_store, ca_cert);
  14093. // svr.update_certs(cert, key, cert_store); // deprecated
  14094. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14095. CLIENT_CA_CERT_FILE);
  14096. ASSERT_TRUE(svr.is_valid());
  14097. svr.stop();
  14098. X509_STORE_free(cert_store);
  14099. X509_free(cert);
  14100. X509_free(ca_cert);
  14101. EVP_PKEY_free(key);
  14102. }
  14103. // Test that update_certs() updates client CA list correctly
  14104. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14105. // Start with file-based constructor
  14106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14107. ASSERT_TRUE(svr.is_valid());
  14108. // Initially no client CA list should be set
  14109. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14110. ASSERT_TRUE(ssl_ctx != nullptr);
  14111. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14112. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14113. EXPECT_EQ(0, count_before);
  14114. // Now update with client CA (PEM string)
  14115. std::string cert_pem, key_pem, ca_pem;
  14116. read_file(SERVER_CERT_FILE, cert_pem);
  14117. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14118. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14119. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14120. ASSERT_TRUE(svr.is_valid());
  14121. // Now client CA list should be set
  14122. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14123. ASSERT_TRUE(ca_list_after != nullptr);
  14124. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14125. }
  14126. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14127. // Test that the file-path SSLServer constructor properly sets the client CA
  14128. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14129. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14130. ASSERT_TRUE(svr.is_valid());
  14131. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14132. ASSERT_TRUE(ssl_ctx != nullptr);
  14133. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14134. ASSERT_TRUE(ca_list != nullptr);
  14135. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14136. }
  14137. #endif
  14138. // ============================================================================
  14139. // MbedTLS-Specific Tests
  14140. // ============================================================================
  14141. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14142. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14143. using namespace httplib::tls;
  14144. // Track if callback was invoked
  14145. bool callback_invoked = false;
  14146. // The callback receives void* ctx which is actually MbedTlsContext*
  14147. // We can access the mbedtls_ssl_config via the context
  14148. auto setup_callback = [&callback_invoked](void *ctx) {
  14149. callback_invoked = true;
  14150. // Cast to MbedTlsContext* to access the ssl config
  14151. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14152. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14153. // Use static variables to hold certificate data (simplified for test)
  14154. static mbedtls_x509_crt own_cert;
  14155. static mbedtls_pk_context own_key;
  14156. static mbedtls_x509_crt ca_chain;
  14157. static bool initialized = false;
  14158. if (!initialized) {
  14159. mbedtls_x509_crt_init(&own_cert);
  14160. mbedtls_pk_init(&own_key);
  14161. mbedtls_x509_crt_init(&ca_chain);
  14162. // Load server certificate
  14163. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14164. return false;
  14165. }
  14166. // Load server private key
  14167. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14168. #if MBEDTLS_VERSION_MAJOR >= 3
  14169. ,
  14170. mbedtls_ctr_drbg_random, nullptr
  14171. #endif
  14172. ) != 0) {
  14173. return false;
  14174. }
  14175. // Load CA chain for client verification
  14176. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14177. return false;
  14178. }
  14179. initialized = true;
  14180. }
  14181. // Configure the SSL config
  14182. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14183. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14184. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14185. // Set minimum TLS version using mbedTLS native API
  14186. #if MBEDTLS_VERSION_MAJOR >= 3
  14187. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14188. #else
  14189. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14190. MBEDTLS_SSL_MINOR_VERSION_3);
  14191. #endif
  14192. return true;
  14193. };
  14194. SSLServer svr(setup_callback);
  14195. ASSERT_TRUE(svr.is_valid());
  14196. ASSERT_TRUE(callback_invoked);
  14197. svr.Get("/test", [&](const Request &req, Response &res) {
  14198. res.set_content("test", "text/plain");
  14199. auto cert = req.peer_cert();
  14200. ASSERT_TRUE(static_cast<bool>(cert));
  14201. auto common_name = cert.subject_cn();
  14202. EXPECT_EQ("Common Name", common_name);
  14203. });
  14204. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14205. auto se = detail::scope_exit([&] {
  14206. svr.stop();
  14207. t.join();
  14208. ASSERT_FALSE(svr.is_running());
  14209. });
  14210. svr.wait_until_ready();
  14211. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14212. cli.enable_server_certificate_verification(false);
  14213. cli.set_connection_timeout(30);
  14214. auto res = cli.Get("/test");
  14215. ASSERT_TRUE(res);
  14216. ASSERT_EQ(StatusCode::OK_200, res->status);
  14217. }
  14218. #endif
  14219. // WebSocket Tests
  14220. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14221. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14222. // defining the meaning of these bits has been negotiated.
  14223. auto make_frame = [](uint8_t first_byte) {
  14224. std::string frame;
  14225. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14226. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14227. frame += "Hello";
  14228. return frame;
  14229. };
  14230. // RSV1 set (0x40)
  14231. {
  14232. detail::BufferStream strm;
  14233. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14234. ws::Opcode opcode;
  14235. std::string payload;
  14236. bool fin;
  14237. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14238. false, 1024));
  14239. }
  14240. // RSV2 set (0x20)
  14241. {
  14242. detail::BufferStream strm;
  14243. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14244. ws::Opcode opcode;
  14245. std::string payload;
  14246. bool fin;
  14247. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14248. false, 1024));
  14249. }
  14250. // RSV3 set (0x10)
  14251. {
  14252. detail::BufferStream strm;
  14253. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14254. ws::Opcode opcode;
  14255. std::string payload;
  14256. bool fin;
  14257. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14258. false, 1024));
  14259. }
  14260. // No RSV bits set - should succeed
  14261. {
  14262. detail::BufferStream strm;
  14263. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14264. ws::Opcode opcode;
  14265. std::string payload;
  14266. bool fin;
  14267. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14268. false, 1024));
  14269. EXPECT_EQ(ws::Opcode::Text, opcode);
  14270. EXPECT_EQ("Hello", payload);
  14271. EXPECT_TRUE(fin);
  14272. }
  14273. }
  14274. TEST(WebSocketTest, ControlFrameValidation) {
  14275. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14276. // payload length <= 125.
  14277. // Ping with FIN=0 - must be rejected
  14278. {
  14279. detail::BufferStream strm;
  14280. std::string frame;
  14281. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14282. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14283. strm.write(frame.data(), frame.size());
  14284. ws::Opcode opcode;
  14285. std::string payload;
  14286. bool fin;
  14287. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14288. false, 1024));
  14289. }
  14290. // Close with FIN=0 - must be rejected
  14291. {
  14292. detail::BufferStream strm;
  14293. std::string frame;
  14294. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14295. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14296. strm.write(frame.data(), frame.size());
  14297. ws::Opcode opcode;
  14298. std::string payload;
  14299. bool fin;
  14300. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14301. false, 1024));
  14302. }
  14303. // Ping with payload_len=126 (extended length) - must be rejected
  14304. {
  14305. detail::BufferStream strm;
  14306. std::string frame;
  14307. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14308. frame += static_cast<char>(126); // payload_len=126 (>125)
  14309. frame += static_cast<char>(0x00); // extended length high byte
  14310. frame += static_cast<char>(126); // extended length low byte
  14311. frame += std::string(126, 'x');
  14312. strm.write(frame.data(), frame.size());
  14313. ws::Opcode opcode;
  14314. std::string payload;
  14315. bool fin;
  14316. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14317. false, 1024));
  14318. }
  14319. // Ping with FIN=1 and payload_len=125 - should succeed
  14320. {
  14321. detail::BufferStream strm;
  14322. std::string frame;
  14323. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14324. frame += static_cast<char>(125); // payload_len=125
  14325. frame += std::string(125, 'x');
  14326. strm.write(frame.data(), frame.size());
  14327. ws::Opcode opcode;
  14328. std::string payload;
  14329. bool fin;
  14330. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14331. false, 1024));
  14332. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14333. EXPECT_EQ(125u, payload.size());
  14334. EXPECT_TRUE(fin);
  14335. }
  14336. }
  14337. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14338. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14339. // length MUST be 0.
  14340. // MSB set - must be rejected
  14341. {
  14342. detail::BufferStream strm;
  14343. std::string frame;
  14344. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14345. frame += static_cast<char>(127); // 64-bit extended length
  14346. frame += static_cast<char>(0x80); // MSB set (invalid)
  14347. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14348. strm.write(frame.data(), frame.size());
  14349. ws::Opcode opcode;
  14350. std::string payload;
  14351. bool fin;
  14352. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14353. false, 1024));
  14354. }
  14355. // MSB clear - should pass length parsing (will be rejected by max_len,
  14356. // but that's a different check; use a small length to verify)
  14357. {
  14358. detail::BufferStream strm;
  14359. std::string frame;
  14360. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14361. frame += static_cast<char>(127); // 64-bit extended length
  14362. frame += std::string(7, '\0'); // high bytes = 0
  14363. frame += static_cast<char>(0x03); // length = 3
  14364. frame += "abc";
  14365. strm.write(frame.data(), frame.size());
  14366. ws::Opcode opcode;
  14367. std::string payload;
  14368. bool fin;
  14369. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14370. false, 1024));
  14371. EXPECT_EQ(ws::Opcode::Text, opcode);
  14372. EXPECT_EQ("abc", payload);
  14373. }
  14374. }
  14375. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14376. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14377. // Valid UTF-8
  14378. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14379. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14380. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14381. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14382. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14383. // Invalid UTF-8
  14384. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14385. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14386. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14387. EXPECT_FALSE(
  14388. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14389. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14390. }
  14391. TEST(WebSocketTest, ConnectAndDisconnect) {
  14392. Server svr;
  14393. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14394. std::string msg;
  14395. while (ws.read(msg)) {}
  14396. });
  14397. auto port = svr.bind_to_any_port(HOST);
  14398. std::thread t([&]() { svr.listen_after_bind(); });
  14399. svr.wait_until_ready();
  14400. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14401. ASSERT_TRUE(client.connect());
  14402. EXPECT_TRUE(client.is_open());
  14403. client.close();
  14404. EXPECT_FALSE(client.is_open());
  14405. svr.stop();
  14406. t.join();
  14407. }
  14408. TEST(WebSocketTest, ValidURL) {
  14409. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14410. EXPECT_TRUE(ws1.is_valid());
  14411. ws::WebSocketClient ws2("ws://example.com/path");
  14412. EXPECT_TRUE(ws2.is_valid());
  14413. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14414. EXPECT_TRUE(ws3.is_valid());
  14415. #ifdef CPPHTTPLIB_SSL_ENABLED
  14416. ws::WebSocketClient wss1("wss://example.com/path");
  14417. EXPECT_TRUE(wss1.is_valid());
  14418. ws::WebSocketClient wss2("wss://example.com:443/path");
  14419. EXPECT_TRUE(wss2.is_valid());
  14420. #endif
  14421. }
  14422. TEST(WebSocketTest, InvalidURL) {
  14423. // No scheme
  14424. ws::WebSocketClient ws1("localhost:8080/path");
  14425. EXPECT_FALSE(ws1.is_valid());
  14426. // No path
  14427. ws::WebSocketClient ws2("ws://localhost:8080");
  14428. EXPECT_FALSE(ws2.is_valid());
  14429. // Empty string
  14430. ws::WebSocketClient ws3("");
  14431. EXPECT_FALSE(ws3.is_valid());
  14432. // Missing host
  14433. ws::WebSocketClient ws4("ws://:8080/path");
  14434. EXPECT_FALSE(ws4.is_valid());
  14435. // Port number overflow — should not crash
  14436. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14437. EXPECT_FALSE(ws5.is_valid());
  14438. // Port out of range
  14439. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14440. EXPECT_FALSE(ws6.is_valid());
  14441. }
  14442. TEST(WebSocketTest, UnsupportedScheme) {
  14443. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14444. ws::WebSocketClient ws1("http://localhost:8080/path");
  14445. EXPECT_FALSE(ws1.is_valid());
  14446. ws::WebSocketClient ws2("https://localhost:8080/path");
  14447. EXPECT_FALSE(ws2.is_valid());
  14448. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14449. EXPECT_FALSE(ws3.is_valid());
  14450. #else
  14451. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14452. std::invalid_argument);
  14453. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14454. std::invalid_argument);
  14455. #endif
  14456. }
  14457. TEST(WebSocketTest, ConnectWhenInvalid) {
  14458. ws::WebSocketClient ws("not a valid url");
  14459. EXPECT_FALSE(ws.is_valid());
  14460. EXPECT_FALSE(ws.connect());
  14461. }
  14462. TEST(WebSocketTest, DefaultPort) {
  14463. ws::WebSocketClient ws1("ws://example.com/path");
  14464. EXPECT_TRUE(ws1.is_valid());
  14465. // ws:// defaults to port 80 (verified by successful parse)
  14466. #ifdef CPPHTTPLIB_SSL_ENABLED
  14467. ws::WebSocketClient ws2("wss://example.com/path");
  14468. EXPECT_TRUE(ws2.is_valid());
  14469. // wss:// defaults to port 443 (verified by successful parse)
  14470. #endif
  14471. }
  14472. TEST(WebSocketTest, IPv6LiteralAddress) {
  14473. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14474. EXPECT_TRUE(ws1.is_valid());
  14475. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14476. EXPECT_TRUE(ws2.is_valid());
  14477. }
  14478. TEST(WebSocketTest, ComplexPath) {
  14479. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14480. EXPECT_TRUE(ws1.is_valid());
  14481. ws::WebSocketClient ws2("ws://localhost:8080/");
  14482. EXPECT_TRUE(ws2.is_valid());
  14483. }
  14484. class WebSocketIntegrationTest : public ::testing::Test {
  14485. protected:
  14486. void SetUp() override {
  14487. server_ = httplib::detail::make_unique<Server>();
  14488. setup_server();
  14489. start_server();
  14490. }
  14491. void TearDown() override {
  14492. server_->stop();
  14493. if (server_thread_.joinable()) { server_thread_.join(); }
  14494. }
  14495. void setup_server() {
  14496. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14497. std::string msg;
  14498. ws::ReadResult ret;
  14499. while ((ret = ws.read(msg))) {
  14500. if (ret == ws::Binary) {
  14501. ws.send(msg.data(), msg.size());
  14502. } else {
  14503. ws.send(msg);
  14504. }
  14505. }
  14506. });
  14507. server_->WebSocket("/ws-echo-string",
  14508. [](const Request &, ws::WebSocket &ws) {
  14509. std::string msg;
  14510. while (ws.read(msg)) {
  14511. ws.send("echo: " + msg);
  14512. }
  14513. });
  14514. server_->WebSocket(
  14515. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14516. // Echo back request metadata
  14517. ws.send("path:" + req.path);
  14518. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14519. std::string msg;
  14520. while (ws.read(msg)) {}
  14521. });
  14522. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14523. std::string msg;
  14524. ws.read(msg); // wait for a message
  14525. ws.close();
  14526. });
  14527. server_->WebSocket("/ws-close-status",
  14528. [](const Request &, ws::WebSocket &ws) {
  14529. std::string msg;
  14530. ws.read(msg); // wait for a message
  14531. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14532. });
  14533. server_->WebSocket(
  14534. "/ws-subprotocol",
  14535. [](const Request &, ws::WebSocket &ws) {
  14536. std::string msg;
  14537. while (ws.read(msg)) {
  14538. ws.send(msg);
  14539. }
  14540. },
  14541. [](const std::vector<std::string> &protocols) -> std::string {
  14542. for (const auto &p : protocols) {
  14543. if (p == "graphql-ws") { return p; }
  14544. }
  14545. return "";
  14546. });
  14547. }
  14548. void start_server() {
  14549. port_ = server_->bind_to_any_port(HOST);
  14550. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14551. server_->wait_until_ready();
  14552. }
  14553. std::unique_ptr<Server> server_;
  14554. std::thread server_thread_;
  14555. int port_ = 0;
  14556. };
  14557. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14558. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14559. "/ws-echo");
  14560. ASSERT_TRUE(client.connect());
  14561. ASSERT_TRUE(client.is_open());
  14562. ASSERT_TRUE(client.send("Hello WebSocket"));
  14563. std::string msg;
  14564. EXPECT_EQ(ws::Text, client.read(msg));
  14565. EXPECT_EQ("Hello WebSocket", msg);
  14566. client.close();
  14567. }
  14568. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14569. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14570. "/ws-echo");
  14571. ASSERT_TRUE(client.connect());
  14572. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14573. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14574. std::string msg;
  14575. EXPECT_EQ(ws::Binary, client.read(msg));
  14576. EXPECT_EQ(binary_data, msg);
  14577. client.close();
  14578. }
  14579. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14580. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14581. "/ws-echo");
  14582. ASSERT_TRUE(client.connect());
  14583. for (int i = 0; i < 10; i++) {
  14584. auto text = "message " + std::to_string(i);
  14585. ASSERT_TRUE(client.send(text));
  14586. std::string msg;
  14587. ASSERT_TRUE(client.read(msg));
  14588. EXPECT_EQ(text, msg);
  14589. }
  14590. client.close();
  14591. }
  14592. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14593. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14594. "/ws-close");
  14595. ASSERT_TRUE(client.connect());
  14596. // Send a message to trigger the server to close
  14597. ASSERT_TRUE(client.send("trigger close"));
  14598. // The server will close, so read should return false
  14599. std::string msg;
  14600. EXPECT_FALSE(client.read(msg));
  14601. EXPECT_FALSE(client.is_open());
  14602. }
  14603. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14604. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14605. "/ws-echo");
  14606. ASSERT_TRUE(client.connect());
  14607. // 128KB message
  14608. std::string large_data(128 * 1024, 'X');
  14609. ASSERT_TRUE(client.send(large_data));
  14610. std::string msg;
  14611. ASSERT_TRUE(client.read(msg));
  14612. EXPECT_EQ(large_data, msg);
  14613. client.close();
  14614. }
  14615. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14616. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14617. "/ws-echo");
  14618. ASSERT_TRUE(client.connect());
  14619. const int num_threads = 4;
  14620. std::vector<std::thread> threads;
  14621. std::atomic<int> send_count{0};
  14622. for (int t = 0; t < num_threads; t++) {
  14623. threads.emplace_back([&client, &send_count, t]() {
  14624. for (int i = 0; i < 5; i++) {
  14625. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14626. if (client.send(text)) { send_count++; }
  14627. }
  14628. });
  14629. }
  14630. for (auto &th : threads) {
  14631. th.join();
  14632. }
  14633. int received = 0;
  14634. std::string msg;
  14635. while (received < send_count.load()) {
  14636. if (!client.read(msg)) { break; }
  14637. received++;
  14638. }
  14639. EXPECT_EQ(send_count.load(), received);
  14640. client.close();
  14641. }
  14642. TEST_F(WebSocketIntegrationTest, ReadString) {
  14643. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14644. "/ws-echo-string");
  14645. ASSERT_TRUE(client.connect());
  14646. ASSERT_TRUE(client.send("hello"));
  14647. std::string msg;
  14648. ASSERT_TRUE(client.read(msg));
  14649. EXPECT_EQ("echo: hello", msg);
  14650. ASSERT_TRUE(client.send("world"));
  14651. ASSERT_TRUE(client.read(msg));
  14652. EXPECT_EQ("echo: world", msg);
  14653. client.close();
  14654. }
  14655. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14656. Headers headers = {{"X-Test-Header", "test-value"}};
  14657. ws::WebSocketClient client(
  14658. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14659. ASSERT_TRUE(client.connect());
  14660. std::string msg;
  14661. ASSERT_TRUE(client.read(msg));
  14662. EXPECT_EQ("path:/ws-request-info", msg);
  14663. ASSERT_TRUE(client.read(msg));
  14664. EXPECT_EQ("header:test-value", msg);
  14665. client.close();
  14666. }
  14667. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14668. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14669. "/ws-echo");
  14670. client.set_read_timeout(1, 0); // 1 second
  14671. ASSERT_TRUE(client.connect());
  14672. // Don't send anything — server echo handler waits for a message,
  14673. // so read() should time out and return false.
  14674. std::string msg;
  14675. EXPECT_FALSE(client.read(msg));
  14676. }
  14677. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14678. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14679. "/ws-echo");
  14680. client.set_read_timeout(5, 0);
  14681. ASSERT_TRUE(client.connect());
  14682. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14683. // The server should reject it and close the connection.
  14684. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14685. client.send(oversized);
  14686. // The server's read() should have failed due to payload limit,
  14687. // so our read() should return false (connection closed).
  14688. std::string msg;
  14689. EXPECT_FALSE(client.read(msg));
  14690. }
  14691. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14692. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14693. "/ws-echo");
  14694. client.set_read_timeout(10, 0);
  14695. ASSERT_TRUE(client.connect());
  14696. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14697. // This should succeed.
  14698. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14699. ASSERT_TRUE(client.send(at_limit));
  14700. std::string msg;
  14701. ASSERT_TRUE(client.read(msg));
  14702. EXPECT_EQ(at_limit.size(), msg.size());
  14703. client.close();
  14704. }
  14705. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14707. "/nonexistent");
  14708. EXPECT_FALSE(client.connect());
  14709. EXPECT_FALSE(client.is_open());
  14710. }
  14711. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14712. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14713. "/ws-echo");
  14714. ASSERT_TRUE(client.connect());
  14715. ASSERT_TRUE(client.send(""));
  14716. std::string msg;
  14717. EXPECT_EQ(ws::Text, client.read(msg));
  14718. EXPECT_EQ("", msg);
  14719. client.close();
  14720. }
  14721. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14723. "/ws-echo");
  14724. // First connection
  14725. ASSERT_TRUE(client.connect());
  14726. ASSERT_TRUE(client.send("first"));
  14727. std::string msg;
  14728. ASSERT_TRUE(client.read(msg));
  14729. EXPECT_EQ("first", msg);
  14730. client.close();
  14731. EXPECT_FALSE(client.is_open());
  14732. // Reconnect using the same client object
  14733. ASSERT_TRUE(client.connect());
  14734. ASSERT_TRUE(client.is_open());
  14735. ASSERT_TRUE(client.send("second"));
  14736. ASSERT_TRUE(client.read(msg));
  14737. EXPECT_EQ("second", msg);
  14738. client.close();
  14739. }
  14740. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14741. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14742. "/ws-close-status");
  14743. ASSERT_TRUE(client.connect());
  14744. // Trigger the server to close with GoingAway status
  14745. ASSERT_TRUE(client.send("trigger"));
  14746. // read() should return false after receiving the close frame
  14747. std::string msg;
  14748. EXPECT_FALSE(client.read(msg));
  14749. EXPECT_FALSE(client.is_open());
  14750. }
  14751. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14752. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14753. "/ws-echo");
  14754. ASSERT_TRUE(client.connect());
  14755. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14756. EXPECT_FALSE(client.is_open());
  14757. }
  14758. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14759. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14760. ws::WebSocketClient client(
  14761. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14762. ASSERT_TRUE(client.connect());
  14763. // Server should have selected graphql-ws
  14764. EXPECT_EQ("graphql-ws", client.subprotocol());
  14765. client.close();
  14766. }
  14767. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14768. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14769. ws::WebSocketClient client(
  14770. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14771. ASSERT_TRUE(client.connect());
  14772. // Server should not have selected any subprotocol
  14773. EXPECT_TRUE(client.subprotocol().empty());
  14774. client.close();
  14775. }
  14776. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14777. // Connect without requesting any subprotocol
  14778. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14779. "/ws-subprotocol");
  14780. ASSERT_TRUE(client.connect());
  14781. EXPECT_TRUE(client.subprotocol().empty());
  14782. client.close();
  14783. }
  14784. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14785. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14786. "/ws-echo");
  14787. client.set_tcp_nodelay(true);
  14788. client.set_connection_timeout(3, 0);
  14789. bool socket_options_called = false;
  14790. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14791. ASSERT_TRUE(client.connect());
  14792. ASSERT_TRUE(client.is_open());
  14793. EXPECT_TRUE(socket_options_called);
  14794. ASSERT_TRUE(client.send("hello"));
  14795. std::string msg;
  14796. auto result = client.read(msg);
  14797. EXPECT_EQ(result, ws::ReadResult::Text);
  14798. EXPECT_EQ(msg, "hello");
  14799. client.close();
  14800. }
  14801. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14802. Server svr;
  14803. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14804. if (!req.has_header("Authorization")) {
  14805. res.status = StatusCode::Unauthorized_401;
  14806. res.set_content("Unauthorized", "text/plain");
  14807. return Server::HandlerResponse::Handled;
  14808. }
  14809. return Server::HandlerResponse::Unhandled;
  14810. });
  14811. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14812. std::string msg;
  14813. while (ws.read(msg)) {
  14814. ws.send(msg);
  14815. }
  14816. });
  14817. auto port = svr.bind_to_any_port("localhost");
  14818. std::thread t([&]() { svr.listen_after_bind(); });
  14819. svr.wait_until_ready();
  14820. // Without Authorization header - should be rejected before upgrade
  14821. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14822. EXPECT_FALSE(client1.connect());
  14823. // With Authorization header - should succeed
  14824. Headers headers = {{"Authorization", "Bearer token123"}};
  14825. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14826. headers);
  14827. ASSERT_TRUE(client2.connect());
  14828. ASSERT_TRUE(client2.send("hello"));
  14829. std::string msg;
  14830. ASSERT_TRUE(client2.read(msg));
  14831. EXPECT_EQ("hello", msg);
  14832. client2.close();
  14833. svr.stop();
  14834. t.join();
  14835. }
  14836. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14837. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14838. protected:
  14839. void SetUp() override {
  14840. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14841. SERVER_PRIVATE_KEY_FILE);
  14842. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14843. std::string msg;
  14844. ws::ReadResult ret;
  14845. while ((ret = ws.read(msg))) {
  14846. if (ret == ws::Binary) {
  14847. ws.send(msg.data(), msg.size());
  14848. } else {
  14849. ws.send(msg);
  14850. }
  14851. }
  14852. });
  14853. port_ = server_->bind_to_any_port(HOST);
  14854. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14855. server_->wait_until_ready();
  14856. }
  14857. void TearDown() override {
  14858. server_->stop();
  14859. if (server_thread_.joinable()) { server_thread_.join(); }
  14860. }
  14861. std::unique_ptr<SSLServer> server_;
  14862. std::thread server_thread_;
  14863. int port_ = 0;
  14864. };
  14865. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14866. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14867. "/ws-echo");
  14868. client.enable_server_certificate_verification(false);
  14869. ASSERT_TRUE(client.connect());
  14870. ASSERT_TRUE(client.is_open());
  14871. ASSERT_TRUE(client.send("Hello WSS"));
  14872. std::string msg;
  14873. EXPECT_EQ(ws::Text, client.read(msg));
  14874. EXPECT_EQ("Hello WSS", msg);
  14875. client.close();
  14876. }
  14877. #endif
  14878. #if !defined(_WIN32)
  14879. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14880. auto secret_dir = std::string("./symlink_test_secret");
  14881. auto served_dir = std::string("./symlink_test_served");
  14882. auto secret_file = secret_dir + "/secret.txt";
  14883. auto symlink_path = served_dir + "/escape";
  14884. // Setup: create directories and files
  14885. mkdir(secret_dir.c_str(), 0755);
  14886. mkdir(served_dir.c_str(), 0755);
  14887. {
  14888. std::ofstream ofs(secret_file);
  14889. ofs << "SECRET_DATA";
  14890. }
  14891. // Create symlink using absolute path so it resolves correctly
  14892. #ifdef PATH_MAX
  14893. char abs_secret[PATH_MAX];
  14894. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14895. #else
  14896. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  14897. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  14898. ASSERT_NE(nullptr, abs_secret);
  14899. #endif
  14900. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14901. auto se = detail::scope_exit([&] {
  14902. unlink(symlink_path.c_str());
  14903. unlink(secret_file.c_str());
  14904. rmdir(served_dir.c_str());
  14905. rmdir(secret_dir.c_str());
  14906. });
  14907. Server svr;
  14908. svr.set_mount_point("/", served_dir);
  14909. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14910. auto se2 = detail::scope_exit([&] {
  14911. svr.stop();
  14912. listen_thread.join();
  14913. });
  14914. svr.wait_until_ready();
  14915. Client cli("localhost", PORT);
  14916. // Symlink pointing outside base dir should be blocked
  14917. auto res = cli.Get("/escape/secret.txt");
  14918. ASSERT_TRUE(res);
  14919. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14920. }
  14921. #endif
  14922. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  14923. // A GET request with Content-Length to a static file handler must have its
  14924. // body drained before the keep-alive connection is reused. Otherwise the
  14925. // unread body bytes are interpreted as the next HTTP request.
  14926. //
  14927. // The body is sent AFTER receiving the first response (as in the original
  14928. // PoC) so that the stream_line_reader cannot buffer it together with the
  14929. // headers of the first request.
  14930. Server svr;
  14931. svr.set_mount_point("/", "./www");
  14932. std::atomic<int> smuggled_count(0);
  14933. svr.Get("/smuggled", [&](const Request &, Response &res) {
  14934. smuggled_count++;
  14935. res.set_content("oops", "text/plain");
  14936. });
  14937. auto port = svr.bind_to_any_port("localhost");
  14938. thread t = thread([&] { svr.listen_after_bind(); });
  14939. auto se = detail::scope_exit([&] {
  14940. svr.stop();
  14941. t.join();
  14942. });
  14943. svr.wait_until_ready();
  14944. auto error = Error::Success;
  14945. auto sock = detail::create_client_socket(
  14946. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  14947. /*connection_timeout_sec=*/2, 0,
  14948. /*read_timeout_sec=*/2, 0,
  14949. /*write_timeout_sec=*/2, 0, std::string(), error);
  14950. ASSERT_NE(INVALID_SOCKET, sock);
  14951. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  14952. // The "smuggled" request will be sent as the body of the outer GET
  14953. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  14954. "Host: localhost\r\n"
  14955. "Connection: close\r\n"
  14956. "\r\n";
  14957. // Step 1: Send only the outer request headers (no body yet)
  14958. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  14959. "Host: localhost\r\n"
  14960. "Content-Length: " +
  14961. std::to_string(smuggled.size()) +
  14962. "\r\n"
  14963. "\r\n";
  14964. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  14965. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  14966. // Step 2: Read the first response (server serves file without reading body)
  14967. std::string first_response;
  14968. char buf[4096];
  14969. for (;;) {
  14970. auto n = recv(sock, buf, sizeof(buf), 0);
  14971. if (n <= 0) break;
  14972. first_response.append(buf, static_cast<size_t>(n));
  14973. // Stop once we have a complete response (headers + body)
  14974. auto hdr_end = first_response.find("\r\n\r\n");
  14975. if (hdr_end != std::string::npos) {
  14976. // Check for Content-Length to know when the body is complete
  14977. auto cl_pos = first_response.find("Content-Length:");
  14978. if (cl_pos != std::string::npos) {
  14979. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  14980. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  14981. auto cl = std::stoul(
  14982. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  14983. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  14984. } else {
  14985. break; // No Content-Length, assume headers-only response
  14986. }
  14987. }
  14988. }
  14989. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  14990. // Step 3: Now send the body, which looks like a new HTTP request.
  14991. // On a vulnerable server the keep-alive loop reads this as a second request.
  14992. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  14993. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  14994. // Step 4: Try to read a second response (should NOT exist after fix)
  14995. std::string second_response;
  14996. for (;;) {
  14997. auto n = recv(sock, buf, sizeof(buf), 0);
  14998. if (n <= 0) break;
  14999. second_response.append(buf, static_cast<size_t>(n));
  15000. }
  15001. // The smuggled request must NOT have been processed
  15002. EXPECT_EQ(0, smuggled_count.load());
  15003. }
  15004. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15005. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15006. // must be rejected with 400 Bad Request.
  15007. Server svr;
  15008. svr.Post("/test", [&](const Request &, Response &res) {
  15009. res.set_content("ok", "text/plain");
  15010. });
  15011. thread t = thread([&] { svr.listen(HOST, PORT); });
  15012. auto se = detail::scope_exit([&] {
  15013. svr.stop();
  15014. t.join();
  15015. ASSERT_FALSE(svr.is_running());
  15016. });
  15017. svr.wait_until_ready();
  15018. // Exact "chunked"
  15019. {
  15020. auto req = "POST /test HTTP/1.1\r\n"
  15021. "Host: localhost\r\n"
  15022. "Content-Length: 5\r\n"
  15023. "Transfer-Encoding: chunked\r\n"
  15024. "Connection: close\r\n"
  15025. "\r\n"
  15026. "hello";
  15027. std::string response;
  15028. ASSERT_TRUE(send_request(1, req, &response));
  15029. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15030. response.substr(0, response.find("\r\n")));
  15031. }
  15032. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15033. {
  15034. auto req = "POST /test HTTP/1.1\r\n"
  15035. "Host: localhost\r\n"
  15036. "Content-Length: 5\r\n"
  15037. "Transfer-Encoding: gzip, chunked\r\n"
  15038. "Connection: close\r\n"
  15039. "\r\n"
  15040. "hello";
  15041. std::string response;
  15042. ASSERT_TRUE(send_request(1, req, &response));
  15043. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15044. response.substr(0, response.find("\r\n")));
  15045. }
  15046. }